What is this program doing?

What is this program doing?

if i enter a negative number it averages out only the non negative numbers.

if i enter any character other than a number the program goes into a infinite loop


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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    #include <iostream>
using namespace std;
int main()
{
cout<<"This program computes the average of ";
cout<<"a list of (nonnegative) exam scores."<<endl;
        double sum;
        int numberOfStudents;
        double next;
        char answer;
       
        do
        {
          
            cout<<"Enter all the scores to be averaged."<<endl;
            cout<<"Enter a negative number after ";
            cout<<"you have entered all the scores."<<endl;
            sum = 0;
            numberOfStudents = 0;
            cin>>next;
            while (next >= 0)
            {
                sum = sum + next;
                numberOfStudents++;
                cin>>next;
            }
            if (numberOfStudents > 0)
               cout<<"The average is "<<(sum / numberOfStudents)<<endl;
            else
               cout<<"No scores to average."<<endl;
            cout<<"Want to average another exam?"<<endl;
            cout<<"Enter y for Yes or n for no."<<endl;
            cin>>answer;
        }
        while (answer=='y'|| answer=='Y');
    
   
    system ("pause");
    return 0;
}

	

It is a simple C++ Program to generate average of non negative numbers that are inputted by the user.

It generates the average of only non negative numbers because it uses a condition here.
1
2
3
4
5
6
while (next >= 0)
            {
                sum = sum + next;
                numberOfStudents++;
                cin>>next;
            }

This block of code checks for terminating condition which is a negative number.As soon as user inputs a negative number then "next" becomes < 0 and hence while loop terminates which makes that negative number not to be included in "sum".

The do-while loop will only be terminated when user enters (y or Y) in this part of code.
1
2
3
 cout<<"Want to average another exam?"<<endl;
 cout<<"Enter y for Yes or n for no."<<endl;
 cin>>answer;


if user enter any character in between the program, it means assigning an integer variable to a character valueand thus the programs runs out for infinite.

Hope that you got my point.
Topic archived. No new replies allowed.