Zack Doyle Zack Doyle - 8 days ago 6
C# Question

Console.ReadLine() not exiting Program in c#

I have an assignment where I have to create code to display factors and whether a number is a perfect and/or prime number. I think I have all the code right to run my program, but when I get to the last line (Console.ReadLine()) I expect to hit enter and then exit the program. Currently, when I hit enter, the program displays whether it is a prime number and/or perfect number over and over again (each time you hit enter). So basically, it executes everything after the while loop over and over again.

Keep in mind, I'm very new to C#, so some of my syntax and readability may be weird. I am only interested in answers that will help me solve the ReadLine issue. My instructors will help me with making my code more readable and organized.

Thanks for your advice! Here is my code. I commented where the ReadLine isn't closing the program:

using System;

namespace Factorizer.UI
{
class Program
{
static void Main(string[] args)
{
string input;
int num, i, x = 0, sum = 0;

while (true)
{
Console.Write("Enter a number: ");
input = Console.ReadLine();

if (int.TryParse(input, out num))
{
Console.Write("\nThe factors are: ");

for (i = 1; i <= num; i++)
{
if (num % i == 0)
{
Console.Write("{0} ", i);
}
}
break;
}
else
{
Console.WriteLine("\nThat was not a valid number!\n");
}
}

for (i = 1; i < num; i++)
{
if (num % i == 0)
{
sum = sum + i;
}
if (sum == num)
{
Console.Write("\n\n{0} is a perfect number.\n", num);
}
else
{
Console.Write("\n\n{0} is not a perfect number.\n", num);
}

for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
x++;
break;
}
}

if (x == 0 && num != 1)
{
Console.Write("\n{0} is a prime number.", num);
}

else
{
Console.Write("\n{0} is not a prime number.", num);
}
Console.ReadLine(); //this isn't closing the program!
}
}
}
}

Answer

Console.ReadLine() is inside the for loop. Move it down after the next bracket.

Comments