STD511: C# Programming
Control Structures:
Repetition
while Loop
count = 0;
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) [Link]("Welcome to C#!");
(loop body) count++;
(A) (B)
while Loop
while (loop-continuation-condition)
{
// loop-body;
Statement(s);
}
int count = 0;
while (count < 100)
{
[Link]("Welcome to C#!");
count++;
}
Exercise
• s to print the numbers 1
Write a C# program
..100.
• Write a C# program to find the sum of the
numbers 1..100.
• Write a C# program to read ten numbers and
finds their sum and average.
• Write a C# program to read ten numbers and
finds the number of evens and odds.
Problem: Guessing Numbers
Write a program that randomly generates an integer between
0 and 100, inclusive. The program prompts the user to enter a
number continuously until the number matches the randomly
generated number. For each user input, the program tells the
user whether the input is too low or too high, so the user can
choose the next input intelligently.
5
Ending a Loop with a
Sentinel Value
• Often the number of times a loop is executed is not predetermined.
You may use an input value to signify the end of the loop. Such a
value is known as a sentinel value.
Write a program that reads and calculates the
sum of an unspecified number of integers. The
input 0 signifies the end of the input.
6
do-while Loop
Statement(s)
(loop body)
true Loop
Continuation
do { Condition?
false
// Loop
body;
} while (loop-continuation-condition);
Statement(s);
7
for
Loops
In itia l-A ctio n i= 0
Loop
false false
C o n tin u a t io n (i < 1 0 0 )?
C o n d itio n ?
tru e tru e
S tate m e n t( C o n s o l e . Wr i t e L i n
s) (lo o p
body) e(
" W elco m e
A ctio n - A fter-E a c h -Iteratio n to C # " );i + +
(A ) (B )
for
Loops
for (initial-action; loop-continuation-condition;
action-after-each-iteration)
{
// loop
body;
Statement(s);
}
int i;
for (i = 0; i < 100; i++)
{
[Link](
"Welcome to C#!");
}
9
Nested Loops
Problem: Write a program that uses nested
for
loops to print a multiplication table.
10
public class TestBreak {
break
public static void Main(String[] args)
{ int sum = 0;
int number = 0;
while (number < 20)
{ number++;
sum += number;
if (sum >=
100)
break;
}
[Link]("The number is " +
number); [Link]("The sum is " +
sum);
}
}
11
continue
public class TestContinue {
public static void Main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11)
continue;
sum += number;
}
[Link]("The sum is " + sum);
}
}
12
Reference
• C# Programming for Absolute Beginners;
Radek Vystavel.
• [Link]
amming-language/
• [Link]
arp/