Reputation: 65
I'm a beginner at C and can't find the answer to this anywhere because I don't know how to word it so I'm just going to ask a question. I understand basic looping but what I want to do is make a small program where the output is this using only loops:
my code so far
int x;
int y = 1;
for (x=1; x<=5; x++)
{
while(y<=5)
{
printf("%d", y);
y++;
}
}
this is what I have so far and don't know where to go next, if anyone could help I'd be grateful.
Upvotes: 3
Views: 2003
Reputation: 101
You need to make 2 changes to your outer loop in order to get the expected output.
for (x=1; x<=5; x++)
should be for (x=1; x<=5; x--)
because your program will count up to 5 the first time, 4 the second time, 3 the third time, etc..printf("\n")
so a new line is printed after each sequence is output.You need to make 1 change to your inner loop as well:
y <= 5
you should say y <= x
because x
will always be equal to the last number that you want to print since you're decrementing it in the outer loop.Upvotes: 1
Reputation: 21
This is another solution using just a FOR loop with Integer Division. Try:
#include <stdio.h>
int main(void){
int n= 12345, i;
for(i=n;i>0;i/=10){
printf("%d\n",i);
}
return 0;
}
Upvotes: 2
Reputation: 6875
Another solution is to use integer division
and use one single loop:
int x = 12345;
// repeat this loop as long as x != 0
while (x)
{
printf("%d\n", x);
x /= 10; // x = x/10;
}
Upvotes: 1
Reputation: 154080
For fun: another approach that simply divides each loop. But use best answer
int main(void) {
int x = 12345;
do {
printf("%d\n", x);
x /= 10;
} while (x);
return 0;
}
Output
12345
1234
123
12
1
Upvotes: 1
Reputation: 12270
You have to see the pattern you want and apply it in the loops to get it.
You need the output 12345 1234 123 12 1
. So, the first iteration should start at 1
and go till 5
, second should start at 1
and go till 4
, and so on..
So, the outer loop should give the end limits for the inner loop, and the inner one should always start with 1
.
Try
for (x=5; x>=1; x--)
{
y = 1; // because the number always start with 1
while(y<=x)
{
printf("%d", y);
y++;
}
printf("\n"); //to go to next line
}
Upvotes: 1
Reputation: 224207
Close. Your outer loop needs to count down, not up, and your inner loop needs to count from 1 to x.
int x, y;
for (x=5; x>=1; x--)
{
for (y=1;y<=x;y++)
{
printf("%d", y);
}
printf("\n");
}
Upvotes: 5