C Exercises: Counts the number of characters left in the file
C For Loop: Exercise-60 with Solution
Write a C program that takes user input and counts the number of characters until the end of the file.
Note: On Linux systems and OS X, the character to input to cause an EOF is CTRL+D. For Windows, it's CTRL+Z
This C program takes input from the user until the end of the file (EOF) is encountered and counts the number of characters entered. It prompts the user with instructions on how to signal EOF based on the operating system. Then, it enters a loop where each character input increments a counter variable. Once EOF is detected, it prints the total count of characters entered.
Sample Solution:
C Code:
#include <stdio.h> // Include the standard input/output header file.
int main(void)
{
// Variable declaration and initialization
int ctr = 0;
// Prompting the user for input
printf("\nInput characters: On Linux systems and OS X EOF is CTRL+D. For Windows EOF is CTRL+Z.\n");
// Loop to count characters until EOF (End of File) is encountered
while (getchar() != EOF)
{
ctr++;
}
// Printing the number of characters counted
printf("\nNumber of Characters: %d\n", ctr);
return 0;
}
Output:
Input characters: On Linux systems and OS X EOF is CTRL+D. For Windows EOF is CTRL+Z. Number of Characters: 10
Flowchart:
C Programming Code Editor:
Previous: Check whether an n digits number is Armstrong or not.
Next: Count the upper-case, lower-case and other characters
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming-exercises/for-loop/c-for-loop-exercises-60.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics