|
CS256 - Fundamentals of Structured Programming
| Displaying exercises/e6/solution/p3.c
#include <stdio.h>
/**
* Make a program that reads a single character at a time from the input (you
* can use scanf() or getchar() to do this) in a loop and then counts all the
* upper and lower case x's and o's in the input then prints the counts of each.
*
* Example input/output:
* ./p6 < Makefile
* X's = 1, O's = 24
*/
int main(void)
{
char c;
// Make sure the counters are all set to 0's before we begin:
int xs = 0, os = 0;
// We could read a character at a time using getchar as well:
// while ((c = getchar()) != EOF) {
// Read a character from the input, one at a time:
while (scanf("%c",&c) == 1) {
// If it's an 'x' or 'X' increment out xs counter:
if (c == 'x' || c == 'X') xs = xs + 1;
// increment os counter if it's an 'o' or 'O':
if (c == 'o' || c == 'O') os = os + 1;
}
// Print the totals outside of the loop:
printf("X's = %d, O's = %d\n", xs, os);
return 0;
}
|