Last Time v We learnt about while loops
Last Time v We learnt about ‘while’ loops. v The three key ingredients of ‘while’ loops are: Ø Initialize the loop control variable Ø Test the loop control variable Ø Update the loop control variable v Loops can be used to: Ø Repeat operations Ø Accumulate a sum or product CS 150 Introduction to Computer Science 1 1
Accumulating a sum count = 1; sum = 0; while (count <= 5) { sum = sum + count; count ++; } cout << “The sum of the first 5 integers is: “ << sum << endl; CS 150 Introduction to Computer Science 1 2
Compound Assignment Operators v What if we want to increment by more than 1? Ø sum = sum + 2; => sum += 2; v What if we want to use a shortcut for other assignments? Ø double = double * 2; => double *= 2; Ø cents = cents%25; => cents %= 25; CS 150 Introduction to Computer Science 1 3
More. . . v How can we accumulate a sum of the first 5 even integers, starting with 2? v How can we accumulate the product of the first 5 integers, starting with 1? CS 150 Introduction to Computer Science 1 4
Example v What’s the output for x = 2? 3? 5? cout << “Enter an integer”; cin >> x; product = x; count = 0; while (count < 4) { cout << product << endl; product *= x; count += 1; } CS 150 Introduction to Computer Science 1 5
More Examples v What’s wrong? Correct the program: count = 0; while (count <= 5) cout << “Enter data item; “; cin >> item; item += sum; count += 1; cout << count << “ data items” << “were added” << endl; cout << “Their sum is “ << sum << endl; CS 150 Introduction to Computer Science 1 6
More v Write a program that reads in 5 grades and computes their average v Write a program that reads in an inputted number of grades and computes the average CS 150 Introduction to Computer Science 1 7
More Examples v Write a program that reads in an indeterminate number of grades and computes the average. The last input will be 99999. The program should end if there are more than 20 grades. v How can you add error checking for invalid grade values? CS 150 Introduction to Computer Science 1 8
- Slides: 8