A while loop statement will repeatedly execute a statement as long as the given condition is true. If the while loop's condition is set to true then the program will go into the loop, and will keep looping as long as that condition remains true. For example:
int score = 15;
while (score < 20)
{
Console.WriteLine("value of score: {0}"), score;
score++;
}
Console.ReadLine();
In this example the program will go into the loop for as long as the value of score is less than 20. Once it's in the loop it will increment the value of score by one, then it will check if a is still less than 20. Once the value of score reaches 20, it will no longer go into the loop as the condition will no longer be true.
A IF statement on the other hand can be a bit similar to a while statement, as it will check the condition at first, and if it's true it will execute the block of code inside of it. IF the condition is true it will run the code but it will only do it once as compared to a while statement. One can also use an ELSE statement to run a different set of code if the condition is false. Example:
Both WHILE and IF statements can be used together in programming, as for example one can have a while statement running for as long as the value of quit is set to false. Inside of the while loop you can use an IF statement to check if the user wants to quit the program. For example:
bool quit = false;
string userResponse;
while (quit == false)
{
Console.WriteLine("enter Q to quit")
userResponse = Console.ReadLine();
If (userResponse == "Q")
{
Console.WriteLine("Until next time!");
Goodbye();
}
}
Sources:
http://www.tutorialspoint.com/csharp/csharp_while_loop.htm
https://msdn.microsoft.com/en-us/library/5011f09h.aspx
http://www.tutorialspoint.com/csharp/if_else_statement_in_csharp.htm
Comments
Post a Comment