How to calculate sum of random numbers in between 0 to 100 using files in C Programming?

In this program, we generate random numbers between 0 and 100, calculate their sum, and store the result in a file. The sum will be different on each execution because random numbers are generated based on the current time.

Syntax

FILE *fptr = fopen("filename.txt", "w");
fprintf(fptr, "format_string", value);
fclose(fptr);

Algorithm

The steps to calculate the sum of random numbers and store in a file are −

  1. Generate 100 random numbers between 1 and 100
  2. Calculate the sum of all generated numbers
  3. Open a file in write mode
  4. Write the sum to the file using fprintf()
  5. Close the file

Example

Note: This example creates a file "numbers.txt" in the current directory. Make sure you have write permissions.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100

int main() {
    srand(time(0));  // Seed random number generator
    int i, sum = 0;
    int num[MAX];
    FILE *fptr;
    
    // Generate 100 random numbers and calculate sum
    for(i = 0; i < MAX; i++) {
        num[i] = rand() % 100 + 1;  // Numbers between 1-100
        sum += num[i];
    }
    
    // Open file in write mode
    fptr = fopen("numbers.txt", "w");
    if(fptr == NULL) {
        printf("Error opening file!<br>");
        return 1;
    }
    
    // Write sum to file
    fprintf(fptr, "Total sum of 100 random numbers: %d<br>", sum);
    printf("Sum calculated and saved to numbers.txt<br>");
    printf("Current sum: %d<br>", sum);
    
    fclose(fptr);  // Close file
    return 0;
}

Sample Output

Sum calculated and saved to numbers.txt
Current sum: 5347

File Content (numbers.txt):
Total sum of 100 random numbers: 5347

Key Points

  • Use srand(time(0)) to seed the random number generator with current time
  • Always check if file pointer is NULL before writing to file
  • Use fprintf() to write formatted data to files
  • Always close the file using fclose() after operations
  • The range rand() % 100 + 1 generates numbers from 1 to 100

Conclusion

This program demonstrates file I/O operations in C by generating random numbers, calculating their sum, and storing the result in a text file. Each execution produces different results due to the random number generation.

Updated on: 2026-03-15T13:46:12+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements