Can someone help with this assignment for C++? We were just introduced to loops, specifically while loop, do-while loop, for loop, and nested loops.
Write a program that reads a sequence of integers and prints the following:
The number of odd and even numbers of inputs
Use a sentinel value to signal the end of inputs. If the sentinel value is the first you enter, give a message "NO input is entered!".
Input Validation: Do not accept a negative number.

Answer :

teobguan2019

Answer:

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5.    int value;
  6.    int oddCount = 0;
  7.    int evenCount = 0;
  8.    
  9.    cout<<"Input a positive number: ";
  10.    cin>> value;
  11.    
  12.    if(value == -1){
  13.        cout<<"NO input is entered!";
  14.        return 0;
  15.    }
  16.    
  17.    if(value < -1) {
  18.          cout<<"The input number must be positive";
  19.          return 0;
  20.    }
  21.    
  22.    while(value != -1){
  23.        
  24.        if(value % 2 == 0){
  25.            evenCount++;
  26.        }else{
  27.            oddCount++;
  28.        }
  29.        cout<<"Input a positive number: ";
  30.        cin>>value;
  31.        if(value < -1){
  32.              cout<<"Wrong input number\n";
  33.              return 0;
  34.        }
  35.    }
  36.    
  37.    cout<<"Number of odd number: "<< oddCount<<"\n";
  38.    cout<<"Number of even number: "<< evenCount;
  39.  
  40.    return 0;
  41. }

Explanation:

Firstly, create three variables, value, oddCount and evenCount (Line 7-9). The value variable is to hold the input number from user (Line 11 -12). oddCount and evenCount are to track the number of occurrence of even and odd number of the user input (Line 21-25).

The sentinel value here is -1 and therefore if user enter -1 as first input, the message "NO input is entered!" will be displayed. (Line 14).

If user input a negative value other than -1 , display the alert message to user and terminate the program (Line 19-22).

We check if the value modulus by two is zero, this means it is an even number and then increment evenCount by one (Line 26-27). Otherwise increment oddCount by one (Line 28-29).  

After that prompt the user to input another number again and repeat the loop (Line 31-36). So long as the user don't enter -1, the while loop will just keep running.

At last, print the number of odd and even number (Line 40-41).

Other Questions