How to stop a while loop? C# - c#

I am very new to C# and while loops. Does anyone know how to stop it? It keeps printing the first if-statement. Here is the code:
const int Year = 400;
const int LeapYear = 4;
const int NoLeapYear = 100;
int input = 0;
input = int.Parse(Console.ReadLine());
while (input != 0)
{
Console.WriteLine("Enter a number: ");
if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
if (input > 0 && input % NoLeapYear != 0)
{
Console.WriteLine($"{input} is not a leap year.");
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
if (input == 0)
{
Console.WriteLine("End of program");
}
}

You have to read the input inside the while loop:
const int Year = 400;
const int LeapYear = 4;
const int NoLeapYear = 100;
int input = -1; // initialize to something different than zero, to enter the while loop (or use do while loop instead of while loop)
while (input != 0)
{
Console.WriteLine("Enter a number: ");
input = int.Parse(Console.ReadLine()); // you were missing this line
if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
if (input > 0 && input % NoLeapYear != 0)
{
Console.WriteLine($"{input} is not a leap year.");
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
if (input == 0)
{
Console.WriteLine("End of program");
}
}
Consider using a do while loop in this case.

If you are using loop just and break to true statement It will breaks it

while (input != 0) {
conditions;
break; // Breaks the loop
}
Use the break; keyword to stop any loop in C# not just C# in many languages also break is used to stop loops
Or,
Satisfy the condition to opposite of what you have it will break/stop the loop

use break (https://www.w3schools.com/cs/cs_break.php)
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
if (i == 4)
{
break;
}
}

Related

school homework - grade calculation

i have got questions.
my problem is The user is asked to enter 20 exam grades. If the grades entered are less than 0 or greater than 100, you should be asked to enter again. How can I do that?
int not;
bool test = true;
for (int i = 0; i < 20; i++)
{
Console.Write((i + 1) + (".Not:"));
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
test = false;
Console.Write("Try again!");
}
else
{
test = true;
}
}
I want to use bool while doing this. would be glad if you help. thank you in advance
i changed code but i used goto. I dont want use to goto. How can i use bool doing this ?
int not;
int temp = 0;
for (int i = 0; i < 20; i++)
{
Console.Write("Add Not : ");
backtoAdd:
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
Console.WriteLine("Try Again!");
goto backtoAdd;
}
Console.WriteLine((i+1)+". Not : "+not);
temp = temp + not;
}
Console.Write("sum of not : "+temp);
Console.ReadKey();
As you mentioned it can be done with a while loop and condition to stop the loop. You can simplify it, I have added comments in the code example:
// declarations
int counter = 0;
int maxExamGradesInputCount = 20;
int highestGrade = 100;
int lowestGrade = 0;
// as long as counter is not equal to maxExamGradesInputCount continue
while (counter != maxExamGradesInputCount)
{
// we give input
string? input = Console.ReadLine();
// we try to parse our input
var parsed = int.TryParse(input, out var grade);
// if our input is parsed correctly
if (parsed)
{
// we check if the input value between the given range
if (grade < lowestGrade || grade > highestGrade)
{
Console.WriteLine("Try Again!");
}
else
{
// if with in range count
counter++;
}
}
}

How can do calculations inside a string?

