Home > Net >  How can I store different values in a variable each time a loop iterates and then add them all toget
How can I store different values in a variable each time a loop iterates and then add them all toget

Time:04-25

FILE *fp;
    add_stock *a;
    int n, i, j;
    printf("Hover the cursor on the URL and click (ctrl click)  to know the d/b shares and stocks and then later on fill the further information as ask  https://youtu.be/AeEgoc3k_0o");
    printf("Enter the no. of stocks you have purchased : ");
    scanf("%d", &n);

    a = (add_stock *)calloc(n, sizeof(add_stock));
    fp = fopen("myportfolio.txt", "a");

    for (i = 0; i < n; i  )
    {
        a[i].total = 0;
        printf("Enter the name of the company : ");
        scanf(" %[^\n]", a[i].name);

        printf("Enter how many shares you have bought : ");
        scanf("%d", &a[i].share);

        printf("Enter the price of each share : ");
        scanf("%f", &a[i].price);
        fprintf(fp, "\n%s \n%d \n%f", a[i].name, a[i].share, a[i].price);
        a[i].total  = a[i].share * a[i].price;
        fprintf(fp, "\n%f", a[i].total);
    }
    
   
    fclose(fp);

what I want here is that ,I get the sum total of the total amount of money invested by a user. Currently, it's giving me only the total amount of money invested in a specific company . But I also want the total amount of money invested in all the companies .I hope u'll get my point.

CodePudding user response:

Just add another variable

fp = fopen("myportfolio.txt", "a");
int grandTotal = 0;

then in the loop

    a[i].total  = a[i].share * a[i].price;
    grandTotal  = a[i].total;
    fprintf(fp, "\n%f", a[i].total);

CodePudding user response:

    ...

    double portfolio_total_value = 0.0 ; // <<<< Before your input loop
    
    for (i = 0; i < n; i  )
    {
        ...

        a[i].total  = a[i].share * a[i].price;
        portfolio_total_value  = a[i].total ;   // <<<< Accumulate total in the input loop
        ...
    }
    
    // >>> Output the total *after* the input loop <<<<
    fprintf( fp, "\nPortfolio value: %f\n", portfolio_total_value ) ;
  •  Tags:  
  • c
  • Related