কম্পিউটার টিউটোরিয়াল

C প্রোগ্রামিং-এ ফাইল ব্যবহার করে ০ থেকে ১০০ পর্যন্ত র‍্যান্ডম সংখ্যার যোগফল বের করা


এই প্রোগ্রামে ০ থেকে ১০০ পর্যন্ত জেনারেট হওয়া র‍্যান্ডম সংখ্যাগুলো যোগ করা হচ্ছে।


প্রতিটি রানটাইমে র‍্যান্ডম সংখ্যার যোগফলের ফলাফল ভিন্ন হয়, অর্থাৎ প্রতিটি এক্সিকিউশনে ভিন্ন ফলাফল পাওয়া যায়।

০ থেকে ১০০ পর্যন্ত র‍্যান্ডম সংখ্যার যোগফল ক্যালকুলেট করার লজিক—

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];
}

প্রথমে র‍্যান্ডম সংখ্যার যোগফল ক্যালকুলেট করে সেটি ফাইলে স্টোর করা হয়। সেজন্য ফাইল রাইট মোডে খোলা হয় এবং fprintf ব্যবহার করে যোগফল অ্যারে ফাইলে অ্যাপেন্ড করা হয়।

fprintf(fptr, "Total sum of the array is %d\n", sum); // appending sum to the array file.

উদাহরণ

#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
}

আউটপুট

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.

  1. C ভাষায় পয়েন্টার ব্যবহার করে অ্যারে এলিমেন্টের যোগফল বের করার পদ্ধতি

  2. ব্লুটুথ ব্যবহার করে ম্যাক এবং অ্যান্ড্রয়ডের মধ্যে ফাইল ট্রান্সফার করার পদ্ধতি

  3. এক্সেলে দুটি সংখ্যার পারসেন্টেজ ডিফারেন্স বের করার পদ্ধতি

  4. SHAREit দিয়ে ল্যাপটপ ডেটা ট্রান্সফার: দ্রুত, ফ্রি এবং വിശ্বস্ত