How to end loops - c#

Starting to learn about loops. It seems like these things go on forever because I am not telling it to stop. Problem is I don't know how to tell it to stop. I am assuming a statement such as != but I really do not know.
Anyone care to explain how loops stop?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication326
{
class Program
{
static void Main(string[] args)
{
bool triLoop = true;
while (triLoop)
{
Console.WriteLine("Please enter the first integer...");
int firstInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the second integer...");
int secondInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the third integer...");
int thirdInt = int.Parse(Console.ReadLine());
if ((firstInt + secondInt > thirdInt) && (secondInt + thirdInt > firstInt) && (firstInt + thirdInt > secondInt))
{
Console.WriteLine("The numbers {0}, {1}, and {2} CAN represent sides of the same triangle.", firstInt, secondInt, thirdInt);
}
else
{
Console.WriteLine("The numbers {0}, {1}, and {2} CANNOT represent the sides of the same triangle.", firstInt, secondInt, thirdInt);
}
}
}
}
}

The break statement will "break out" of a loop.
Alternatively, you can just set your boolean value (triLoop) to false.

Anyone care to explain how loops stop
While loop will run for as long as the condition within the loop is true. In order to break it you need to set the expression in the while loop to false.
it will stop when you set triLoop to false. You should read the documentation.
while(triLoop)
{
if(somecondition)
triLoop = false; //loop will not run after this
}
a basic example of this. This loop will run till 5.
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}

Set triLoop to false. Or use break;.

Other answers have explained how the condition works, but if you want to ask the user whether they want to continue, you could add this to the end of your loop:
Console.WriteLine("Would you like to continue? (Y/N)");
if(Console.ReadLine() == "Y")
triLoop = false;
Then the condition will evaluate to false if the user types "Y", and the loop will end.

There are multiple answers.
break; //exits the loop and continues with the code
return; //stops the loop and doesn't proceed with the rest of the code
In your case, you can also set triloop to false.

use this in loops to stop loops
break;

as you are using while loop
while (triLoop)
{
}
this loop runs while triLoop variable is true
you need to set it to false somewhere within while loop
like
while (triLoop)
{
//your code
// on some condition
triLoop = false;
}
or
while (triLoop)
{
//your code
// on some condition
break;
}

try this:
while (triLoop)
{
Console.WriteLine("Please enter the first integer...");
int firstInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the second integer...");
int secondInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the third integer...");
int thirdInt = int.Parse(Console.ReadLine());
if ((firstInt + secondInt > thirdInt) && (secondInt + thirdInt > firstInt) && (firstInt + thirdInt > secondInt))
{
Console.WriteLine("The numbers {0}, {1}, and {2} CAN represent sides of the same triangle.", firstInt, secondInt, thirdInt);
}
else
{
Console.WriteLine("The numbers {0}, {1}, and {2} CANNOT represent the sides of the same triangle.", firstInt, secondInt, thirdInt);
}
Console.WriteLine("press 0 if you want to continue...");
int flag = int.Parse(Console.ReadLine());
if(flag!=0) break;
}

Related

why loop set do end when set to false althoght I the it suppused to be true

Hi I'm a noob C# programmer and I need some help here
I'm trying TryParse function and here is my code:
while (bContinue)
{
Console.Write("Enter a number: ");
// string numInput = Console.ReadLine();
int num = 0;
bool success = int.TryParse(Console.ReadLine(), out num);
if (success)
{
bContinue = false;
Console.WriteLine("\nYou have entered " + num + "\n Salam");
}
else
Console.WriteLine("Invalid input");
}
this code working perfectly fine but I tried to do it in another way:
bool success = true;
while (success == true)
{
Console.Write("Enter a number: ");
// string numInput = Console.ReadLine();
int num = 0;
success = int.TryParse(Console.ReadLine(), out num);
if (success)
{
Console.WriteLine("\nYou have entered " + num);
success = false;
}
else
Console.WriteLine("Invalid input");
}
in the first code the loop end when entering valid number but in the second code the the reverse is happening the loop end when enter invalid number which is word. Also, in the second code the VS is saying that "success = false;" is redundent and it is suggesting to remove it.
Any idea?
In the first code the loop end when entering valid number but in the second code the the reverse is happening the loop end when enter invalid number which is word.
In the second loop, the success variable is set to false, no matter the outcome of TryParse, which causes the loop to terminate when it receives any value, valid or not.
Assuming that you're trying to make the loop continue until a valid value is entered, your first loop should work, but if you want simpler code, you should try this:
bool success;
do {
Console.Write("Enter a number: ");
success = Int32.TryParse(Console.ReadLine(), out int num);
if (success) Console.WriteLine($"You have entered {num}.");
else Console.WriteLine("Invalid input.");
} while (!success);
Also, in the second code the VS is saying that "success = false;" is redundent and it is suggesting to remove it.
success = false shouldn't be redundant and I agree with Lasse's comment above; I put the code into Visual Studio and IntelliSense didn't say anything about it (besides not needing to assign a value to num, etc.)

