user11560496
user11560496

Reputation:

If the user wants to input x amount of numbers, how do I manage to keep track of it and then end the program?

I am trying to write a program that asks the user to enter a sequence of integers. As the numbers are being input, the program should count the number of odd and even numbers. When the user is finished entering data, the program should display the number of odd numbers and the number of even numbers that were entered.

Can I achieve the above result, without having to use a sentinel value ? Also, if i ask the user "How many numbers would you like to enter?", how do I have the program output "Enter data:" 5 times if the input is "5" ?

#include <iostream>

using namespace std;

int main()
{
int userInput;
int evenCount = 0;
int oddCount = 0;
cout << "Odd and Evens ";

do
{
    cout << "Please enter an integer: ";
    cin >> userInput;


    if (userInput % 2 == 0)
    {
        evenCount++;
    }
    else
    {
        oddCount++;
    }

} while (userInput != 0);
cout << "You entered " << oddCount << " odd numbers, and " << evenCount - 1 << " even numbers " << endl;

system("pause");
return 0;
}

This is what I am trying to achieve with my program:

How many numbers are you going to enter? 5
Enter data: -5
Enter data: 2
Enter data: 3
Enter data: 6
Enter data: 0
Odd numbers entered: 2
Even numbers entered: 3

Upvotes: 0

Views: 5459

Answers (2)

mahbubcseju
mahbubcseju

Reputation: 2290

First prompt the user for how many number they want to enter. After taking input that number , use your loop until your total odd number and even number is less than that number.

Like:

#include <iostream>

using namespace std;

int main()
{
    int numberOfInput;
    cout<<"How many numbers are you going to enter? ";
    cin>>numberOfInput;

    int userInput;
    int evenCount = 0;
    int oddCount = 0;

    do
    {
        cout << "Enter data: ";
        cin >> userInput;


        if (userInput % 2 == 0)
        {
            evenCount++;
        }
        else
        {
            oddCount++;
        }

    }
    while (evenCount+oddCount<numberOfInput);

    cout<<"Odd numbers entered: "<<oddCount<<endl;

    cout<<"Even numbers entered: "<<evenCount<<endl;
    return 0;
}

Upvotes: 1

Faysal Mahmud
Faysal Mahmud

Reputation: 11

I would use a simple for loop.

int main() {
 int userinput;
 int even=0;
 int odd=0;
 cout<<"Enter a value: ";
 cin>>userinput;
 int integerAdded;
 for (int i=0;i<userinput;i++){
    cout<<"Enter Data: ";
    cin>>integerAdded;
    if ((integerAdded%2)==0){
      even++;
    }
    else{
      odd++;
    }
  }

  cout<<"The amount of even numbers is "<<even<<endl;
  cout<<"The number of odd characters is: "<<odd<<endl;
}

Upvotes: 1

Related Questions