This blog is under construction

Saturday 29 June 2013

C program to read numbers from a file and write even, odd and prime numbers in separate files

Write a C program to read numbers from a file and write even, odd and prime numbers in separate files.


  #include <stdio.h>
  int main() {
        FILE *fp1, *fp2, *fp3, *fp4;
        int n, i, num, flag = 0;

        /* open data.txt in read mode */
        fp1 = fopen("data.txt", "w");
        printf("Enter the value for n:");
        scanf("%d", &n);
        for (i = 0; i <= n; i++)
                fprintf(fp1, "%d ", i);
        fprintf(fp1, "\n");
        fclose(fp1);

        /* open files to write even, odd and prime nos separately */
        fp1 = fopen("data.txt", "r");
        fp2 = fopen("even.txt", "w");
        fp3 = fopen("odd.txt", "w");
        fp4 = fopen("prime.txt", "w");

        fprintf(fp2, "Even Numbers:\n");
        fprintf(fp3, "Odd Numbers:\n");
        fprintf(fp4, "Prime Numbers:\n");

        /* print even, odd and prime numbers in separate files */
        while (!feof(fp1)) {
                fscanf(fp1, "%d", &num);
                if (num % 2 == 0) {
                        fprintf(fp2, "%d ", num);
                } else {
                        if (num > 1) {
                                for (i = 2; i < num; i++) {
                                        if (num % i == 0) {
                                                flag = 1;
                                                break;
                                        }
                                }
                                if (!flag) {
                                        fprintf(fp4, "%d ", num);
                                }
                        }
                        fprintf(fp3, "%d ", num);
                        flag = 0;
                }
        }
        fprintf(fp2, "\n");
        fprintf(fp3, "\n");
        fprintf(fp4, "\n");

        /* close all opened files */
        fclose(fp1);
        fclose(fp2);
        fclose(fp3);
        fclose(fp4);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:25


  jp@jp-VirtualBox:~/$ cat data.txt 
  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 


  jp@jp-VirtualBox:~/$ cat even.txt 
  Even Numbers:
  0 2 4 6 8 10 12 14 16 18 20 22 24 

  jp@jp-VirtualBox:~/$ cat odd.txt 
  Odd Numbers:
  1 3 5 7 9 11 13 15 17 19 21 23 25 25 

  jp@jp-VirtualBox:~/$ cat prime.txt 
  Prime Numbers:
  3 5 7 11 13 17 19 23 






SEE ALSO

    No comments:

    Post a Comment