Write a program that prints out the even integers between 2 and 100.

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 num = 2;
   int count = 0;
   
   while (num <= 100)
   {
      cout << num << endl;
      num +=2;
   }
         
   return 0;
} // End function main.       
      


The code works fine but I need the results to print out like

2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40

instead of

2
4
6
8
10
12

I don't know how to do this.
Really?
omit the endl and replace it with " " then.
Last edited on
If you want a newline after every 10 numbers:

if(num % 20 == 0)
{
cout << endl;
}

This will separate after 20, 40, etc...
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

int main()
{
   int num = 2;
   int count = 0;
   
   while (num <= 100)
   {
      cout << num << " ";
      num +=2;
      
      if (num % 20 == 0)
      {
         cout << endl;  
      }   
   }
         
   return 0;
}


It prints out
2 4 6 8 10 12 14 16 18
20 … 38


100

Its supposed to print out
2-20
22-40
42-60
62-80
82-100

What am I doing wrong?
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
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

using namespace std;

int main()
{
   int num = 2;
   int count = 0;

   while (num <= 100)
   {
      cout << num << " ";
      num +=2;

      switch (num)
      {
      case 22:
        cout << endl;
        break;

      case 42:
        cout << endl;
        break;

      case 62:
        cout << endl;
        break;

      case 82:
        cout << endl;
        break;
      }
   }

   return 0;
}


output:

2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60
62 64 66 68 70 72 74 76 78 80
82 84 86 88 90 92 94 96 98 100
Last edited on
if(num % 20 == 0)
{
cout << endl;
}

n+= 2;

Move the n+=2 to the bottom of the loop.
Thanks a lot guys!!!
Topic archived. No new replies allowed.