0

I have written a c code to generate random numbers(each time generate a different set of random numbers) and need to ask the user if want to generate another random number. If the user reply yes, the program need to generate another random number; if the user replies No, the program needs to calculate the total and average of the random numbers.

My problem is I don't know how to store the random number and there is a problem with my loops.

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

main() 
{
    int sum=0, i, num[100], arr[100];
    float avg;
    char choice;
    
    srand(time(0));

        for(i=0; i<100; i++)
        {
            arr[i] = rand();
            printf("Random number generated: %d", arr[i]);
            fflush(stdin);
            printf("\nGenerate another random number(y/n)? ");
            scanf("%c", &choice);
            if(choice == 'n' || choice == 'N')
            {
                sum += arr[i];
                avg = sum / i;
        
                printf("\n::TOTAL     : %d", sum);
                printf("\n::AVERAGE   : %.2f", avg); 
            }
        }    
    system("PAUSE");
}

The correct output should be like this: Correct output

  • 2
    Please do not post pictures of code (or, here, expected output), just integrate it to your post like the above code – Adalcar Feb 24 '21 at 10:29
  • 4
    *there is a problem*. Please tell us what specific error or incorrect behaviour you have. *I don't know how to store the random number*. What does that mean? Isn't `arr[i] = rand();` storing the number? – kaylum Feb 24 '21 at 10:31
  • 1
    You gave us the `correct output` but not the `current output`, so there is no way to know what the problem is – Adalcar Feb 24 '21 at 10:33
  • 1
    Don't `fflush(stdin)`: https://stackoverflow.com/questions/2979209/using-fflushstdin – William Pursell Feb 24 '21 at 10:43
  • `scanf("%c", &choice);` --> `scanf(" %c", &choice);` (Add space). Drop `fflush(stdin);` – chux - Reinstate Monica Feb 24 '21 at 10:55

1 Answers1

1

There are several issues with your code:

  1. Add a break at the end of your "No"-condition to get out of the loop in that case.
  2. Accumulate your sum (for the average) outside the "No"-condition.
  3. To store you could simply run another loop for(int j=0; j<=i; ++j) printf("%d\t", arr[j]); and copy the output from the command line - or get yourself familiar with file IO.
  4. By the way: sum is likely to overflow if you accumulate several numbers of the same data type.
André
  • 303
  • 1
  • 8