While Loops

This program loops to show "pass" or "fail" for each grade.

Notice that the first value is read before the loop and each subsequent value is read as the last thing in the loop. This avoids the problem of the negative value showing "Fail".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//Input grades until a negative grade is entered, count number of passing and number failing
#include <iostream>
using namespace std;
main()
{ int grade, passCount, failCount;
  passCount = 0;
  failCount = 0;
  cout<<"Enter grade: ";
  cin>>grade;
  while (grade >=0)
  {  if (grade >= 60)
     {  cout<<"Pass\n";
	  passCount++;
     } //pass
     else
     {  cout<<"Fail\n";
	  failCount++;
     } //fail
     cout<<"Enter grade: ";
     cin>>grade;
  } //while loop
  cout<<"Number of passing grades: "<<passCount<<"\n";
  cout<<"Number of failing grades: "<<failCount<<"\n";
  return 0;
} //main
CODE

To Do:

  • Run the program in your compiler. Try different sets of numbers.
  • Enter data that will cause the value of count to be 0.
  • What values can end the loop?

NEXT: Finding the smallest and largest