Hep with "\n"

So I did a program with outputs: 2 4 6 8 10 12 14 16.... 44 46 48 50.
But I want a program which shows:

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

instead of showing the number in a linear manner.

Here's the code:

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
  // OneFirst.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <conio.h>
#include <stdio.h>
#include <iostream>
#include <string>


using namespace std;


void main()
{
	int firstNum= 2;
	
	

	while (firstNum<=50)
	{
		
		printf(" %d", firstNum);
		firstNum= firstNum+1;
		firstNum++;
	}
		printf("\n");
	
  


	getch();
	
}





Really appreciate it if anyone could help me with this, I just started and I feel like a real noob. >_< hehe, thanks. :)
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 <stdio.h>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int firstNum= 2;
    int count = 0;
    int newlineAt = 4;
    while (firstNum<=50)
    {
        printf(" %d", firstNum);
        firstNum= firstNum+1;
        firstNum++;
        count++;
        if (count > newlineAt) {
            printf("\n");
            count = 0;
        }
    }
    printf("\n");
    return 0;
}
Last edited on
If you think about this for a couple minutes, the answer becomes clear. You want to do something 5 times, and then start over. If you forget about the starting over part, you want to do something 5 times. Since you know how many times the loop needs to loop, a for loop is the obvious choice. All you have to do is put that inside your while loop so that it starts over again.

There is no reason to increment the number like you do:
1
2
3
4
firstNum= firstNum+1;
firstNum++;
// is == 
firstNum = firstNum +2;


^
I think it'll look something like this.

1
2
3
4
5
6
7
8
	while (firstNum<=50)
	{
		printf(" %d", firstNum);
		firstNum= firstNum+1;

                for (int i = 0; i < 5; i++)
		printf(" %d", firstNum);
	}


Topic archived. No new replies allowed.