Print out even numbers with while-loop

Feb 22, 2016 at 8:29pm
I am trying to write a program that prints out the even numbers between 1 and 21 using the WHILE loop. This is what I have, but there is no output. Why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 #include <iostream>
using namespace std;

int main()
{
        int number = 1;

        while (number <= 21 && number / 2)
        {
                cout << number;
                number++;
        }
        return 0;
}
Feb 22, 2016 at 8:33pm
When is number / 2 true?
Feb 22, 2016 at 8:36pm
I was trying to say when the number was even, but what would I set number / 2 equal to to make that work?
Feb 22, 2016 at 8:38pm
2 things.

1. The reason nothing is being outputted is that, number starts at 1, the condition is not met therefore it will never enter the while loop, and therefore it will never become 2, which would make the condition true.

I was trying to say when the number was even

2. You want to use the modulus operator here, otherwise you will get incorrect results -
http://www.cprogramming.com/tutorial/modulus.html


This is how I would do it -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
	int number = 1;

	while (number <= 21)
	{
		if (number % 2 == 0)
		{
			cout << number;
		}
		number++;
	}
	
	return 0;
}
Last edited on Feb 22, 2016 at 8:38pm
Feb 22, 2016 at 8:44pm
That makes more sense, but whenever I try to run your code, I'm still not having any output.
Feb 22, 2016 at 8:46pm
Works perfectly fine on visual studio 2013/2015 and on cpp.sh.

http://cpp.sh/6wrr
Feb 22, 2016 at 8:54pm
This is another way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main()
{
    const int start  = 1;
    const int finish = 21;
    
    int number = start;
    if (number % 2) number++;

    while (number <= finish)
    {
        cout << number << ' ';
        number += 2;
    }
    
    return 0;
}
Feb 22, 2016 at 9:01pm
Okay, I got it now! Thank you everyone!
Topic archived. No new replies allowed.