Yesterday we learnt about "Character Counting in C" using while loop. Today in order to illustrate the same character counting in C, we will trying using for loop. We will also try to use float or double datatype to store the character count.
Lets get started ....
Above program,
It's very simple but very useful snippet while coding !!
Lets get started ....
#include <stdio.h>
int main()
{
double char_count;
printf("\n Input characters to count \n");
for(char_count = 0; getchar() != '\n'; ++char_count);
printf("\n You have typed %.0f character :) \n",char_count);
return 0;
}
Above program,
- Declares char_count as doube instead of int to make sure that the count is not overflow while taking the input. double takes relatively more time to overflow than int.
- Requests user to input characters
- Reads character by character using getchar() till end of the line
- As you can see, there is no body for for loop here because whole operation of character counting is done in for loop itself. This is the beauty of for loop.
- for loop and while loop they check the condition first and enter their body to execute the code which provides the programmer more flexibility of programming.
- Once a line is entered, program exits by printing the character count.
- One important thing to note here while printing is "%.0f", usually printf uses %f for printing float or double. Since char_count is decalared as double, we use "%.0f" to supress the decimal point and fraction part which is zero.
Now output of this program is..
mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out
Input characters to count
This is single line of input
You have typed 28 character :)
It's very simple but very useful snippet while coding !!
No comments:
Post a Comment