Loop

How can I write a loop that counts only the odd numbers out of the first five numbers entered from the keyboard, but skips the number 7 inside the loop?



You give no code of your own so that I see where and how you store the numbers you read.
So I guess I'll just show you how I'd do it. No loops are needed for the actual check.

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
#include <algorithm>
#include <iostream>
#include <vector>

bool oddButNotSeven(int i)
{
    return i%2 != 0 && i != 7;
}

int main()
{
    std::vector<int> vi;
    int i;

    std::cout << "Now reading numbers. Press Control-D Enter to stop.\n >> ";

    while (std::cin >> i)
    {
        vi.push_back(i);
        std::cout << " >> ";
    }

    std::cout << "There are " << std::count_if(vi.begin(), vi.end(), oddButNotSeven)
        << " odd numbers, different from seven." << std::endl;
}

... and a simplified version, if you aren't required to store the numbers...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

bool oddButNotSeven(int i)
{
    return i%2 != 0 && i != 7;
}

int main()
{
    std::size_t count = 0;
    int i;

    std::cout << "Now reading numbers. Press Control-D Enter to stop.\n >> ";

    while (std::cin >> i)
    {
        if (oddButNotSeven(i))
            ++count;

        std::cout << " >> ";
    }

    std::cout << "There are " << count << " odd numbers, different from seven." << std::endl;
}
But how would I write it using a for loop? If I choose to do so
Topic archived. No new replies allowed.