Home > Software engineering >  breaking while loop and doesn't print the result c#
breaking while loop and doesn't print the result c#

Time:10-14

I'm a beginner in c# and I'm training on codeforces and SPOJ to learning how to solve problems, the problem with me is when the loop is break doesn't print all the input it's just end the program without printing

please can someone tell me what is the mistake in these 2 codes that i write >

the Input: 1,2,88,42 ,99 Output: 1,2,88

class Program

 {

  static void Main(string[] args)
    {
        Console.WriteLine("please enter an integer number in two digits");

        int numbers;
        int[] array_num = new int[100];

        string nu = "";
        int i =1;
      
         while(i<100)
         {
             numbers = int.Parse(Console.ReadLine());
             nu  = numbers;
             array_num[i] = numbers;
             

            if(array_num[i]<array_num[i-1])

            {
                Console.WriteLine("the numbers is "  nu  "");
                break;
            }

            i  ;
            
           
         }
       
       }

      }

and i do it in for loop and the same problem

   static void Main(string[] args)
    {
        Console.WriteLine("please enter an integer number in two digits");

        int numbers;
        int[] array_num = new int[50];

        string nu = "";

        for (int i = 1; i <= array_num.Length; i  )
        {
            numbers = int.Parse(Console.ReadLine());
            nu  = numbers;
            array_num[i] = numbers;
           
            if (array_num[i] < array_num[i - 1])
            {

                Console.WriteLine("the number is "   nu   "");
                           
                break;
            }
           
        }

    }

what is the mistake?

CodePudding user response:

Answering to "...the problem is when the loop is break doesn't print all the input it's just end the program...":

That's because after you breaked loop there is no more code to execute - so Console closes. You can add Console.ReadKey() or Console.ReadLine() at the end of Main method to keep Console opened after loop breaked. Console.ReadKey() would wait until you press any key, Console.ReadLine() would wait until you input something and press Enter (or just press Enter). Or in both ways Console will stay opened until you close it manually.

static void Main(string[] args)
{
    // ...
    for (int i = 1; i <= array_num.Length; i  )
    {
        // ...
        if (array_num[i] < array_num[i - 1])
        {
            Console.WriteLine("the number is "   nu   "");
            break;
        }
    }
    
    Console.ReadKey(); // Here Console will wait until you press any key and will stay opened
}
  • Related