0
 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?

Matthew Watson
  • 96,889
  • 9
  • 144
  • 240
Kobus
  • 13
  • 6

4 Answers4

2

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():
} 
isydmr
  • 649
  • 6
  • 16
1

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():
} 
Barr J
  • 10,104
  • 1
  • 27
  • 44
  • 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 02 '18 at 14:03
1

No need to use 2 loops. Just repeat that character

for (int i = 0; i <= 6; i++)
{
  Console.Write(new String("#",i)); 
  Console.WriteLine():
} 
Adelin
  • 7,269
  • 5
  • 36
  • 62
1

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:

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)

Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199