Counting grade letters using while and switch-case-break for C programming

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Counting grade letters using while and switch-case-break for C programming

To show: How to use the C while, switch-case-break statement to count the grade letters

 

// Counting letter grades using while, switch and multiple case

#include <stdio.h>

 

int main(void)

{

int grade;

int aCount=0,bCount=0,cCount=0,dCount=0,eCount=0,fCount = 0;

 

printf("Enter the letter grades.\n");

printf("Enter the 'S' character to end.\n");

 

while((grade = getchar()) != 'S')

{

// switch nested in while

switch(grade)

{

// grade was uppercase A or lowercase a

case 'A': case 'a': ++aCount;

break;

//grade was uppercase B or lowercase b

case 'B': case 'b': ++bCount;

break;

// grade was uppercase C or lowercase c

case 'C': case 'c': ++cCount;

break;

// grade was uppercase D or lowercase d

case 'D': case 'd': ++dCount;

break;

// grade was uppercase E or lowercase e

case 'E': case 'e': ++eCount;

break;

// grade was uppercase F or lowercase f

case 'F': case 'f': ++fCount;

break;

// ignore these input

case '\n': case ' ': break;

// catch all other characters

default:

{printf("Incorrect letter grade entered.\n");

printf("Enter a new grade.\n");}

break;

}

}

 

// Do the counting...

printf("\nTotals for each letter grade are:\n");

printf("A: %d\n", aCount);

printf("B: %d\n", bCount);

printf("C: %d\n", cCount);

printf("D: %d\n", dCount);

printf("E: %d\n", eCount);

printf("F: %d\n", fCount);

 

return 0;

}

 

Output example:

 

Enter the letter grades.

Enter the 'S' character to end.

abcFedDefCBaEFS

Totals for each letter grade are:

A: 2

B: 2

C: 2

D: 2

E: 3

F: 3

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index