Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading in an integer array, and stopping when a string is entered

int [] arr = new int [100];
int count = 0;
int val;
arr[count] = 0;

while(count < arr.Length && (int.TryParse(arr[count], out val)))
{
    arr[count] = Convert.ToInt32.Console.ReadLine();
}

I want the user to enter values for an array, and when they enter ‘exit’ the while loop breaks

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should read input first using do..while loop and use exit condition to get out of while loop if user enters exit

do
{
   string input = Console.ReadLine();  //Read input from user
   if(input == "exit")  //exit condition
     break;
   if(int.TryParse(input, out int intData))
       arr[count++] = intData;
}while(count < arr.Length);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading