Upload
hock-leng-puah
View
2.829
Download
9
Embed Size (px)
DESCRIPTION
loop revision
Citation preview
Revision Exercises on “Loops”
while loop for loop do while Vs while loops
Agenda
while loop
int i = 0;while (i < 101){// Processing : i++; // at the end}
while loop
Write a while loop to solve the following problem
Annie has $0 at the start, she saves $300 per month. What will she save after 24 months?
Exercise 1
How many variables we need?1. saving (start from 0)2. month (start from 1)3. savingPerMth = 300
Problem solving: variables?
int saving = 0;int month = 1;int savingPerMth = 300;while (month <= 24){ saving = saving + savingPerMth; // saving += savingPerMth
month++;}Console.WriteLine(“Total saving = ” + saving.ToString() );
Possible solution
Write a while loop to solve the following problem
John has $300 at the start, she saves $100 per month.
For every 6 months after he gets his bonuses, he saves extra $500.
What will he save after 12 months?
Exercise 2
int saving = 300;int month = 1;int savingPerMth = 100;int bonus = 500;while (month <= 12){ saving += savingPerMth; // saving += savingPerMth
if ( (month%6) == 0) { saving += bonus; } month++;}Console.WriteLine(“Total saving = ” + saving.ToString() );
Possible solution
for (int i=0; i < 101; i++ ) { // Processing}
for loop
Write a while loop to solve the following problem
Annie has $0 at the start, she saves $300 per month. What will she save after 24 months?
Exercise 1 using for loop
int saving = 0;int savingPerMth = 300; for (int month=1; month<=24; month++){ saving += savingPerMth; }
Console.WriteLine(“Total saving = ” + saving.ToString() );
Possible solution
Write a while loop to solve the following problem
John has $300 at the start, she saves $100 per month.
For every 6 months after he gets his bonuses, he saves extra $500.
What will he save after 12 months?
Exercise 2 using for loop
int saving = 300;int savingPerMth = 100;int bonus = 500;
for (int month=1; month<=12; month++){ saving += savingPerMth; if ( (month%6) == 0) { saving += bonus; }}
Console.WriteLine(“Total saving = ” + saving.ToString() );
Possible solution
a) write a for loop to output 0 to 10
b) write a for loop to output 10, 8, 6, 4, 2 and 0
Exercise 3 using for loop
a) for (int x = 0; x <=10; x++) { Console.WriteLine( x.ToString() ); }b) for (int x = 10; x >=0; x = x -2) { Console.WriteLine( x.ToString() ); }
Possible solution
do loop
do{
} while ( ); // End condition
// The difference between the "while" and "do while" loops is that the code in a do while loop will get executed at least once, because its while part is at the end.