Home  >  Article  >  Backend Development  >  How to calculate the sum of random numbers between 0 and 100 using file in C programming?

How to calculate the sum of random numbers between 0 and 100 using file in C programming?

PHPz
PHPzforward
2023-08-28 18:41:061495browse

How to calculate the sum of random numbers between 0 and 100 using file in C programming?

In this program we add generated random numbers between 0 and 100.

After each run, the result of the sum of random numbers is different, that is, we get different results every time it is executed.

The logic we use to calculate the sum of random numbers between 0 and 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 the file opened in write open and use fprintf to append the sum to the array file.

fprintf(fptr, "Total sum of the array is %d</p><p>", 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</p><p>", 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.

The above is the detailed content of How to calculate the sum of random numbers between 0 and 100 using file in C programming?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete