Looping
We need code to keep runing the code over and over, we need loop.
There are some format loop that you've learned before:
- While
- Do-While
- For
One-must thing to remember is we need to have a break or quit from loop, to prevent looping runs forever.
We will use while loop in our FitnessFrog. Basic format of while loop shown below.
bool keepGoing = true;
while(keepGoing){
}
While loop will only executed when inside parameter, keepGoing
, valued true.
Put it inside our previous code.
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
string entry;
bool keepGoing = true;
while (keepGoing){
// Prompt the for minutes exercised
Console.Write("Enter how many minutes you exercised: ");
entry = Console.ReadLine();
int minutes = int.Parse(entry);
// Add minutes exercised to a running total
// Display the running total in minutes
Console.Write("You entered " + minutes + " minutes");
// Ask repeatedly until user quits
}
}
}
}
Good Job!
Now we want to add the number of our working minutes, let's store it in totalWorkingTime variable. When we do arithmetic operation in integer, first, we need to initialize it with 0.
int totalWorkingTime = 0;
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
string entry;
bool keepGoing = true;
int totalWorkingTime = 0;
while (keepGoing){
// Prompt the for minutes exercised
Console.Write("Enter how many minutes you exercised: ");
entry = Console.ReadLine();
int minutes = int.Parse(entry);
// Add minutes exercised to a running total
totalWorkingTime = totalWorkingTime + minutes;
// Display the running total in minutes
Console.Write("Your total working minutes is " + totalWorkingTime + " minutes");
// Ask repeatedly until user quits
}
}
}
}
There comes another problem, when the loop will be stopped?
Because our keepGoing
always true, the loop will remains forever. We need some condition to change the keepGoing
to false.