Digital जीवन

Free Online Education for India...

Full width home advertisement

Computer Basic

C Programming

Engineering Graphics

Post Page Advertisement [Top]

Dr. A.P.J. Abdul Kalam Technical University, Lucknow

KCS151 / KCS251 Programming for Problem Solving - Using C Language


Lab Exercises


40. Write a program to print all the prime numbers, between 1 to 100 in file prime.txt.


/*
 File: Prgrm40.c
 Author: Aditya Saini
 Date: Jan 20, 2021
 Description: Program to print all the prime numbers, between 1 to 100 in file prime.txt.
*/

#include <stdio.h>

int main (void)
{
     FILE *f_ptr;
     char path[256];
     int i, j;

     //Input file path
     printf ("Input file path: ");
     fflush (stdin);
     gets (path);

     //Open file
     f_ptr = fopen (path, "w");
     if (f_ptr == NULL)
     {
          printf ("Error! Unable to save file.");
          return 0;
     }

     for (i = 2; i <= 100; i++)
     {
          //Checking if i is prime or not
          for (j = 2; j < i; j++)
               if (i % j == 0)
                    break;
          if (j == i)
               fprintf (f_ptr, "%d ", i);
     }

     //Close file
     fclose (f_ptr);

     return 0;
};



No comments:

Post a Comment

Please do not post spam links.

Bottom Ad [Post Page]

| Designed by Colorlib