Oct 3, 2009 at 1:34pm UTC
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..
Oct 3, 2009 at 2:30pm UTC
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.
Oct 3, 2009 at 3:33pm UTC
performing arithmetic operation on un(assigned|initialized) count. BIG MISTAKE.
Oct 4, 2009 at 9:56am UTC
oh right haha carelessness always get to me
Oct 4, 2009 at 9:59am UTC
damn it's still an infinite loop.
Oct 4, 2009 at 10:11am UTC
Did you initialise int num, count
with an integer? (i.e. int num = 1;
)
Last edited on Oct 4, 2009 at 10:11am UTC
Oct 4, 2009 at 11:04am UTC
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...
Oct 4, 2009 at 1:20pm UTC
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.
Oct 4, 2009 at 1:36pm UTC
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 Oct 4, 2009 at 1:37pm UTC
Oct 4, 2009 at 1:51pm UTC
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
Oct 4, 2009 at 2:29pm UTC
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 Oct 4, 2009 at 2:34pm UTC
Oct 4, 2009 at 11:04pm UTC
Yep, following seecoder's hint, you only have to work on this line:
if (count % 4 == 0
Oct 5, 2009 at 12:31am UTC
can you elaborate on that hint please.
I'm fairly a beginner.
Oct 5, 2009 at 5:17am UTC
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?