This lab serves multiple goals:
while loops,< and <=),0,Create a new project, and replace the content of the Main method with
the following code:
int i = 0;
while(i < 100)
{
Console.WriteLine(i);
i++;
}
< with <=, and note that it prints the numbers from 0 to
100, even even though you did not change the numbers.0 with 100 and 100 with 300, and note that it prints
the numbers from 100 to 300. Observe that the counter can start from
and terminate with any number you wish.Create a new project and replace the content of the Main method with
the following code:
int n = 100;
while (n > 0)
{
Console.WriteLine(n);
n--;
}
Execute the code, and explain what you see in the console. Note that the counter is decremented, not incremented.
Create a new project and replace the content of the Main method with
the following code:
int n;
Console.Write("Enter a natural number greater than 2: ");
n = int.Parse(Console.ReadLine());
int i = 2;
while(n % i != 0 && i < n )
{
i++;
}
if (i == n)
Console.WriteLine($"{n} is a ... number");
else
Console.WriteLine($"{n} is not a ... number");
... with a meaningful word.Write a program that asks for an integer value greater than 1 from the
user, and computes the result of this series: 1 + 2 + 3 + 4 + ... up
to n where n represents the number obtained from the user.
Here is an example of the desired execution, where the user input is underlined, and hitting “enter” is represented by ↵:
Please enter an integer greater than 1:
8̲↵
The sum from 1 to your number is: 36
And you can verify for yourself that 1+2+3+4+5+6+7+8 = 36.
All of the following are examples of infinite loops. Can you spot the “problem”? For each of them, suggest an edit that would make them terminate.
int number = 0;
while (number <=5) {
Console.WriteLine("Hi!");
Console.WriteLine(number);
}
int number1 = 0, number = 0;
while (number <=5) {
Console.WriteLine("Hi!");
Console.WriteLine(number);
number1++;
}
int number = 0;
while (number <=5);
{
Console.WriteLine("Hi!");
Console.WriteLine(number);
number++;
}
int number = 0;
while (number <=5)
Console.WriteLine("Hi!");
Console.WriteLine(number);
number++;
int number = 0;
while (number <= 5)
{
Console.WriteLine("Hi!");
Console.WriteLine(number);
}
number++;
int number = 0;
while (number <= 5)
{
Console.WriteLine("Hi!");
number--;
Console.WriteLine(number);
number++;
}
Here are two advanced while loop challenges. Try to think
“off-keyboard” for a while before coding your solution, and test it
extensively.
Study the following program:
Console.WriteLine("Enter a number to sum, or \"Done\" to stop and print the total.");
string enter = Console.ReadLine();
int sum = 0;
while (enter != "Done")
{
sum += int.Parse(enter);
Console.WriteLine("Enter a number to sum, or \"Done\" to stop and print the total.");
enter = Console.ReadLine();
}
Console.WriteLine($"Your total is {sum}.");
Write a program that gets a number from the user and finds its biggest divisor less than the number itself.