Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS150 Introduction to Computer Science 1

Similar presentations


Presentation on theme: "CS150 Introduction to Computer Science 1"— Presentation transcript:

1 CS150 Introduction to Computer Science 1
Last Time We learnt about ‘while’ loops. The three key ingredients of ‘while’ loops are: Initialize the loop control variable Test the loop control variable Update the loop control variable Loops can be used to: Repeat operations Accumulate a sum or product 2/17/2019 CS150 Introduction to Computer Science 1

2 CS150 Introduction to Computer Science 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; 2/17/2019 CS150 Introduction to Computer Science 1

3 Compound Assignment Operators
What if we want to increment by more than 1? sum = sum + 2; => sum += 2; What if we want to use a shortcut for other assignments? double = double * 2; => double *= 2; cents = cents%25; => cents %= 25; 2/17/2019 CS150 Introduction to Computer Science 1

4 CS150 Introduction to Computer Science 1
More... How can we accumulate a sum of the first 5 even integers, starting with 2? How can we accumulate the product of the first 5 integers, starting with 1? 2/17/2019 CS150 Introduction to Computer Science 1

5 CS150 Introduction to Computer Science 1
Example 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; } 2/17/2019 CS150 Introduction to Computer Science 1

6 CS150 Introduction to Computer Science 1
More Examples 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; 2/17/2019 CS150 Introduction to Computer Science 1

7 CS150 Introduction to Computer Science 1
More Write a program that reads in 5 grades and computes their average Write a program that reads in an inputted number of grades and computes the average 2/17/2019 CS150 Introduction to Computer Science 1

8 CS150 Introduction to Computer Science 1
More Examples Write a program that reads in an indeterminate number of grades Write a program that reads in an indeterminate number of grades and computes the average. The last input will be The program should end if there are more than 20 grades. How can you add error checking for invalid grade values? 2/17/2019 CS150 Introduction to Computer Science 1


Download ppt "CS150 Introduction to Computer Science 1"

Similar presentations


Ads by Google