While loop

Can anyone help me in making a code that displays the integer 1 to 20 with only 4 numbers per line using only a while loop.

ex:
1234
5678 ...
etc..
How's this?

#include<stdio.h>
int main()
{
int num, count;
while (num<=20)
{
printf ("%d", count);
count++;
if(count % 4 == 0)
printf ("\n");
}

return 0;

}


that is all I could think of.
performing arithmetic operation on un(assigned|initialized) count. BIG MISTAKE.
oh right haha carelessness always get to me
damn it's still an infinite loop.
Did you initialise int num, count with an integer? (i.e. int num = 1;)
Last edited on
Hi guys, new to the forum and to c++, still learning myself

metalheadrenzo have you tried using a for loop inside the while loop to do the counting for you?

just a thought...
to blezor: yes I did. same with count yet I still get an infinite loop

and to seecoder: yeah I know it would have been much easier with a for loop but the instructions given was to use only a while loop.
Oh right.. look at your loop lol -

1
2
3
4
5
while (num <= 20) //look at the condition
{
     //now look thoroughly at what really happens inside the loop
    //.......
}


Pretty obvious once you look carefully xD

Tip: You don't need int num in your case, you can make the program work with just int count.
Last edited on
lol I got it.

Problem is I can't get it to form a 4 number per line out come :(

outcome is :

123
4567
891011
12131415
16171819
20

hint: (without giving you the direct answer)
using your code above, is there another way for you to test your (count % 4) result inside the if statement...

edit: that is to say, is there a slight modification to your formula in the area of (count % 4) that will give you the correct result (sorry, should have made myself clearer...)
Last edited on
Yep, following seecoder's hint, you only have to work on this line:

if (count % 4 == 0
can you elaborate on that hint please.

I'm fairly a beginner.
As in.. change it a bit.. work around it. Change the values a bit and experiment - it's good experience.

What happens if its 4 % 1? 4 % 2?
got it haha thanks
Topic archived. No new replies allowed.