David Frickert - 1 year ago 68
C Question

# Printing from 1 to 100 in columns

Code:

``````for(int i = 1; i <= 100; i++){
if(i % 10 == 1)
printf("\n%d", i);
else printf("%4d",i);
}
``````

Results:

``````(blank line)
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  37  38  39  40
41  42  43  44  45  46  47  48  49  50
51  52  53  54  55  56  57  58  59  60
61  62  63  64  65  66  67  68  69  70
71  72  73  74  75  76  77  78  79  80
81  82  83  84  85  86  87  88  89  90
91  92  93  94  95  96  97  98  99 100
``````

How can i remove the first blank line without doing something like:

``````for(int i = 1; i <= 100; i++){
if(i == 1 || i % 10 == 1)
printf("\n%d", i);
else printf("%4d",i);
}
``````

And how can i 'ident' the columns? As the last column isn't properly arranged, and I have no idea how to fix it using printf's.

At last, sorry for wrinting '(blank line)' as i don't know how to make a blank line, and thanks for the help.

Rather than printing a newline at the start of a line, print it at the end instead:

``````for (int i = 1; i <= 100; i++){
printf("%4d",i);
if (i % 10 == 0)
printf("\n");
}
``````

This prints each number in a 4 character field, then prints a newline if the last number is divisible by 10.

Output:

``````   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  37  38  39  40
41  42  43  44  45  46  47  48  49  50
51  52  53  54  55  56  57  58  59  60
61  62  63  64  65  66  67  68  69  70
71  72  73  74  75  76  77  78  79  80
81  82  83  84  85  86  87  88  89  90
91  92  93  94  95  96  97  98  99 100
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download