C Program to create two files to store even and odd numbers
ALGORITHM :
Step 1: Start
Step 2: Create two empty files named "even_numbers.txt" and "odd_numbers.txt".
Step 3: Open the even_numbers.txt file in write mode as even_file.
Step 4: Open the odd_numbers.txt file in write mode as odd_file.
Step 5: Iterate through numbers from 1 to 100.
Step 6: If the number is even, write it to even_file followed by a newline character.
Step 7: If the number is odd, write it to odd_file followed by a newline character.
Step 8: Close both files after the loop ends.
Step 9: End
SOURCE CODE :
#include <stdio.h>
int main() {
FILE *evenFile, *oddFile;
evenFile = fopen("even.txt", "w");
oddFile = fopen("odd.txt", "w");
if (evenFile == NULL || oddFile == NULL) {
printf("Error opening the files.\n");
return 1;
}
int num;
char choice = 'y';
while (choice == 'y') {
printf("Enter a number: ");
scanf("%d", &num);
if (num % 2 == 0)
fprintf(evenFile, "%d\n", num);
else
fprintf(oddFile, "%d\n", num);
printf("Do you want to enter more numbers? (y/n): ");
getchar(); // To consume the newline character from the previous input
scanf("%c", &choice);
}
fclose(evenFile);
fclose(oddFile);
return 0;
}
OUTPUT :
Before Execution do this :
Files "even.txt" and "odd.txt" will be created with the respective numbers.
Enter a number: 12
Do you want to enter more numbers? (y/n): y
Enter a number: 34
Do you want to enter more numbers? (y/n): y
Enter a number: 6
Do you want to enter more numbers? (y/n): y
Enter a number: 8
Do you want to enter more numbers? (y/n): y
Enter a number: 2
Do you want to enter more numbers? (y/n): y
Enter a number: 9
Do you want to enter more numbers? (y/n): y
Enter a number: 15
Do you want to enter more numbers? (y/n): y
Enter a number: 21
Do you want to enter more numbers? (y/n): n
No comments:
Post a Comment