0

How can i get this code to show once and it counting all the positive?

When i enter a 10 numbers. it show

The positive are....
The positive are....
The positive are....
The positive are...
The positive are...
...
until 10

can someone show me how to make it show only once and keeping counting the number?

 if (findNum[i] > 0)
        {
            cout <<"The positive are " << findNum [i] << endl;

        }

        else
        {
            cout <<"The Negative number are " << findNum[i] << endl;

        }
3
Contributors
6
Replies
34
Views
3 Years
Discussion Span
Last Post by Ancient Dragon
0

you didn't post the loop, but you need to declare a counter before the loop starts then increment it every time a positive integer is encountered inside the loop. Only after the loop finishes should you display the final count.

0
for (int i=0; i < num ; i++)
    {
        if (findNum[i] > 0)
        {
            cout <<"The positive are " << findNum [i] << endl;

        }

        else
        {
            cout <<"The Negative number are " << findNum[i] << endl;

        }



    }
0

if i change to this way

if (findNum[i] > 0)
        {
            cout <<"The positive are " << i + 1 << endl;

        }

it show me how many i got but still have the

The positive are....
The positive are....
The positive are....
The positive are...
The positive are...
...
until 10

0

What are the contents of findNum? That's somewhat critical as to your results. However, it strikes me that you'd want to split it into two loops to get a more reader friendly output:

cout << "Positive: ";

for (int i = 0; i < num; i++)
{
    if (findNum[i] > 0)
    {
        cout << findNum[i] << ' ';
    }
}

cout << "\nNegative: ";

for (int i = 0; i < num; i++)
{
    if (findNum[i] < 0)
    {
        cout << findNum[i] << ' ';
    }
}

cout << '\n';
0

this is what I meant

int counter = 0;
for (int i=0; i < num ; i++)
    {
        if (findNum[i] >= 0)
        {
            ++counter;
        }

    }
cout <<"The number of positive integers are " << counter << endl;
cout <<"The number of negative integers are " << num - counter << endl;

Edited by Ancient Dragon

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.