Home > Backend Development > C++ > 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
Release: 2023-08-28 18:41:06
forward
1556 people have browsed it

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];
}
Copy after login

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.
Copy after login

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
}
Copy after login

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.
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template