0

I am currently making a program which asks the user to input 10 integers and the code will have to count how many odd numbers there are. At the end of the program it prompts the user whether to retry it again, essentially in a loop if they choose to input a new set of 10 integers.

int i, value;
int odd = 0;
char option;

do
{
    for (i=1;i<=10;++i)
    {
        cout << "Enter integer no. " << i << ": ";
        cin >> value;
        if (value % 2 == 1)
        {
            odd++;
        }
    }
    cout << "\nThere are " << odd << " odd numbers.\n";

    cout << "\nDo you want to try again? \nEnter Y for Yes and N for No: ";
    cin >> option;
    if (option == 'N')
    {
        cout << "\nThank you for using this program. \nProgram Terminating!";
        break;
    }
} while (option == 'Y');

return 0;

My problem is that the counted and displayed odd numbers on the previous count is added to the next count in the loop. If the previous count had 5 odd numbers and the next count had 4 odd numbers, it would then display a total of 9 odd numbers. How do I separate the count of odd numbers without them adding up with each other with every new input of 10 integers?

Yun
  • 3,056
  • 6
  • 9
  • 28
ANTOINE
  • 23
  • 5
  • 4
    A strategically placed `odd = 0;` seems fitting, perhaps right before the end of the outer do-while loop? Or how about just moving `int odd = 0;` so it is immediately *inside* the do-while loop. – WhozCraig Sep 18 '21 at 18:41
  • 2
    Please indent the contents of the `do`...`while` loop and of the `for` loop. Your code is very hard to read without proper indentation. – Andreas Wenzel Sep 18 '21 at 18:42

1 Answers1

1

The definition/initializationint odd = 0; is outside of the do…while loop so it is not being reinitialized for each loop iterations. There are two options to accomplish what you want to do:

  1. Move int odd = 0; to the beginning of the do…while loop after do{. This reduces the variable scope to each iteration of the loop and will force it to reinitialize to zero each time.
  2. Add the statement odd=0 either at the end or the beginning of the loop.
Jonathon S.
  • 1,928
  • 1
  • 12
  • 18
  • I followed your advice and moved the 'int odd = 0' inside the 'do...while' loop and it worked! I guess it just needed to be reinitialized for each iteration, thank you very much! – ANTOINE Sep 19 '21 at 00:42