Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5; x += 5; The above expressions add 5 to x and store the increased amount back into x. Similarly, you can do: y = y - 10; or y -= 10; z = z * (x + 2); or z *= x + 2; The following is erroneous. Do you see why? x = 10; y /= x - 10; There is yet another shortcut for incrementing/decrementing a value. The following are equivalent:! x = x + 1;!! x += 1;!! x++;!! ++x; // increment by 1! y = y - 1;!! y -= 1;!! y--;!! --y; // decrement by 1 The incremental operator ++ is the reason behind the naming of language C++, as C++ started as the extention of the language C. (Can you guess the name of the predecessor of C?) (Maybe a little tricky) ++ and -- behave slightly differently based on their location. See the following: x = 5;! y = x++;! cout << y << endl;!!! // It prints: This is an assignment, so the first step is to evaluate the right hand side expression and the next step is to assign the evaluated value to the variable on the left hand side. The expression x++ evaluates to the original value of x. On the contrary, when the variable comes after ++, it evaluates to the resulting value. x = 5;! y = ++x;! cout << y << endl;!!! // It prints: Use this kind of increment-assignment combination only if you fully understand what is going on. It is wise to break it into two statements when it is not obvious what you are doing. The Type bool Remember, boolean expressions are expressions that evaluate to either true or false. Just like integers can be stored in int variables and real numbers can be stored in double variables, true and false values can be stored in bool variables. For instance, the following are equivalent: if (x > 5) cout << "x is greater than 5" << endl; and Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 1/10
bool test = x > 5; if (test) cout << "x is greater than 5" << endl; bool s can be handy when you have to evaluate the same condition multiple times. They let you evaluate the expression once and for all, as in: bool test = x > 5;!! // test is true if x is greater than 5 at this moment. if (test && x < 10)! // true if x is greater than 5 and less than 10. // do something if (test x < 0)! // true if x is greater than 5 or less than 0. // do something else Nested If Statements Recall that an if statement takes the following form ( else part omitted): if (condition) // if body This is a single if statement, and both if and else bodies may consist of multiple statements. The following if statement has two statements in the if body. if (x > 5) cin >> x; cout << "x was greater than 5, so we assigned a new value for x: " << x << endl; This means that in an if body (and in an else body), we can have another if statement as well. if (x > 5) cout << "x is greater than 5"; if (x > 10) cout << "... and it is even greater than 10." << endl; else cout << "... but it is less than or equal to 10." << endl; And you can nest your if statements as many times as you want (as long as it doesn t get messy). Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 2/10
Practices Problem 1 Get name and test score of a student, and print a letter grade. The score must be between 0 and 100 (inclusive). If the score is out of range, print error. Assume the class is not curved -- give A for 90-100, B for 80-89, C for 70-79, D for 60-69, and F for below 60. The score cannot have any decimal points. Assume the user always enters some number (as opposed to characters) for score. For example: Name: Brian Score: 92 Brian receives a/an A. Your code: Name: Mr. Lazy Score: 25 Mr. Lazy receives a/an F. Name: Sean Score: -1 error Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 3/10
Problem 2 Get the birthday of a person and today s date, and determine how many days are left before the birthday. If the birthday has passed, say so. For simplicity, assume there are only 30 days in a month, and that the user never provides illogical input. Examples: Birthday (month): 5 Birthday (day): 25 Today (month): 3 Today (day): 2 83 days left Birthday (month): 11 Birthday (day): 4 Today (month): 9 Today (day): 20 44 days left Birthday (month): 3 Birthday (day): 2 Today (month): 5 Today (day): 24 Your birthday has passed I ve written a portion of the code for you below: int birthmonth, birthday; int currentmonth, currentday; int daysleft; // Get the dates. cout << Birthday (month): ; cin >> birthmonth; cout << Birthday (day): ; cin >> birthday; cout << Today (month): ; cin >> currentmonth; cout << Today (day): ; cin >> currentday; // Your code below. return 0; Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 4/10
Loops While Loops Here is the syntax for a while loop: while (condition) body; body is repeatedly run while condition holds. Take a look at the following example: #include <iostream> Output: using namespace std; int x = 0, y = 10; while (x < y) x++; // equivalent to x = x + 1 cout << x << endl; cout << endl; return 0; Be careful when you are using while statements, though. what is wrong with the following code? x = 1; y = 0; while (y == 0) x++; Infinite loops will cause your program to crash so you should always make sure that it ends at some point! There is a variation of while statement called do-while. It works just like while, but will execute the loop once no matter what, and then test the condition. This is most useful in a case like the following, where you ask for a valid input from the user: int x = 0; do cout << "Input 5 or 6: "; cin >> x; while (x!= 5 && x!= 6); // Don t forget that semicolon For Loops Often, in your looping structure you will need some kind of counter to keep track of the number of times the loop is executed. (e.g., printing Hello 100 times, adding numbers 1 to 50) While this can be done with a while loop, for your convenience, C++ defines another looping structure that supports it: for ( initialization ; condition ; update ) body which we call for loops. An example should help this make better sense: Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 5/10
#include <iostream> using namespace std; int i, sum = 0; for (i = 1; i <= 100; i++) sum = sum + i; cout << "sum = " << sum << endl; return 0; What does the above program do? The evaluation rule is as follows. Recall that the syntax for a for loop is: for ( initialization ; condition ; update ) body 1. Execute initialization 2. Check the condition If true, 3. run the body 4. do the update go back to 2 If false, exit the for loop. The order of execution is therefore 1-2-3-4-2-3-4-2-3-4-...-2-3-4-2. For to While conversion If you can do something using a while loop, you should be able to write a for loop equivalent, and vice versa. The for-to-while conversion rule is quite straightforward, and is illustrated on the right side. initialization should come before everything, and it must be executed only once. Therefore, it comes before the whole while loop. Then the condition must be checked, thus condition goes inside the while statement. If this is true, we execute the body, and then update. Note that update statement must be inside the while loop. (What happens if it s outside the loop?) This conversion is somewhat straightforward from the evaluation steps of for loops we saw above. For to do-while conversion works in a similar way. Homework 2 should have bugged you enough for this. for (initialization; condition; update) body initialization while (condition) body update Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 6/10
Question: Can you tell how the following for statements will behave? What values does i take on? for (int i = 10; i >= 0; i--) for (int i = 0; i < 100; i += 2) for (int i = 32; i > 1; i /= 2) Question: Write a for loop that finds the sum of numbers 1 to 100. Question: (Nested Loops) How many times does # get printed? for (int i = 0; i < 10; i++) for (int j = i; j < 10; j++) cout << # ; cout << # ; Question: Convert the following for loop into a while loop. for (int i = 0; i < 50; i += 2) cout << Hello << endl; Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 7/10
Functions Suppose I want to write a program that computes 3 things: - the sum of integers 1 to 100 - the sum of integers 51 to 150 - the sum of integers 103 to 276 You can create a loop for each one of the sums, but this is cumbersome. If we are allowed to define a method of summing up numbers just once, and then use it three times, it will reduce some burden. In other words, you can teach your computer how to sum, as opposed to what to sum. In C++, functions (or equivalently known as methods, subroutines, or procedures in other contexts) are meant to serve this purpose. An example of a C++ function is shown here ----> Hey, that resembles the main() thing that we used to write. In fact, main() is also a function, which we call main function, and it happens to be the one that gets executed when the program begins. Before we take it apart, let me bring up an analogy: int sum(int begin, int end) int temp = 0; for (int i = begin; i <= end; i++) temp += i; return temp; This is called a function for a reason. Where else do you see functions? In high school algebra, we ve seen functions presented in the following way: f(x) = 2x + 5 This function, called f, takes a value, denoted x, and maps this number in a predetermined way to another number. If the input x is 5, for instance, we do: f(5) = 2(5) + 5 = 15 and it would result in a different number for a different output. Once we have defined this function f, we can simplify other expressions using f. 4x + 10 = 2f(x) 2x 2 + 7x + 5 = (x+1)(2x+5) = (x+1)f(x) This is exactly what we do with our C++ functions. We define it, and then use it to simplify our program. Now let s take the function definition apart. - int indicates that the output is of type integer. We call this return type. - sum is the name, or the identifier, of the function, just like f is for the function above. - begin and end are arguments to the function sum, just like x is for the function f. The arguments must be within parentheses. - The function body within defines the mapping rule. - The function must return the value explicitly, depending on the input it receives. Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 8/10
In general, the syntax goes as follows: return_type function_name(arg1, arg2, arg3,...) function_body and the function body must include return statements such that every execution of the function ends up in a return statement. A function can also have no arguments, in which case the argument list simply becomes empty (i.e., ()). So where in the program should this function go and how do we use it? Here is an example. #include <iostream> using namespace std; int sum(int begin, int end) int temp = 0; for (int i = begin; i <= end; i++) temp += i; return temp; cout << sum(1, 20) << endl; // prints the sum 1 +... + 20 cout << sum(20, 50) << endl; // prints the sum 20 +... + 50 int sum1, sum2; sum1 = sum(4, 8); // stores the sum 4+5+6+7+8 into sum1 sum2 = sum(1, 10) + sum(15, 20); // stores the sum 1+...+10+15+...+20 into sum2 cout << sum1 << << sum2 << endl; return 0; Note that the function must be defined before it can be used. If the definition of sum comes after the main function, the compiler will complain that sum is an undefined identifier. If for a style reason you want to keep the main function on the top and define other functions later, you can let the computer know that there s going to be a function with a certain name first, and define later. For instance, you can do what s on the right. The bolded line is called a function prototype. #include <iostream> // I will define "sum" later. int sum(int begin, int end);... // Define it here. int sum(int begin, int end)... Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 9/10
Now it s time for a little practice: Question: Define a function f that takes in a real number x and returns the result of 2x + 5. Question: Use the function f and sum to find the sum from f(3) to f(72), and store it in a variable called z. Question: How many # s will you see on the screen? int mystery(int len) for (int i = 0; i < len; i++) cout << # ; if (len % 2 == 0) return len + 1; else return len + 3; int y = 5; while (y < 10) y = mystery(y); return 0; Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 10/10