How to prevent input of null enter in C# [duplicate]

This question already has answers here:
check for valid number input - console application
(5 answers)
Allow To Only Input A Number - C#
(1 answer)
Closed 2 years ago.
I have just started a table programme. I am just a trainee learning C# from internet, so I am not so good in this.
I just wanted the programme to run according to the user. I want that if the user hits enter simply, the programme should not crash. That is I just wanted to know how to prevent null enter. This is the code is used:
The "______" which used if for writing a line
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tables
{
class Program
{
static void Main(string[] args)
{
goto found;
found:
Console.WriteLine("");
string textToEnter = "MULTIPLATION TABLES";
Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (textToEnter.Length / 2)) + "}", textToEnter));
Console.WriteLine("");
Console.WriteLine("________________________________________________________________________________");
Console.WriteLine("");
int num, j, i;
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32( Console.ReadLine());
while (num == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32(Console.ReadLine());
}
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
while (j == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
}
i = Convert.ToInt32(j);
for (j=1; ; j++)
{
if (j > i)
{
break;
}
Console.WriteLine(num + " * " + j + " = " + num * j);
}
string str;
Console.Write("do you want to continue? (y/n) :- " );
str= Console.ReadLine();
foreach (char ch in str)
{
if (ch == 'y')
{
goto found;
}
else if (ch=='n' )
{
Console.WriteLine("");
Console.WriteLine("THANK YOU FOR USING MY PRODUCT");
}
else
{
Console.WriteLine("please enter a valid input");
}
}
Console.ReadKey();
}
}
}
As suggested in the comments, I'd use int.TryParse(), but inside a do...while() loop. Use a separate flag (boolean) to track whether the user should keep trying again:
bool invalid;
int num, j, i;
do
{
invalid = true;
Console.Write("enter the number of which table u need ? :- ");
String response = Console.ReadLine();
if (int.TryParse(response, out num))
{
invalid = false;
}
else
{
Console.WriteLine("Invalid input. Please try again.");
}
} while (invalid);
// ...repeat the above do...while() block for "j" and "i"...
When you're accepting user input, it's important to perform validation on it. You can't assume that the user will always enter correctly formatted data that your program will be able to work with. As you discovered, a user who hits enter will give you an empty string (""), which can't be parsed to anything.
C# has several ways of attempting parsing. The first, which you're using, is Convert.ToInt32(), which throws an exception if the input it receives is not, in fact, a number. You have to catch the exception with a try/catch block, like so:
try
{
num = Convert.ToInt32(Console.ReadLine());
}
catch(FormatException ex)
{
Console.WriteLine("You didn't enter a proper number!");
}
However, in general, exceptions should be, well, exceptional. They should only be relied upon when rare failures occur, because unwinding the call stack can be expensive.
I would argue that C# has a better method for you to use in this instance: Int32.TryParse()
You can see the documentation here.
TryParse takes two parameters, the thing you're trying to parse (convert), and then a number to store the value in. It returns true or false, indicating if it succeeded or failed in converting the number.
You might use it like this:
var success = Int32.TryParse(Console.ReadLine(), num);
if (success)
{
// do something with 'num' -- it has a valid value now.
}
else
{
// Warn the user, perhaps prompt them to try again
Console.WriteLine("That wasn't a valid number!");
}
You can use a methode to get a safe int value:
private static int ReadIntValue(string psMessage)
{
int lnInt;
string lsValue = string.Empty;
do
{
Console.Write(psMessage);
lsValue = Console.ReadLine();
} while (!int.TryParse(lsValue, out lnInt));
return lnInt;
}
And then use this:
num = ReadIntValue("enter the number of which table u need ? :- ");

TryParse in C# and using the while loop

