Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 Variables You have to instruct your computer every little thing it needs to do even what it needs to remember. We create data storages for the computer and explicitly tells it what to store in which storage. We call these storages variables. /* */ A simple program demonstrating the usage of variables. int x; // create an integer variable x int y; // create an integer variable y x = 5; // store 5 in x y = 6; // store 6 in y cout << "x = " << x << ", y = " << y << endl; // print them out Output: (Note: We use /*... */ and // for making notes in the code for ourselves. Text within /* and */ (which can span over multiple lines), and everything after // and before the end of the line are not considered to be part of the code. We call such text a comment and say that part of the code is commented out. It is an important practice to get your codes properly commented.) int x; This is how you declare a variable. int indicates this variable must store an integer (called data type), and labels it x (called identifier). You can think of it as the process of creating an integer box for later use. See the textbook for other data types. Among these data types, we mainly use the following types in this course: int : integer, 4 bytes long, ranging from -2,147,483,647 to 2,147,483,647 double : real numbers, 8 bytes long, ranging from 1.7 10 308 to 1.7 10 308 bool : boolean, 1 byte long, either true or false (IGNORE FOR NOW) char : character, 1 byte long, holds an ASCII character (IGNORE FOR NOW) string : string, let s talk about this later today Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 1/8
Identifiers There are variable naming rules. An identifier must begin with an alphabetic character (a-z or A-Z) or an underscore ( _ ), which may be followed by alphabetic/numeric (0-9) characters and underscores. Violating any of these rules will result in a compile error. Question: Can you tell which ones of these are valid identifiers? los angeles computer_science engineering bruin@ucla.edu C++ 5272BH cs31 A commonly used convention is that you use lowercase letters except for the first letter of the second word (e.g. moneypaid, milesperhour). Later you ll see some special variables called constants (actually, constants are constants because they are not variables, but we will explain this later), which we name using uppercase letters (e.g. GRAVITY). Be descriptive with the varible names -- countapple is better than ca. Question: (case sensitivity) Do engineering and Engineering refer to the same variable? Variable Declaration You ve seen examples already. Here are more examples of variable declarations: int x; // integer x double milesperhour; // double milesperhour int countapple, countorange; // multiple declarations (same type) at once You can use these variables only after you declare them. Otherwise, the compiler will throw an unknown variable error. Also note that these variables initially store some random values (that is, you cannot assume x is initialized to 0). Assignments You created some variables. Now it s time to store data in there. We saw in page 1: x = 5; y = 6; = is called the assignment operator. Note that an assignment is different from equal to. Important! Evaluation order for the assignment: 1. Evaluate the expression on the right-hand side of the assignment operator. 2. Store the value into the variable on the left-hand side of the assignment operator. The original value gets overwritten. You may assign initial values as you declare the variable: int x = 5; // create an integer variable x, assign 5 int y = 6; // create an integer variable y, assign 6 You are allowed to do the following as well: int x = 5, y = 6; // multiple declarations/assignments at once The value you put into a variable must be compatible. For example, x = "Hello" won t work because "Hello" cannot be converted into an integer. However, x = 5.23 is a valid statement, as a decimal number on the right can be made into an integer simply by cutting off the fractional part. Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 2/8
Now something fun: let s make the user decide what to store in the variables. int x, y; cout << "Enter x: "; cin >> x; // get a number for x cout << "Enter y: "; cin >> y; // get a number for y cout << "x = " << x << ", y = " << y << endl; // print them out Output: Enter x: 7 Enter y: 2 Try diffrent inputs. In particular, try inputs other than integers and see how they change the outcome. Expressions Just inputting and outputting stuff is not fun or useful. Now let s play with the data. double initpos, finalpos; // initial and final position double time; // time traveled double distance, velocity; // distance traveled and velocity - to be computed cout << "What is the ball s initial position (at t=0)? "; cin >> initpos; cout << "What is the ball s final position? "; cin >> finalpos; cout << "For how long did the ball travel (in sec)? "; cin >> time; distance = finalpos - initpos; velocity = (finalpos - initpos) / time; cout << "The ball traveled the distance of " << distance << "m at " << velocity << "m/s on average." << endl; Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 3/8
We are particularly interested in the following lines: distance = finalpos - initpos; velocity = (finalpos - initpos) / time; The arithmetic operations on the right hand side of = s are called expressions. It can take the form of an arithmetic expression like this, or can be more complex C++ operations. In any case, the expression is expected to return us the data that we can store into the variable on the left hand side of =. Here are some of the possible operators we can use: + - * / ( ) ++ -- If you try inputting 2 for initpos, 5 for finalpos, and 7 for time, you will see the following output: The ball traveled the distance of 3m at 0.428571m/s on average. Well, that may be too many decimal points for us to handle. We can restrict the number of decimal points to show using the following magic code: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); // vary this number as you need to Try including this into the code before outputting anything and see what happens. Don t try to understand or remember these 3 lines of code (but I know some of you nerds will do regardless). Just copy-and-paste it whenever you need it. Strings We left out the explanation for the type string, so let s talk about it now. We have already seen the use of double quotes in Hello! program last week. A string is an ordered sequence of 0 or more characters. #include <string> // this enables us to use cin and cout // this enables us to use strings string str = "Hello!"; // create a string str with // "Hello, World!" as the initial value string answer; // create a string variable called answer cout << str << endl; cout << "Please answer my greeting!" << endl; getline(cin, answer); // get a user input for answer cout << "You said, " << answer << endl; Output: Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 4/8
Note the two bold-faced lines #include <string> and getline(cin, str). #include <string> allows you to use string data type. You can store values in string variables using the usual assignment, with the value in double quotes. However, when getting input from the user, use getline (cin, str) instead of cin >> str. The former lets let the user to type in a string, and stores the whole line he typed in into str. Can you guess when cin >> str fails to work as intended? If Statements There are times when you want your program to behave differently based on some condition. if-statement is what we use to achieve this. It takes the following form: if ( condition ) then_body else // else part is optional else_body When your computer reaches this part of the program, then_body is executed if condition evaluates to true. Otherwise, else_body is executed. Take a look at the following example: int x, y; cout << "Input x and y: "; cin >> x >> y; if (x > y) // is x greater than y? cout << "x is greater" << endl; // yes else cout << "y is greater" << endl; // no This program receives two values, x and y, from the user. Then it compares the two values to see if x is greater than y, and prints different statements on screen based on the comparison. A quick question: Do you see any logic error in the above code? Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 5/8
Boolean Expressions A boolean expression is an expression that evaluates to either true or false (e.g. x > y). What are other things you can do with conditionals? See the table below for some binary operators you can use. symbol meaning > greater than >= greater than or equal to < less than <= less than or equal to == equal to!= not equal to && AND OR Note that equal to symbol consists of two = s not just one. (Ask yourself now: how are = and == different?) As in arithmetic expressions you saw last week, you can use parentheses in boolean expressions. and and or operations apply to boolean expressions only. Let s do some exercises. Assume x, y, z are all integers. Try reading the following expressions in English. x >= y x == y (x - y) > 10 x > y && y < z ((x!= y) (x > 3)) && (y == z) Don t really try the last one, but you should know what it means. Question: The following expressions are all invalid. Do you see why? x = y x!= y x x < 10 && > 5 5 < x < 10 Question: Now suppose x == 5, y == 6, z == 7. Can you evaluate the following expressions? x >= y x == y (x - y) > 10 x < y && y < z ((x!= y) (x > y)) && (y == z) (x!= y) ((x > y) && (y == z)) Question: Now let s write a couple of expressions! appleprice is less than 50 appleprice times numapples is greater than 10 or numpeaches is greater than 5 Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 6/8
Back to If Statements Now, can you predict the output of the following program? double gasprice = 1.00; // $1 per gallon (we all hope) double tank = 10; // how many gallons to fill the whole tank? double remaining = 1; // 1 gallons left in our tank... double inpocket = 35; // 35 dollars in my pocket... if (gasprice * (tank - remaining) <= inpocket) cout << "Enough money, let's fill it up." << endl; else cout << remaining << " gallons of gas might be enough to get me home." << endl; // Wait, but I m too hungry -- let s get some food inpocket = inpocket - 10; if (gasprice * (tank - remaining) <= inpocket) cout << "Enough money, let's fill it up." << endl; remaining = tank; inpocket = inpocket - (gasprice * (tank - remaining)); else cout << "Not enough money to fill the whole tank, but enough for " << gasprice * inpocket << " gallons." << endl; remaining = remaining + inpocket / gasprice; inpocket = 0; cout << "I have " << remaining << " gallons in the tank." << endl; Output: Try this in Visual C++. Was your prediction correct? Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 7/8
Additional Notes on Number Types int and double are both types that represent numbers, and thus are compatible. The following lines are valid: double x = 5; int y = 7.0; When you assign a non-integer into an integer, it takes the floor of the number (i.e. decimal points are dropped -- the number is NOT rounded): int z = 10.999; // z becomes 10 If an arithmetic expression consists only of integers, it evaluates to an integer. And this holds even for divisions. int q = 5 / 2; // q becomes 2 Note that 5 / 2 is an integer 2 not because you are assigning it into an integer q, but because it is a division that involves only integers. This means, quite confusingly to many at first: double q2 = 5 / 2; // q2 becomes 2.0! Damn! How do I make it such that q2 correctly gets 2.5? Simply make sure your expression contains an non-integer! That is: double q2 = 5.0 / 2; // q2 will be 2.5 You can t apply this.0 trick to integer variables. If your expression involves an integer variable, then you should do: int d = 5; double q3 = (double) d / 2; or equivalently double q3 = static_cast<double>(d) / 2; This is a technique called casting, but you probably won t use it much in this class, so the above use is the only thing you need to know about casting. Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 8/8