How do i use operands in this code? What can i do to resolve this problem? Any suggestions or links to tutorials would be appreciated.
Operator '%' cannot be applied to operands of type 'string' 'int'
int i = 0;
double[] arr1 = new double[20];
for (i = 0; i < 20; i++)
{
Console.Write("Enter a number (0=stop): ");
var year = Console.ReadLine();
if (year == "0") break;
arr1[i] = int.Parse(year);
while (year != 0)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
Console.WriteLine($"{year} is a leap year.");
}
else if (year < 0)
{
Console.WriteLine($"Year must be positive!");
}
else
{
Console.WriteLine($"{year} is not a leap year.");
}`
You are close. You are already parsing the string to an int. Just use that instead of the string year when doing your calculations. Also, I'm not sure what you're trying to do with that while loop but I don't think you need it. It seems to just cause your program to go in an infinite loop because while is evaluating year but there is no opportunity to change the year value within the while loop.
void Main()
{
int i = 0;
double[] arr1 = new double[20];
for (i = 0; i < 20; i++)
{
Console.Write("Enter a number (0=stop): ");
var line = Console.ReadLine();
int numYear = int.Parse(line);
arr1[i] = numYear;
string message = "" ;
if (line != "0")
{
if (numYear < 0)
{
message = "Year must be positive!";
}
else if ((numYear % 4 == 0) && (numYear % 100 != 0)) || (numYear % 400 == 0))
{
message = $"{numYear} is a leap year.");
}
else
{
message = $"{numYear} is not a leap year.");
}
Console.WriteLine(message);
}
}
}

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!
}
}
}
}
Console.ReadLine() is inside the for loop. Move it down after the next bracket.
Just put Console.ReadLine(); after the for, it's inside the for block that's why it keeps printing and remove the for that you have after the while block, like this:
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!
//}

How to convert user input to an int Array in c#

The closest thing I found to answering this question was converting several string inputs into an array using a for loop.
I just want to take 1 string and convert the first 7 digits into an int array.
This code takes integer values of characters and then tests them against the Unicode values to return true if it is valid or false to reiterate the while loop and ask for input again. When I do this with the Console.Read(); method, and put in an invalid value first, it will say that my code is invalid for 7 more iterations. That means console.Read() has to run 7 more times even if the string has valid input.
public static void GetDigits(ref int[] callNumberArray, ref bool valid)
{
Console.WriteLine("Please enter the code you wish to dial.");
while ( valid == false)
{//This loop will reiterate the read() function if the code is not valid.
valid = true;
for (int i = 0; i < 7; i++ )
{
if (i != 6 && i!= 5 && i != 5 && i != 4 && i != 3 && i != 2 && i != 1 && i != 0)
{
i = 0;
}
callNumberArray[i] = Console.Read();// I want to change this
}
for (int i = 0; i < 7; i++)
{
if (i != 6 && i != 5 && i != 5 && i != 4 && i != 3 && i != 2 && i != 1 && i != 0)
{
i = 0;
}
if (callNumberArray[0] == 53)
{
valid = false;
}
if (callNumberArray[i] < 49)
{
valid = false;
}
if (callNumberArray[i] > 57 && callNumberArray[i] < 65)
{
valid = false;
}
if (callNumberArray[i] > 90 && callNumberArray[i] < 97)
{
valid = false;
}
if (callNumberArray[i] > 122)
{
valid = false;
}
}
if (valid == false)
{
Console.WriteLine("You entered an invalid code. Please re-enter your code.");
}
}
I think you should use Regex, example:
MatchCollection matchList = Regex.Matches(Content, Pattern);
var list = matchList.Cast<Match>().Select(match => match.Value).ToList();
I just want to take 1 string and convert the first 7 digits into an int array.
string subString = Console.ReadLine().Substring(0,7);
//Check if the whole string is a parsable number
if(int.TryParse(subString) == false)
{
Console.WriteLine("Not a valid number...");
return;
}
//convert it an int[]
int[] values = subString.ToCharArray().Select( value => int.Parse(value.ToString())).ToArray();
That's it basically, if you want to do it character by character that's fine, too, but's it's far easier to check for a number using int.TryParse() or a regex [0-9] (per character) if you're confortable with that.
Not sure about the "algorithm" you wrote and I agree with Sergey Berezovskiy that the if's looks weird, anyway this should answer your specific question:
public static void GetDigits(ref int[] callNumberArray, ref bool valid)
{
Console.WriteLine("Please enter the code you wish to dial.");
while ( valid == false)
{//This loop will reiterate the read() function if the code is not valid.
valid = true;
for (int i = 0; i < 7; i++ )
{
if (i != 6 && i!= 5 && i != 5 && i != 4 && i != 3 && i != 2 && i != 1 && i != 0)
{
i = 0;
}
callNumberArray[i] = Console.Read();// I want to change this
}
for (int i = 0; i < 7; i++)
{
if(!valid) break;
if (i != 6 && i != 5 && i != 5 && i != 4 && i != 3 && i != 2 && i != 1 && i != 0)
{
i = 0;
}
if (callNumberArray[0] == 53)
{
valid = false;
}
if (callNumberArray[i] < 49)
{
valid = false;
}
if (callNumberArray[i] > 57 && callNumberArray[i] < 65)
{
valid = false;
}
if (callNumberArray[i] > 90 && callNumberArray[i] < 97)
{
valid = false;
}
if (callNumberArray[i] > 122)
{
valid = false;
}
}
if (valid == false)
{
Console.WriteLine("You entered an invalid code. Please re-enter your code.");
}
}
Here is method which prompts user to input phone number, denies invalid characters and shows current phone number with placeholder for numbers left to input:
private static int[] GetPhoneNumber(int phoneLength = 7)
{
List<int> phoneNumbers = new List<int>();
while (true)
{
EditorFor("Phone", String.Concat(phoneNumbers), phoneLength);
var key = Console.ReadKey(intercept: true);
if (key.Key == ConsoleKey.Escape)
return new int[0]; // return empty array if user cancelled input
var c = key.KeyChar;
if (!Char.IsDigit(c))
continue;
phoneNumbers.Add(Int32.Parse(c.ToString()));
if (phoneNumbers.Count == phoneLength)
{
EditorFor("Phone", String.Concat(phoneNumbers), phoneLength);
return phoneNumbers.ToArray();
}
}
}
Prompt for input:
private static void EditorFor(string label, string value, int length)
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new String(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop);
int charactersLeftToInput = length - value.Length;
string placeholder = new String('*', charactersLeftToInput);
Console.Write("{0}: {1}{2}", label, value, placeholder);
Console.CursorLeft -= charactersLeftToInput;
}
Usage:
Console.WriteLine("Please enter the code you wish to dial.");
int[] code = GetPhoneNumber(); // if you want default length
Console:
Okay so After much deliberation I decided to use a separate Console.Read(); for each element in the array and now it's doing what I want it to do.
while ( valid == false)
{
valid = true;
callNumberArray[0] = Console.Read();
callNumberArray[1] = Console.Read();
callNumberArray[2] = Console.Read();
callNumberArray[3] = Console.Read();
callNumberArray[4] = Console.Read();
callNumberArray[5] = Console.Read();
callNumberArray[6] = Console.Read();
//etc etc...

use loop to determine if number is valid c#

I am trying to ask the user to enter a number from 2-12. I want to use a loop to check if valid, but am having trouble only displaying the result once.
Console.WriteLine("Enter number between 2 and 12");
int x = int.Parse(Console.ReadLine());
bool isValid = true;
for(int p = 2; p < 13; p++)
{
if(p > x)
{
isValid = true;
}
else
isValid = false;
if(isValid == true)
{
Console.WriteLine("{0} is good", x);
}
else
Console.WriteLine("not valid");
}
Why you need loop to check value from range ?
Try like this
if(x>=2 && x<=12)
Console.WriteLine("{0} is good", x);
else
Console.WriteLine("not valid");
Why do you want to use a loop for this?
You could check if the number is between 2 and 12 by doing this instead:
int x = int.Parse(Console.ReadLine());
bool isValid = true;
if (x < 2 || x > 12)
{
isValid = false;
}
Otherwise, if you still want to do your loop, you can try this:
Console.WriteLine("Enter a number between 2 and 12");
int x = int.Parse(Console.ReadLine());
bool isValid = false;
for(int p=2; p<13; p++)
{
if(x == p)
{
isValid = true;
break;
}
}
if(isValid==true)
{
Console.WriteLine("{0} is good", x);
}
else
{
Console.WriteLine("not valid");
}
Edit:
Also just a suggestion but you should be careful with using Parse. If you use Parse and the user enters a non-numeric character or enters a number bigger/smaller than the allowed values for int, your app will stop with a FormatException error.
To fix this, you can use TryParse instead like this:
int x;
bool result = int.TryParse(Console.ReadLine(), out x);
if (result)
{
// Put your for loop or if statement here
}
else
{
Console.WriteLine("Error: Invalid number was detected.");
}
What are you trying to achieve? There's a flaw in the logic on the sample above, where you only ask once, and then loop 10 times. To simplify you can loop and then ask for the user input until 0 is entered and the loop will exit.
Sample:
static void Main(string[] args)
{
int x = 0;
do
{
Console.WriteLine("Enter number between 2 and 12. (0 to exit)");
x = int.Parse(Console.ReadLine());
if (x >= 2 && x <= 12)
{
Console.WriteLine("{0} is good", x);
}
else if(x != 0)
{
Console.WriteLine("{0} is not valid", x);
}
} while (x != 0);
}
Console.WriteLine("Enter number between 2 and 12: ");
int x = int.Parse(Console.ReadLine());
bool isValid = (2 <= x && x <= 12);
Console.WriteLine("{0} is {1}valid", x, isValid ? "" : "not ");
Here try this
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter number between 2 and 12");
int x = int.Parse(Console.ReadLine());
if (!Enumerable.Range(1, 12).Contains(x))
{
Console.WriteLine("{0} Its not Good\n",x);
}
else
{
Console.WriteLine("{0} Its Good\n",x);
break;
}
}
Console.WriteLine("Press any key to exit..");
Console.ReadKey();
}
If you're trying to validate if the number fall within the range 2-12 you should remove your loop and use this instead
bool isValid = true;
if (x < 2 || x > 12) {
isValid = false;
}
or simply
bool isValid = x >= 2 && x <= 12;

Categories