none
For Loop RRS feed

  • Question

  •             Console.WriteLine("enter the size of array");
                int a = Console.Read();

                // Declare and initialize an array:
                string[] WeekDays = new string[a]; 

                Console.ReadLine();
                //initialize the array

                for (int i = 0; i <a; i++)
                {
                    Console.WriteLine("write the content of {0} index element", i);
                    WeekDays[i] = Console.ReadLine();

                }

                /* // Pass the array as a parameter:
                 PrintArray(WeekDays);*/

                for (int i = 0; i < a; i++)
                {
                    Console.WriteLine(WeekDays[i]);
                }
                Console.ReadKey();
            }

    Why the for loop becomes an infinte loop.?? 


    • Edited by Bilal Mubeen Saturday, February 15, 2014 2:23 AM
    Saturday, February 15, 2014 2:23 AM

Answers

  • That loop is not infinite, it's just that the size of the array is larger than you expect because you didn't read it correctly.

    Console.Read will return an integer that represents the code of the typed character. The character code is not the same thing as the value of a character digit. For example if you type 7 then the length of the array will be 55 because that's the character code of '7'.

    To read a number from the console use ReadLine and parse the line to a number:

    string line = Console.ReadLine();
    int a = int.Parse(line);

    Saturday, February 15, 2014 7:28 AM
    Moderator