+ All Categories
Home > Documents > EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function...

EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function...

Date post: 18-Jul-2020
Category:
Upload: others
View: 4 times
Download: 0 times
Share this document with a friend
14
EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’ grades (as integers), and returns the sum. The number of grades to read is specified by the function’s argument. Write the implementation of getStudentPoints below. /** * Requires: studentCount is greater than zero * Modifies: cout, cin * Effects: prompts the user to enter student grades, reads in a single grade * for each student, and returns the sum of all values entered */ int getStudentPoints(int studentCount); int getStudentPoints(int studentCount) { cout << "Grades: "; int sum = 0; for (int i = 0; i < studentCount; i++) { int grade; cin >> grade; sum += grade; } return sum; } Maxim Aleksa ([email protected]) 0 < 14 http://maximal.io/eecs183
Transcript
Page 1: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 6Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’ grades (as integers), and returns the sum. The number of grades to read is specified by the function’s argument.

Write the implementation of getStudentPoints below.

/** * Requires: studentCount is greater than zero * Modifies: cout, cin * Effects: prompts the user to enter student grades, reads in a single grade * for each student, and returns the sum of all values entered */ int getStudentPoints(int studentCount);

int getStudentPoints(int studentCount) { cout << "Grades: "; int sum = 0; for (int i = 0; i < studentCount; i++) { int grade; cin >> grade; sum += grade; } return sum; }

Maxim Aleksa ([email protected]) 0 < �14 http://maximal.io/eecs183

Page 2: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 6Lab 4: Nested Loops

Thinking about nested loops…

test.cpp

#include <iostream> #include "loops.h" using namespace std;

int main() { somePrintFn(1); somePrintFn(5); }

loops.h

// prototypes

/** * RME */ void somePrintFn(int n);

loops.cpp

#include "loops.h"

// implementations

