How do I print # in a nested for loop [duplicate]


How do I print # in a nested for loop [duplicate]



This question already has an answer here:


for (int i = 0; i <= 6; i++)
{
string doors = new string[6];
doors[i] = "#";
for (int j = 1; j <=i; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}



Hi guys. I need to print # one and then # twice, until i get to six times. It says System.index.out.of.range. How come?



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





You don't want any array - string doors - at all. Just print out # - Console.Write('#')
– Dmitry Bychenko
Jul 2 at 13:30



string doors


#


Console.Write('#')





How to i declare the # then?
– Kobus
Jul 2 at 13:32





dotnetfiddle.net/2hEdV7
– Ehsan Sajjad
Jul 2 at 13:33





see the above example
– Ehsan Sajjad
Jul 2 at 13:34





@Kobus: you don't want to declare anything. Just print out a constant # in the loops: Console.Write('#');
– Dmitry Bychenko
Jul 2 at 13:34


#


Console.Write('#');




4 Answers
4



If



I need to print # one and then # twice, until i get to six times.



You don't want any array - string doors = new string[6];, just loops:


string doors = new string[6];


for (int line = 1; line <= 6; ++line) {
for (int column = 1; column <= line; ++column) {
Console.Write('#');
}

Console.WriteLine();
}



If you have to work with array (i.e. array will be used somewhere else), get rid of magic numbers:


// Create and fill the array
string doors = new string[6];

for (int i = 0; i < doors.Length; i++)
doors[i] = "#";

// Printing out the array in the desired view
for (int i = 0; i < doors.Length; i++) {
for (int j = 0; j < i; j++) {
Console.Write(doors[j]);
}

Console.Writeline();
}



Please, notice that arrays are zero-based (array with 6 items has 0..5 indexes for them)


6


0..5



You should try to extend your array, it's limited to 6 elements but you try to access 7 elements as you go through 0 to 6.


for (int i = 0; i <= 6; i++)
{
string doors = new string[7];
doors[i] = "#";
for (int j = 1; j <=i; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}



because it is out of range.



change it to this:


for (int i = 0; i <= 6; i++)
{
string doors = new string[6];
doors[i] = "#";
for (int j = 0; j <=i.length; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}





What are you wanting i.length to do here? Given i is an int the answer to what it actually is doing is probably throwing a compiler error...
– Chris
Jul 2 at 14:03


i.length


int



No need to use 2 loops. Just repeat that character


for (int i = 0; i <= 6; i++)
{
Console.Write(new String("#",i));
Console.WriteLine():
}

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?