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}");
}
}
}
>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}");