void somePrintFn(int n) { // TODO }

print_rectangle(5, 4);

**** **** **** **** ****

print_right(5);

* ** *** **** *****

print_right_justified(5);

* ** *** **** *****

Maxim Aleksa ([email protected]) 1 < �14 http://maximal.io/eecs183

Page 3: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 6General 0. At which location do you have to take the exam? See https://eecs183.org/exams/1 1. Source code vs. object code?

Source code is somewhat English-looking code that is written and understood by humans. It is then compiled to object code, composed of 0s and 1s that are understood by the computer.

2. What’s a library?A library is a collection of pre-written code, available to use if #included (e.g., cmath).

3. (T/F) All .cpp files must have a main function.False. All C++ programs must have a main function, but a C++ program can be made up of several .cpp (and .h) files and only one of those .cpp files must have a main function.

Variables 4. Name main data types in C++.

int, double, bool, char, string 5. Is string a native data type in C++? What do you need to do atop the .cpp file to use

strings?string is not a native data type in C++ and we need to #include <string> in order to be able to use it.

6. When does implicit conversion of data types happen in C++? When does it not happen? Implicit conversion happens between int, double, bool and char when passing an argument by value to a function, when assigning a value to a variable or when returning a value:int x = 3.14; int ASCII_value_of_A = ‘A'; int result = sqrt(9);Implicit conversion does not happen when passing an argument by reference.

7. How are these two lines of code different?

The first line creates (i.e., declares) a new variable x of type int and sets its value (i.e., initializes it) to 5. The second line just sets the value of x to 6 and does not create a new variable.

8. Any problems with this line of code?

Integer overflow. 9. What is wrong with this line of code?

5 / 9 happens before cast to double and results in 0, so celsius is always set to 0.

int x = 5;x = 6;

int someNumber = 1000 * 1000 * 1000 * 1000;

double celsius = static_cast<double>(5 / 9) * (fahrenheit - 32);

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 4: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 610. What are the differences between variables and constants? What are naming conventions

for each?Variables can change value and are named likeThis or like_this. Constants cannot change value and are named LIKE_THIS.

11. Which of the following are valid variable declarations?

1f is invalid because it begins with a number. if is invalid because if is a keyword in C++. if1 is valid. f+1 is invalid because + cannot be part of a variable name.

12. What prints?

1 1

13. Given two ints, a and b, how to divide a by b and get a double back? double result = (double) a / b; ordouble result = static_cast<double>(a) / b;

14. What’s the best way to compare two variables of type double for equality? Instead of comparing with ==, as in if (a == b) {,check how close two doubles are with if (abs(a - b) < 0.0000001) {.

I/O 15. cin >> str; vs. getline(cin, str);? When to use each?

cin >> str works with strings, numbers and characters. It skips leading whitespace and reads until whitespace or type mismatch (e.g., a letter if reading into a variable of type int).getline only works with strings. It does not skip leading whitespace and reads until the end of the line. Next reading will start on the following line.

16. What do \', \", \n, \t and \\ do?There are escape sequences that are used to represent characters that are otherwise difficult to type. \' is a single quote ('), \" is a double quote ("), \n is new line, \t is tab, and \\ is a backslash (\).

17. Consider the following code:

What prints if the user types the following?

2 is read into x, . is read into ch and 5 is read into y.10 prints.

int 1f; int if; int if1; int f+1;

int x = 18 / 5 – 5 / 2; cout << x << endl; double y = 18 / 5 – 5 / 2; cout << y << endl;

x gets 3 - 2 = 1 1 is printed y gets 3 - 2 = 1 1 is printed

int x = 2, y = 4; char ch; cin >> x >> ch >> y; cout << x * y << endl;

2.5 * 2.0<Enter>

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 5: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 6Functions 18. In the following code, mark declaration, prototype, function call, definition,

implementation, signature, header, argument/parameter list, return type, return statement.

19. What is the difference between prototype and implementation?The implementation (definition) gives all the information that the compiler needs to know about a function. It consists of a header (return type, function name and parameter list) and the body (code within the curly braces that executes when the function is called). The prototype (declaration) matches the header of the function definition, except that it ends with a semicolon. The function prototype lets us define function functions after main and call them before the compiler has seen their definitions.

20. Which of the following are valid function prototypes?

21. If a variable fillColor is accessible only within function drawRect, then fillColor is known as… a local variable

22. What is RME?RME is a multiline comment above a function prototype. It consists of three parts: Requires (what the function assumes about its parameters) Modifies (what the function changes outside of its local scope, such as cout or pass-by-reference parameters)Effects (what the function does and what it returns.

23. How is RME interpreted by the C++ compiler?RME is a comment, so it is ignored by the compiler.

#include <iostream> using namespace std;

/** * Requires: Nothing. * Modifies: Nothing. * Effects: Returns sum of a and b. */ int add(int a, int b);

int main() { int sum = add(1, 2); cout << sum << endl; }

int add(int a, int b) { int sum = a + b; return sum; }

char void(double x); int maximum(x, y); int calc(void x); void squareRoot(double x);

invalid function name parameters need types invalid parameter type valid

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 6: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 624. Implement max, a function that returns the maximum of the three arguments passed in.

Conditions 25. (T/F) if is a function.

False. if is a statement. 26. How are these two snippets of pseudocode different?

27. For each expression in the left column, find its complement in the right column and write the letter of the complement on the blank.

28. (T/F) Order of conditions in a sequence of if / else if / else statements matters.True.

29. (T/F) It is possible to write every sequence of if / else if / else statement as a switch statement.False. switch matches only ints, chars and bools. It does not work with strings, for example.

30. (T/F) It is possible to write every switch statement as a sequence of if / else if / else statements.True.

31. What does this code print? Does the program crash (i.e., have a runtime error)?

false prints. (3 == 4) is false, and (3 / 0 == 4) is not executed due to short-circuit evaluation. The program does not crash because division by 0 does not happen.

int max(int a, int b, int c);

int max(int a, int b, int c) { if (a >= b && a >= c) { return a; } else if (b >= c) { return b; } else { return c; } }

if conditionA: do something if conditionB: do something else if conditionC: do this other thing

if conditionA: do something else if conditionB: do something else else if conditionC: do this other thing

________ price < 50________ 20 <= price && price < 50 ________ 20 > price || price > 50 ________ price < 50 && inStock ________ !inStock || price < 50

A. price < 20 || price >= 50 B. price >= 50 && inStock C. price >= 50 && !inStock D. price >= 50 || !inStock E. price >= 50 F. price >= 20 && price <= 50

if ((3 == 4) && (3 / 0 == 4)) { cout << "true" << endl; } else { cout << "false" << endl; }

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 7: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 632. What prints?

non-zero prints.(x = 0) assigns 0 to x. The value 0 (the value that is assigned to x) is used as the condition. 0 is false, so the execution goes to the else block.

33. Find (and fix!) errors with in the snippet of code below.

34. Rewrite this expression without using && (isStudent is of type bool and age is of type int):

Loops 35. For loops vs. while loops? When to use each?

For loops and while loops are interchangeable and either can be used. However, for loops are generally used when the number of iterations is known and while loops are used for conditions that are based on some event. Also, if the loop variable is declared inside the for loop, as in for (int i = 0; ...; ...) {, it goes out of scope after the for loop and cannot be used.

36. (T/F) It is possible to write every for loop as a while loop.True.

37. (T/F) It is possible to write every while loop as a for loop.True.

38. Rewrite this for loop as a while loop:

int x = 0; if (x = 0) { cout << "zero" << endl; } else { cout << "non-zero" << endl; }

int lecture = getLectureNumber();

if (lecture == 1 || 3) { string instructor = "Bill Arthur"; } else if (lecture == 2) { string instructor = "Héctor García"; } else if (lecture == 3) { string instructor = "Mary Lou Dorf"; } else { string instructor = "Staff"; }

cout << "Your professor is " << instructor << endl;

isStudent && age >= 18

for (int i = 10; i > 0; i--) { cout << i << endl; }

int i = 10; while (i > 0) { cout << i << endl; i--; }

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 8: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 639. Write a loop that prints a triangle of stars of height 4:

40. Write a loop that prints an upside-down triangle of stars of height 4:

41. What does this snippet of code print?

20 4 0 0 0 0 ... (infinite loop) 42. What does this loop print?

Nothing prints. 43. Implement countOnes, a function that counts how many ones are in the integer passed as

an argument and returns the count. Here’s its declaration:

* ** *** ****

for (int i = 0; i < 4; i++) { for (int j = 0; j <= i; j++) { cout << '*'; } cout << endl; }

**** *** ** *

for (int i = 0; i < 4; i++) { for (int j = 0; j < i; j++) { cout << ' '; } for (int j = i; j < 4; j++) { cout << '*'; } cout << endl; }

int x = 100; while (x >= 0) { x /= 5; cout << x << " "; }

for (int i = 0; i >= 3; i++) { cout << 'X'; }

int countOnes(int n);

int countOnes(int n); n = abs(n); int numberOfOnes = 0; while (n != 0) { int lastDigit = n % 10; n = n / 10; if (lastDigit == 1) { numberOfOnes++; } } return numberOfOnes; }

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 9: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 644. Write some code uses loops to print a multiplication table.

ASCII Maps characters to their numerical representation. Don’t memorize the table. Remember this though: • 'A' is 65 • 'a' is 97 • 'A' comes before 'a' • 'Z' and 'a' and are not next to each other • '0' is not 0 45. Suppose you want to determine whether the user typed in a letter or not. What condition

goes inside of the if statement?

0 1 2 3 4 5 6 7 8 ------------------------------------ 0 | 0 0 0 0 0 0 0 0 0 1 | 0 1 2 3 4 5 6 7 8 2 | 0 2 4 6 8 10 12 14 16 3 | 0 3 6 9 12 15 18 21 24 4 | 0 4 8 12 16 20 24 28 32 5 | 0 5 10 15 20 25 30 35 40

// header row for (int col = 0; col <= MAX_COLUMN; col++) { cout << "\t" << col; } // line of dashes cout << endl << " --"; for (int col = 0; col <= MAX_COLUMN; col++) { cout << "----"; } cout << endl;

for (int row = 0; row <= MAX_ROW; row++) { // header column cout << row << " |"; // multiplication for (int col = 0; col <= MAX_COLUMN; col++) { cout << "\t" << row * col; } cout << endl; }

char character; cin >> character;

if ((character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z')) { cout << "letter" << endl; } else { cout << "not a letter" << endl; )

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 10: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 646. Implement characterToInt, a function that, given a character, returns the digit

corresponding to that character (as an int). If the character is not a numeric character, characterToInt should return -1. Here’s its declaration:

47. Implement intToCharacter, a function that, given a one-digit integer, returns the character corresponding to that number. If the number is not between 0 and 9, intToCharacter should return '?'. Here’s its declaration:

Strings String is a sequence of characters. Each character has an index. The index of the last character is length of the string – 1.

Let’s say we have a string name that we read from the user.

48. How can you get the length of name?

49. How can we get the first character of name?

int characterToInt(char c);

int characterToInt(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else { return -1; } }

char intToCharacter(int n);

char intToCharacter(int n) { if (n >= 0 && n <= 9) { return '0' + n; } else { return '?'; } }

0K

1a

2t

3h

4e

5r

6i

7n

8e

string name; cin >> name;

int numberOfCharacters = name.length();

char firstCharacter = name[0];

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 11: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 650. Write a complete program (with main and one other function) that asks the user for a

string, and then prints that same string with the first character capitalized (if a letter). The program should behave per the sample output below, where the user’s input is underlined:

See capitalize-0.cpp, capitalize-1.cpp, capitalize-2.cpp and capitalize-3.cpp inWeek 6 source code (http://maximal.io/eecs183).

51. Write a complete program that asks the user for a uniqname, and then prints if it is valid (between 3 and 8 alphabetical characters) or invalid. The program should behave per the sample output below, where the user’s input is underlined:

See uniqname.cpp in Week 6 source code (http://maximal.io/eecs183). 52. Write a program that prompts the user for a message, and then outputs the message with

its first letter capitalized, with all letters in alternating case. The program should behave per the sample output below, where the user’s input is underlined:

See mySpace.cpp in Week 6 source code (http://maximal.io/eecs183).

Debugging 53. What’s a breakpoint?

A breakpoint is an intentional stopping of execution of a program. Setting a breakpoint on line n will pause the execution of the program right before line n executes.

54. What’s the difference between step into and step over commands?Unless the line on which the execution has paused has a function call, step into and step over commands will behave in the same way—they will cause the line to be executed and the execution will pause before the next line.However, if the line contains a function call, step into command will step into the function call and the execution will pause on the first line of the function. Step over command will step over the function call and the execution will pause before the next line.

55. (T/F) Debuggers allow you to change the value of a variable while the execution of code is paused at a breakpoint.True.

Please give me a string: hello Hello

Uniqname: maximal Valid

Uniqname: eecs183 Invalid

Give me a string: Thanks for the add! ThAnKs FoR tHe AdD!

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 12: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 6Pass-by-Value and Pass-by-Reference 56. What is pass-by-value?

When a parameter is passed by value, the value of the argument is copied into the parameter of the function. Changes made in the function do not affect the original variable that is used as the argument. The only way for the function to pass the information back to where it was called is to return a value.

57. What is pass-by-reference?When a parameter is passed by reference, the value of the argument is copied into the parameter of the function. No copy is made, so time and memory is saved. Changes made in the function do affect the original variable that is used as the argument.

58. Why would someone use pass-by-value over pass-by-reference? Pass-by-reference over pass-by-value?Pass-by-value is often used to make sure that original variables are not modified. Pass-by-reference is used to “return” more than one value (i.e., pass more than one piece of information back to where the function was called from). In addition, pass-by-reference is more efficient when large objects are passed as arguments (such as strings, more on this later).

59. What prints?

1 prints.

60. What prints?

3 20 prints.

void increment(int x);

int main() { int x = 1; increment(x); cout << "x is " << x << endl; }

void increment(int x) { x += 1; }

void foo(int& x, int y);

int main() { int a = 3; int b = 4; foo(b, a); cout << a << " " << b << endl; }

void foo(int& x, int y) { y += 2; x *= y; }

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 13: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 661. Fix the swap function.

62. For each main function, pretend to be a C++ compiler and figure out what prints. Draw a memory diagram for each function to keep track of variables.

63. Consider the following C++ function:

What does the following code print?

12 prints.

void swap(int a, int b) { int temp = a; a = b; b = temp; }

Common functions main function Memory diagrams Outputint foo(int x) { cout << x--; return x; }

int bar(int y) { cout << y; return y + 2; }

int baz(int &z) { z++; cout << z; return z; z += 2; }

int main() { int a = 2; cout << a; foo(a); cout << a; }

int main() { int b = 3; cout << b; b = bar(b); cout << b; }

int main() { int c = 4; cout << c; c = baz(c); cout << c; }

int main() { int d = 2; int e = 3; d = baz(d + e); cout << d; }

int main() { int f = bar(foo(2)); cout << f; }

int main() { int g = foo(baz(4)); cout << g; }

int triple(int& x) { x = x * 3; return x; }

int y = 1; cout << triple(y) + triple(y);

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183

Page 14: EECS 183, Week 6 - Maxim Aleksa · EECS 183, Week 6 Lab 4: Loops getStudentPoints is a function that asks the user to enter the grades (by printing "Grades: "), reads students’

EECS 183, Week 6Arrays 64. (T/F) Arrays in C++ cannot store data of multiple types.

True. 65. How can you declare and initialize the following arrays?

(a) 4 8 15 16 23 42 (b) 0 0 0 0 0 0 (c) 183 203 280 0 0 0

66. What is the best way to know the size of the array? Use a variable of type int to keep track of the array’s size.

67. (T/F) Arrays in C++ can change size.False.

68. What is the best way to print the contents of an array?Use a loop!for (int i = 0; i < SIZE; i++) { cout << arr[i] << endl;}

69. What is the best way to compare the contents of two arrays?Use a loop!bool same = true;for (int i = 0; i < SIZE; i++) { if (arrayA[i] != array[i]) { same = false; }}

70. What happens when an array is accessed beyond its legal bounds? C++ does not do boundary checking when arrays are accessed and anything outside of array’s bounds causes undefined behavior. If the index is near the array, then most likely another part of the program’s memory (e.g., another variable) is accessed. If the index is largely out of the range of the array, the operating system will kill the program causing a runtime error.

71. What prints?

1 2 4 5 1 prints. 72. After the execution of the following code, what is in arr[3]?

arr[3] contains the value 5.

int a[] = { 1, 2, 1, 2, 1 };

for (int i = 1; i < 4; i++) { a[i] = a[i - 1] + a[i + 1]; }

for (int i = 0; i < 5; i++) { cout << a[i] << " "; }

int arr[5]; for (int i = 0; i < 4; i++) { arr[i] = i + 2; if (i >= 2) { arr[i + 1] = arr[i] + 3; } }

Maxim Aleksa ([email protected]) 2 < �14 http://maximal.io/eecs183


Recommended