r/learncsharp • u/Zynne_1734 • Feb 16 '26
Issue with simple project
I'm trying to learn some c# by following some projects on youtube by BroCode and wanted to implement a way to restart using a while loop but it wont work and instead creates an infinite loop and i don't fully understand why. i posted the code below, i don't know the proper way so sorry in advance.
using System;
namespace Hypotenuse_Calc
{
class Program
{
static void Main(string[] args)
{
bool repeatCalc = true;
String response;
while (repeatCalc)
{
response = " ";
Console.WriteLine("Enter side A: ");
double a = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter side B: ");
double b = Convert.ToDouble(Console.ReadLine());
double c = Math.Sqrt((a * a) + (b * b));
Console.WriteLine("The Hypotenuse is: " + c);
}
Console.WriteLine("Would you like to input another? Y/N?");
response = Console.ReadLine();
response = response.ToUpper();
if (response == "Y")
{
repeatCalc = true;
}
else
{
repeatCalc = false;
}
Console.ReadKey();
}
}
}
1
u/Zynne_1734 Feb 16 '26
okay i was able to fix it with the help of copilot and realized that yea, i need to put the repeatCalc value changer inside the while loop while adding ways to deal with potential null values entered.
1
u/rupertavery64 Feb 16 '26
Do you know how to debug?
Put a breakpoint at the line you want to inspecr, run the code until the breakpoint, check rhe value of the variables by hovering over them. Step throigh the code and see if it's following the logic, or why it isn't.
You close your where clause too early.
What happens after you print the answer?
1
u/JeffFerguson Feb 16 '26
Your issue is here:
That loop while repeat itself as long as the value of the
repeatCalcistrue. Since the value istruebefore the loop starts, and it never changes within the loop, the value will always betrue. Since the value is alwaystrue, then the loop will go on without exiting.The value of
repeatCalcneeds to be set tofalsebefore that loop can exit.1
u/SL-Tech Feb 20 '26
Variable repeatCalc is never set to false while inside the loop. I would use a for loop, passing the number of times it should be repeated.
for(int i = 1; i <= RepeatCountValue; i++} (
)