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

Break Loop on pressing =

How can i break the loop when = is pressed instead of 0 without advanced code please because i’m still at the start

[Here’s the code][1]

  internal class Program
    {
        static void Main()
        {
            int sum = 0;

            while (true)
            {
                Console.Write("Enter a number (or 0 to exit): ");
                string input = (Console.ReadLine());

                if (input == "=")
                {
                    break;
                }

                sum += Convert.ToInt32(input);
            }

            Console.WriteLine($"The sum of all the numbers is: {sum}");
        }
    }
}

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

>Solution :

instead of getting an int get a string from Console.ReadLine() like this:

string input = Console.ReadLine();

then check if it is = and break:

if(input == "=")
{
    break;
}

and you can still use it as a number in the cases that they didn’t input =, full code would be something like

int sum = 0;

while(true)
{
    Console.Write("Enter a number (or = to exit)");
    string input = Console.ReadLine(); // Take input as string
    
    if(input == "=") // If they entered =, break
    {
        break;
    }

    sum += Convert.ToInt32(input); // If they entered a number, convert it to integer
}

Console.WriteLine($"The sum of all the numbers is: {sum}");
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