TPS 5: Loops
- Due Mar 3, 2021 by 10am
- Points 1
- Submitting a file upload
- File Types doc and docx
- Available after Mar 3, 2021 at 9am
Although we haven't talked about it in detail in class, the readings covered the modulo (%) operator. If x and y are integers, the C++ expression `x / y` tells us how many times y goes into x evenly—recall that integer revision always truncates the result, meaning the fractional component is removed. The expression `x % y` (read as "x mod y") tells us what the remainder is after performing `x / y`. This number will always be in the range 0 (in the event that x goes into y exactly) and (y-1). Here are some examples:
- 50 % 10 is 0, because 10 goes into 50 five times with no remainder
- 10 % 50 is 10, because 50 goes into 10 zero times with 10 left over
- 6092394925 % 10 is 5, because 10 goes into 6092394925 609239492 times with 5 left over (when modding by 10, you really just need to look at the right most digit of x to find the result quickly)
We'll use mod for several purposes this semester, one of them being to test even and oddness. All even numbers, by definition, are divisible by 2. That means if we take any even number and mod by 2, the result should be 0 because there shouldn't be any remainder. Odd numbers, on the other hand, are always one away from an even number, and thus modding them by 2 will result in a value of 1:
- 1 % 2 is 1
- 2 % 2 is 0
- 3 % 2 is 1
- 4 % 2 is 0
- ...
- 6092394925 % 2 is 1
- 6092394926 % 2 is 0
- ...
For this TPS, write the C++ implementation of the pseudo code (lines 17–19), which will print only the even the numbers in a given range.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> using namespace std; int main(){ int start, end, value; // Read in the range from the user. cout << "Enter start of range: "; cin >> start; cout << "Enter end of range: "; cin >> end; // Print the even numbers. cout << "Even numbers:" << endl; // TODO: Implement this pseudo code: // for each value between start and end: // if the value is even: // print the value return 0; } |
After we've completed the group share portion, upload a copy of your updated TPS document.