Reputation:
I'm trying to create this only with for loops:
1
12
123
1234
12345
My code:
for (int i = 1; i <=5; i++)
{
int counter = 1;
Console.Write(counter);
for(int j = 2; j <= i; j++)
{
Console.Write(counter + 1);
}
Console.WriteLine();
}
But I get this:
1
12
122
1222
and is there any way I can do it without the counter?
Upvotes: 0
Views: 65
Reputation: 23208
You should update your internal for
loop at little bit, remove counter
variable and start a loop from j
equals 1
till current value of i
from external loop
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
The reason, why your code doesn't work is that you set counter
to 1
and didn't change its value anymore, and always use counter + 1
, which prints 2
Upvotes: 2
Reputation: 9804
If you allow the use of a string, it can be done in 1 for loop:
string output = "";
for(int i = 1; i<5; i++){
//Append new number
output += i.ToString();
//Output it
Console.WriteLine(output);
}
Console.WriteLine();
I am the first to admit that is not the most robust solution. You may want to use a List<int>
for output. But with those, the output code is way more complciated. So I choose the string shortcut here.
Upvotes: 1