4. while loop inti = 0; while (i < 101) { // Processing : i++; // at the end }
5. 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
6. How many variables we need? saving (start from 0) month (start from 1) savingPerMth = 300 Problem solving: variables?
7. int saving = 0; int month = 1; intsavingPerMth = 300; while (month <= 24) { saving = saving + savingPerMth; // saving += savingPerMth month++; } Console.WriteLine(“Total saving = ” + saving.ToString() ); Possible solution
8. 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
9. int saving = 300; int month = 1; intsavingPerMth = 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
10. for loop for (inti=0; i < 101; i++ ) { // Processing }
11. 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
12. int saving = 0; intsavingPerMth = 300; for (int month=1; month<=24; month++) { saving += savingPerMth; } Console.WriteLine(“Total saving = ” + saving.ToString() ); Possible solution
13. 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
14. int saving = 300; intsavingPerMth = 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
15. 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
16. 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
17. 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.