Thursday, November 27, 2014

C program to write all the even elements into a file “Even.txt” and all Odd numbers into another file “Odd.txt” from an array

/*.......................................................................................................................................
File : rec24.c
Program : Write a program to write all the even elements into a file “Even.txt” and all Odd numbers into another file “Odd.txt” from an array. Display the same by reading from the file.
Author : sujithbaby440@gmail.com
Date : 22-11-2014
.............................................................................................................................................. */
#include<stdio.h>
#include<stdlib.h>
main()
{
int n,i,num,ecnt=0,ocnt=0;
system("clear");
FILE *fpo,*fpe;
if((fpe=fopen("even.txt","w"))==NULL){
printf("Cannot create file");
exit(1);
}
if((fpo=fopen("odd.txt","w"))==NULL){
printf("cannot create file");
exit(1);
}
printf("Enter the value of n:");
scanf("%d",&n);
printf("Enter %d numbers\n",n);
for(i=1;i<=n;i++){
scanf("%d",&num);
if(num%2==0){
fprintf(fpe,"%d\t",num);
ecnt++;
}
else{
fprintf(fpo,"%d\t",num);
ocnt=ocnt+1;
}
}
fclose(fpe);
fclose(fpo);
if((fpe=fopen("even.txt","r"))==NULL){
printf("Not able to read file");
exit(1);
}
if((fpo=fopen("odd.txt","r"))==NULL){
printf("not able to read file");
exit(1);
}
printf("Even numbers in the array:\n");
for(i=1;i<=ecnt;i++){
fscanf(fpe,"%d",&num);
printf("%d\n",num);
}
printf("Odd numbers in the array:\n");
for(i=1;i<=ocnt;i++){
fscanf(fpo,"%d\t",&num);
printf("%d\t",num);
}
fclose(fpe);
fclose(fpo);
}

OUTPUT:-
Enter the value of n: 5
Enter 5 numbers
44
66
99
88
77
Even numbers in the array:
44
66
88
Odd numbers in the array:
99 77 [141740@localhost ~]$
Enter the value of n: 3
Enter 3 numbers
59
61
64
Even numbers in the array:
64
Odd numbers in the array:
59 61 [141740@localhost ~]$

No comments:

Post a Comment