Is this program not supposed to output 5 x 5 4 3 2 1 when i type in 5 (or whatever number it is)

It outputs an infinite number of numbers. How should i do it?
1
2
3
4
5
6
7
8
9
10
11
12
13
  #include <stdio.h>
int main(void)
{
	int i;
	printf("Enter a number: ");
	scanf_s("%d", &i);
	for (; i; i--)
	{
		for (; i; i--)
			printf("%d", i);
	}
	return 0;
}
you need your for loop to be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <iostream>

using namespace std;

int main(void)
{
	int i;
	cin >> i;
	
	for (int x = i; x > 0; x--)
	{
		for (int c = i; c > 0; c--)
		{
			std::cout << c << " ";
		}
		
		std::cout << endl;
	}
	return 0;
}
Lets think what happens in the (original) loops.

You have i alone in the conditional expression. Although i is an integer, it can be used as boolean value. 0==i means false and 0!=i means true.


The input is N. A positive number. (If you type in a negative number, it should be clear that the I stays negative for a while.)

The outer loop test passes, for 0!=N.
The inner loop starts.
On each iteration it first prints value of i and then decreases it.

When 0==i, the inner loop ends and the i remains 0.
Now the outer loop has completed one iteration. Almost. It too will decrement i.

The first iteration of the outer loop is now entirely complete and i == -1.

The second iteration of outer loop would start, if 0 != i.
Oh yes, it isn't. It is already negative. Iteration continues.
That's a great explanation! Thanks a lot!
Topic archived. No new replies allowed.