Thursday, December 24, 2009

Need help with C# coding arrays?

Keep getting that index was outside bounds of array on compile. I am trying to generate array of 20 numbers from 0-9, search for first occurence of number 7 , if any, and report its position in the array. Do this 1000 times





public class Program


{





public int[] array = new int[20];


Random random = new Random();





public void newarray()


{


int count = 0;





while (count %26lt; 1000)


{





for (int i = 0; i %26lt; array.Length; i++)


{


array[i] = random.Next(0, 9);


}





int z = 0;


while (array[z] != 7)


if (z %26lt; array.Length)


z++;


else z = -1;

















Console.WriteLine(';Its at index '; + z);


count++;


}


}





public static void Main()


{


Program program = new Program();


program.newarray();





}


}


}Need help with C# coding arrays?
Here's the problem:





else z = -1;





After this else statement, it goes back to ';while (array[z] != 7)'; and you obviously can't have -1 for an index.

No comments:

Post a Comment