In this program, we are adding random numbers that are generated in between 0 and 100.
After every runtime, the result of sum of random numbers is different, i.e., we get a different result for every execution.
The logic we use to calculate the sum of random numbers in between 0 to 100 is −
for(i = 0; i <=99; i++){ // Storing random numbers in an array. num[i] = rand() % 100 + 1; // calculating the sum of the random numbers. sum+= num[i]; }
First, we calculate the sum of random numbers and store that sum in a file. For that open file in write open and append the sum to the array file using fprintf.
fprintf(fptr, "Total sum of the array is %d\n", sum); //appending sum to the array file.
Example
#include<stdio.h> #include<stdlib.h> #include<time.h> #define max 100 // Declaring the main function in the main header. int main(void){ srand(time(0)); int i; int sum = 0, num[max]; FILE *fptr; // Declaring the loop to generate 100 random numbers for(i = 0; i <=99; i++){ // Storing random numbers in an array. num[i] = rand() % 100 + 1; // calculating the sum of the random numbers. sum+= num[i]; } // intializing the file node with the right node. fptr = fopen("numbers.txt", "w"); // cheching if the file pointer is null, check if we are going to exit or not. if(fptr == NULL){ printf("Error!"); exit(1); } fprintf(fptr, "Total sum of the array is %d\n", sum); // appending sum to the array file. fclose(fptr); // closing the file pointer }
Output
Run 1: Total sum of the array is 5224 Run 2: Total sum of the array is 5555 Note: after executing a text file is created in the same folder with number.txt We have to open it; there we can see the sum of random numbers.