-2

Is there anyway i can make use of self defined function in this code? my homework requires me to make use of self defined function, but i am not very good at this, how do i do it? This is a cashier program that ask user for item code of the product they wish to purchase.

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int i,j = 0, code, amt, key, lines = 0;
    int id[100], stock[100], k = 0;
    char name[100][20], product[100], newstock[100];
    float price[100], sum;
    float total = 0;  
    char ipname[100][20];
    int quantity[100], ch;
    float ipprice[100];
    float ipsub[100],pay,balance;

    FILE *fp1;

    fp1 = fopen("Fruit.txt", "r");

    if(fp1 == NULL)
    {
        printf("ERROR in opening file\n");
        return 1;
    }
    else
    {
        while((ch = getc(fp1))!= EOF)
        {
            if(ch == '\n')
                lines++;
        }
    }

    fclose(fp1);

    fp1 = fopen("Fruit.txt","r");

    if(fp1 == NULL)
    {
        printf("ERROR in opening file\n");
        return 1;
    }
    else
    {
        for(i = 0; i < lines; i++)
        {
            fgets(product, sizeof(product), fp1);
            id[i] = atoi(strtok(product, ","));
            strcpy(name[i], strtok(NULL, ","));
            price[i] = atof(strtok(NULL, ","));
            stock[i]=atoi(strtok(NULL,"\n"));
        }
    }

    fclose(fp1);

    FILE *fp3;

    fp3 = fopen("Stock.txt", "r");

    if(fp3!=NULL)
    {
        for(i = 0; i < lines; i++)
        {
            fgets(newstock, sizeof(newstock), fp3);

            id[i] = atoi(strtok(newstock, ","));
            strcpy(name[i], strtok(NULL, ","));
            price[i] = atof(strtok(NULL, ","));
            stock[i] = atoi(strtok(NULL, "\n"));
        }
    }

    fclose(fp3);

    printf("=============================================================\n");

    for(i = 0; i < lines; i++)
    { 
        printf("%d:%-10s\t", i +1, name[i]);
    }

    printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
    printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

    do
    {  
        k = 0;
        system("cls");
        printf("=============================================================\n");

        for(i = 0; i < lines; i++)
        {
            printf("%d:%-10s\t", i +1, name[i]);
        }

        printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
        printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

        if(j > 0)
        {
            for(k = 0; k < j; k++)
            {
                printf("%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
            }
        }

        sum = 0;
        amt = 0;

        printf("\nProduct code:");
        scanf("%d", &code);

        i = code -1;

        if(i < lines && i >= 0)
        {
            printf("Quantity:");
            scanf("%d", &amt);
            stock[i] = stock[i] -amt;

            system("cls");

            sum = price[i] *amt;
            total = total + sum;
            ipprice[j] = price[i];

            strcpy(ipname[j], name[i]);

            quantity[j] = amt;
            ipsub[j] = sum;

            printf("=============================================================\n");

            for(i = 0; i < lines; i++)
            {
                printf("%d:%-10s\t", i +1, name[i]);
            }

            printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
            printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

            for(k = 0; k <= j; k++)
            {
                printf("%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
            }

            printf("\nPress ESC on keyboard to finalize the bill or Press any key continue...\n");

            j++;

            key = _getch();
        }
        else
        {
            system("cls");

            printf("=============================================================\n");

            for(i = 0; i < lines; i++)
            { 
                printf("%d:%-10s\t", i +1, name[i]);
            }

            printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
            printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

            if(j > 0)
            {
                for(k = 0; k < j; k++)
                {
                    printf("%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
                }
            }

            printf("\nInvalid product code entered, press any key to try again or press esc to finalize   bill...\n\n");
        }
    } while(key != 27);

    do
    {
        system("cls");

        printf("=============================================================\n");

        for(i = 0; i < lines; i++)
        {
            printf("%d:%-10s\t",i+1,name[i]);
        }

        printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
        printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

        for(k = 0; k < j; k++)
        {
            printf("%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
        }

        printf("\nGrand Total = RM%.2f\n",total);
        printf("\nPayment = RM");
        scanf("%f", &pay);

        if(pay >= total)
        {
            balance = pay - total;
            printf("\nBalance = RM%.2f\n", balance);
        }
        else
        {
            printf("\nInsufficient payment, Please enter larger amount!\nPress any key...");

            getch();
        }

    }while(pay < total);

    FILE *fp2;
    fp2 = fopen("receipt.txt", "w");

    if(fp1 == NULL)
    {
        printf("ERROR in opening file\n");
        return 1;
    }

    time_t now;
    time(&now);

    fprintf(fp2,"\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
    fprintf(fp2,"%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

    for(k = 0; k < j; k++)
    {
        fprintf(fp2,"%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
    }

    fprintf(fp2,"\n\nGrand Total = RM%.2f\n", total);
    fprintf(fp2,"Payment = RM%.2f\n", pay);
    fprintf(fp2,"Balance = RM%.2f\n", balance);

    fclose(fp2);

    fp3 = fopen("Stock.txt", "w");

    if(fp3 == NULL)
    {
        printf("ERROR in updating stock file\n");
        return 1;
    }
    else
    {
        for(i = 0; i < lines; i++)
        {
            fprintf(fp3,"%d,%s,%.2f,%d\n", id[i], name[i], price[i], stock[i])
        }
    }

    fclose(fp1);

    return 0;
}

content of txt file

18156,Apple,1.49,73
45776,Aprikot,1.59,23
73191,Avocado,2.49,63
72829,Banana,2.99,27
74084,Blueberry,5.49,36
79800,Coconut,3.49,80
16611,Grape,8.99,42
62690,Grapefruit,2.19,34
47089,Guava,4.99,42
70412,Jackfruit,19.99,29
44640,Kiwifruit,2.15,38
94768,Lemon,0.99,42
86240,Mango,3.99,62
78697,Orange,1.69,23
74470,Papaya,4.49,23
23959,Pear,2.49,36
78862,Pineapple,2.99,71
82943,Pomegranate,4.35,19
56180,Pomelo,12.99,72
67712,Starfruit,2.79,59
33974,Strawberry,13.99,31
45584,Watermelon,6.88,21
Vi.
  • 37,014
  • 18
  • 93
  • 148
problematic
  • 31
  • 1
  • 1
  • 6
  • 3
    PLEASEPROVIDEPROPERINDENTATIONSOTHATTHEREADERCANUNDERSTAND!!! – Arpit Aug 24 '14 at 13:51
  • 2
    you have defined main function...it is user defined. Similarly, create other functions and call it from the main. This you will get in any basic book. – Arpit Aug 24 '14 at 13:53
  • **Every** function that you write in this code will be self-defined. Compare against the function `fopen` you are using -- did you write it? Does it appear in this code? – Jongware Aug 24 '14 at 13:55
  • We are talking about a recursive function you? Or You want to split the main function simply. – BLUEPIXY Aug 24 '14 at 14:00
  • i added comments and rearranged the code, hope it helps – problematic Aug 24 '14 at 14:12
  • i don't know how my code can work with self defined, i read my lecture slides but i dont know how can i apply that , those examples involve only simple calculations replacing variable, is that how self defined works??.. – problematic Aug 24 '14 at 14:13
  • the self defined i talking about is something like this void(~~~~~); //prototype (~~~);//call function void(~~~~){~~~}//function definition – problematic Aug 24 '14 at 14:18
  • @BLUEPIXY split the main function i think, involve something like this void(int x , int y, char........) – problematic Aug 24 '14 at 14:19
  • @Arpit i editted the code, i hope its easier to understand now, can you read again to see if there is a chance to write them int self define function, my notes teach us making calculation function, i don't see how it can apply to my code... something like this void function name (variable), but how??? i am confused – problematic Aug 24 '14 at 14:24
  • @Jongware fopen is a built in compiler function, it is not user defined... – problematic Aug 24 '14 at 14:33
  • @BLUEPIXY how do i split the main function?? – problematic Aug 24 '14 at 15:31

1 Answers1

0

First and the most important, Throw out your notes and get yourself a good C programming book. Here The Definitive C Book Guide and List you can find a good list and you can have a good idea.

Just a basic idea about functions. Try to identify the code which you will be requiring again and again and put that code in a function, so that the program will be small, easily understandable and you don't have to write it again.Like, In your code I see that this code is being used number of times:

        printf("=============================================================\n");

        for(i = 0; i < lines; i++)
        { 
            printf("%d:%-10s\t", i +1, name[i]);
        }

        printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
        printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

So put this in a function like this:

void PrintNewBillHeader ()
{
            printf("=============================================================\n");

            for(i = 0; i < lines; i++)
            { 
                printf("%d:%-10s\t", i +1, name[i]);
            }

            printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
            printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");
}

And then wherever you are performing these steps, in place of that just call this function PrntNewBillHeader(). Simple.

In the starting, you are reading data from the file and it has been called twice. So, create a new function ReadFileData() and put the reading code in that function. But here you have to pass the filename and the array in which you want to store the data. So this will be done like this:

int ReadFileData (char * pFileName, char * name, float *pPrice, float *pStock)
{
    /**Do declare the variable to be use in this function**/

    fp1 = fopen("Fruit.txt","r");

    if(fp1 == NULL)
    {
        return -1;
    }
    else
    {
        for(i = 0; i < lines; i++)
        {
            fgets(product, sizeof(product), fp1);
            id[i] = atoi(strtok(product, ","));
            strcpy(name[i], strtok(NULL, ","));
            price[i] = atof(strtok(NULL, ","));
            stock[i]=atoi(strtok(NULL,"\n"));
        }
    }

    fclose(fp1);

    return 1;
}

I hope you must have got a fair amount of idea.

Just try to split the main function by removing one redundant code at a time.

Hope this helps.

Community
  • 1
  • 1
Arpit
  • 767
  • 7
  • 20
  • thanks, do i need to declare variable in the first function? How to call the second function? – problematic Aug 25 '14 at 14:46
  • do i just copy ur code? or i have to add something, What did which didn't work: declare prototype - void PrntNewBillHeader(): call function - PrntNewBillHeader(); function definition - copy and paste exactly – problematic Aug 25 '14 at 14:52
  • Yes you have to declare the variables in the functions. First one you can copy and check what all variables are needed. May be some need to be passed as arguments. What I gave you is just a prototype. Try yourself and then you can post the new problem, if any. – Arpit Aug 25 '14 at 22:25