The user Input should be within 0 to 10 and I want to use tryparse and check if the input is correct, if not then it should prompt the user again. my code is like below it only works once but if the user enters the wrong number it again executes. In this case, where should I put the loop?
int number;
bool True;
Console.Write("Enter number between 0 t0 10: ");
True = int.TryParse(Console.ReadLine(), out number);
while (number < 0 || number > 10)
{
while (True)
Console.Write("Enter number between 0 t0 10: ");
int.TryParse(Console.ReadLine(), out number);
}
{
Console.WriteLine("Please enter the correct number");
}
return number;
use do while .
int i = 0;
do
{
Console.Write("Enter number between 0 t0 10: ");
True = int.TryParse(Console.ReadLine(), out number);
} while (!True);
I'd write similar code to what you already have, but I'd rename True to isValid and use a do/while loop:
int number;
bool isValid = false;
do
{
Console.Write("Enter number between 0 and 10: ");
isValid = int.TryParse(Console.ReadLine(), out number)
&& number >= 0
&& number <= 10;
if (isValid)
{
Console.WriteLine("Please enter the correct number");
}
}
while (!isValid);
Better yet, do away with isValid altogether:
int number;
do
{
Console.Write("Enter number between 0 and 10: ");
if (int.TryParse(Console.ReadLine(), out number) && number >= 0 && number <= 10)
{
break;
}
Console.WriteLine("Please enter the correct number");
}
while (true);
Now, if the number is valid, we simply break out of the loop.
P.S. You'll see that I swaped the number conditions around to make them validity checks instead, so < became >= and > became <=.
Also, don't call a variable something like True. Imagine you're reading through a longer method and you come across this line (months after you've written it):
while (True)
That's an endless loop right? Oh no! It's the variable True, not the constant true. Now imagine further up you havebool True = false;. If you're reading quickly, you might misunderstand what the code does. Even if you're not, you have to put more mental effort into understanding what's happening.

Number guessing game using TryParse

I´m having problems with getting my code to work while using TryParse to catch if the user where to input a string instead of a int. If I use it as it looks now I only get the base value of 0 if something other than an int is input. I want it to show an error message to the user.
Have tried messing around with a number of different ways of using TryParse but none of them has really been helpfull.
static void Main(string[] args)
{
Random r = new Random();
int speltal = r.Next(1,21);
bool play = false;
int myNum;
while (!play)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
Int32.TryParse(Console.ReadLine(), out myNum);
if (myNum < guessNum)
{
Console.WriteLine("\tThe number you have guessed is to low");
Console.ReadLine();
}
if (myNum > guessNum)
{
Console.WriteLine("\tThe number you have guessed is to high");
Console.ReadLine();
}
if (myNum == guessNum)
{
Console.WriteLine("\tCongratulations you guessed the right number!");
Console.ReadLine();
}
I want it show an error message to the user if they put in anything other than a int. It also have to include TryParse according to my teatcher
You're not capturing the bool output of TryParse so you have no idea if a non-numeric value was entered. Try something like this:
bool isValid;
do
{
Console.Write("\n\tGuess a number between 1 and 20: ");
isValid = Int32.TryParse(Console.ReadLine(), out myNum);
if(!isValid)
{
Console.WriteLine("\n\tInvalid input detected. Please try again.");
}
} while(!isValid)
The TryParse method can only put integers in the passed variable (as it is of type int), so if the value passed to it can't be parsed into an integer, the default value of int (0) will be assigned to the variable.
The way TryParse tell you if it successfully parsed the number or not, is by returning a boolean indicator.
You can try this:
while (true)
{
bool valid = int.TryParse(Console.ReadLine(), out myNum);
if(valid)
break;
Console.WriteLine("Input invalid. Please try again");
}
TryParse returns a Boolean which indicates if the input string was successfully parsed or not. Both of the answers above are correct on how to handle a invalid input but, here is a cleaner version which will also uphold the rule, between 1 and 20:
while (true)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
//Checks to see if the input was successfully parsed to a integer also, performs a Trim on the input as to remove any accidental white spaces that a user might have typed in, e.g. "1000 "
if (int.TryParse(Console.ReadLine().Trim(), out myNum))
{
//Checks to see if the parsed number is in the specified range
if ((myNum > 0) && (myNum < 21))
{
break;
}
Console.WriteLine("\tThe input number was out of the specified range.");
}
else
{
Console.WriteLine("\tFailed to parse the input text.");
}
//Optional, makes the thread sleep so the user has the time to read the error message.
Thread.Sleep(1500);
//Optional, clears the console as to not create duplicates of the error message and the value of Console.Write
Console.Clear();
}
// Continue here, if (myNum < guessNum) . . .
You should use the bool returned by TryParse. Something that looks like this:
Updated answer:
static void Main(string[] args)
{
Random random = new Random();
int guessNum = random.Next(1, 21);
while(true)
{
Console.WriteLine("Guess the number between 1 and 21.");
if (Int32.TryParse(Console.ReadLine(), out int input))
{
if (input == guessNum)
{
Console.WriteLine($"You guessed it right. The number is {input}");
if(ShouldContinue())
{
guessNum = random.Next();
continue;
}
else
{
break;
}
}
if (input < guessNum)
Console.WriteLine("The number you guessed is smaller.");
else
Console.WriteLine("The number you guessed is bigger");
}
else
{
Console.WriteLine("Please enter a number between 1 and 21 as your guess");
}
}
}
static bool ShouldContinue()
{
while (true)
{
Console.WriteLine($"Do you want to continue playing? (y/n)");
string continueInput = Console.ReadLine().Trim().ToLower();
if (continueInput == "y")
return true;
else if (continueInput == "n")
return false;
else
Console.WriteLine("Invalid input!. Please choose 'y' or 'n'.");
}
}
Old answer:
while (true)
{
if (Int32.TryParse(inputInt, out int myNum))
{
// your logic goes here, too low/high or correct answer.
}
}

c# Need help trying to put in and run two loops for the same input

I've put in a loop with Try.Parse so that if the user enters a decimal number, the program will ask them to enter another number until they put in a integer and then the program will carry on with the next part.
However what i'm struggling with is putting in another loop that makes it so that the user can only enter a number between 1 and 100, and if they don't there should be an error message that loops until they do enter this. Id like them to run at the same time and i have this one, but i want it to also check whether its in the range and i'm not sure how to do that.
I'm new to programming so I'm not great at this.
Thank you in advance!
string inputcost;
string inputmoney;
int validcost;
int validmoney;
int changereq;
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
bool result = int.TryParse(inputcost, out validcost);
while (!int.TryParse(inputcost, out validcost))
{
if (result == true)
{
Console.Write("Valid Value");
}
if (result == false)
{
Console.Write("Please Enter A Valid Integer Value");
Console.WriteLine();
inputcost = Console.ReadLine();
}
}
Your problem here is that the result variable you're looking at is only written once: outside the loop. Consider trying something like the following pseudocode (a do-while loop works exactly the same as a while loop, except it always gets executed once before the condition is checked):
bool validInput;
do
{
// If you set it true to begin with, you can set it false on any unmet conditions
// If it doesn't get set false, you've got a valid input and can exit the loop.
validInput = true;
Read input from user
Check if it's a valid integer, if not print message and validInput = false
Check if it's between 1-100, if not print message and validInput = false;
} while (!validInput);
Then if you want to tackle something more advanced, look at the continue keyword.
Try something like this.
string inputcost;
string inputmoney;
int validcost;
int validmoney;
int changereq;
while (true)
{
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
if (!(valuecost >=1 && valuecost <=100))
{
Console.Write("Please enter value between 1 and 100.");
}
bool result = int.TryParse(inputcost, out validcost);
if (result == true)
{
Console.Write("Valid Value");
}
if (result == false)
{
Console.Write("Please Enter A Valid Integer Value");
}
}
It would be useful to use a method and do something like:
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
bool result = false;
while (!result)
{
result = checkNumber();
}
public static bool checkNumber()
{
if(inputcost < 1 || inputcost > 100)
{
Console.Write("Please Enter a valid value: ");
inputcost = Console.ReadLine();
return false;
}
else
return true;
}
Hope this helps.
string inputcost;
string inputmoney;
int validcost = 0;
int validmoney = 0;
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
// only accept integers
while (!int.TryParse(inputcost, out validcost))
{
Console.Write("Please Enter An Integer Value: ");
inputcost = Console.ReadLine();
}
// valid integer input in variable validcost
bool done = false;
while (!done)
{
Console.Write("Enter an integer between 1 and 100: ");
inputmoney = Console.ReadLine();
if (int.TryParse(inputmoney, out validmoney))
{
if (validmoney > 0 && validmoney < 101)
{
done = true;
}
else
{
Console.WriteLine("Invalid input: " + inputmoney);
}
}
else
{
Console.WriteLine("Invalid input: " + inputmoney);
}
}
//validcost is an integer and validmoney is an integer between 1 and 100
Console.WriteLine("validcost: " + validcost + " validmoney: " + validmoney);
Console.ReadKey();

Categories

Resources