C/C++ Programming for Engineers: Working with Integer Variables John T. Bell Department of Computer Science University of Illinois, Chicago Preview Every good program should begin with a large comment block explaining what the program does, who wrote it and when. How do you indicate a comment in C/C++? A. // B. % C. /*... */ D. & E. Either A or C 2 1
C++ has five basic types of data: Integers Whole numbers with no fractions. Floating Point Numbers that may contain fractions, and have a larger range due to exponents. Characters Small integer codes representing individual letters and other symbols. Strings Collections of zero or more characters. Booleans Variables holding True or False. 3 Integers come in many flavors: int The natural size for the machine. short May use less bits than an int. long May use more bits than an int. long long Twice as many bits as a long unsigned No negatives, but twice the positives. char 8 bits, usually used to hold characters. wchar 16 bits, wide char for more symbols. 4 2
If a byte is 8 bits, how many bits are in an int? A. 8 B. 16 C. 32 D. 64 E. It depends on the computer hardware and the compiler being used. # of bits: short int long < long long 5 All variables must be declared before use, by specifying their type: int i, j, k; int numstudents; int natoms, nelectrons, nprotons; // Number of students // Number of atoms // Number of electrons // Number of protons. Variables may be initialized when declared: int ncarbons = 0, nhydrogens, noxygens = 16; Uninitialized variables should be assumed random. 6 3
Variable name ( Identifier ) rules Identifiers must begin with a letter ( or underscore. ) Additional characters may be letters, numbers, or underscores. Identifiers are case sensitive: ball Ball BALL Characters beyond a certain number ( 32? ) are ignored. Identifiers may not be C++ reserved words. 7 Variable name ( Identifier ) conventions Integers often begin with i to n. Floating point with a to h, m to z. counters with n or num: natoms, numstudents normal variables begin with lower case. Globals begin with upper case. CONSTANTS in all upper case. Multiword variables in camel case: newhouse Alternate using underscores: new_house Use meaningful names from application domain. 8 4
Assigning values to variables The assignment operator, =, takes the value from the right and stores it in the variable on the left: X = 7; // Store 7 in X X = 5 + Y; // Add 5 to Y, store result in X X = X + 9; // Add 9 to original value of X, // Store result back into X. 9 Some expressions from math class are not legal in C++, and vice versa: X = Y + 7; // Legal in C++ and math class X Y = 7; // Legal in math, not in C++ 7 = X Y; // Legal in math, not in C++ X = X + 42; // Legal in C++, contradiction in math class. 10 5
Basic arithmetic using integers + ( plus ) adds two numbers and yields the result. X = Y + 7; - ( minus ) can be used two ways: Unary takes the negative: X = -Y; Binary subtracts and yields difference: X = Y 10; * ( asterisk or star ) multiplies two numbers and yields the product: X = 3 * 5; 11 DANGER DANGER! Integer division truncates fractions! / ( slash ) divides the number on the left by the number on the right: X = Y / 2; 15 / 5 yields 3 5 / 2 yields 2 99 / 100 yields 0 centigrade = 5 / 9 * ( fahrenheit 32 ); // Stores 0 for all values of Fahrenheit // ( 5.0 / 9.0 would yield correct results. ) 12 6
The modulo operator, %, yields the remainder after division 137 % 10 yields 7 5 % 3 yields 2 3 % 5 yields 3 // 3 / 5 is zero, remainder 3 N % 2 yields 0 if N is even, 1 if N is odd N % M yields an integer from 0 to M-1 inclusive, regardless of the value of N o card = rand( ) % 52; // Yields random 0 to 51 13 Precedence and Associativity *, /, and % have equal precedence, all higher than + and binary ( which are also equal to each other. ) All these operators associate left to right, within operators of equal precedence. So all *, /, and % would be evaluated first, from left to right, followed by all + and binary from left to right. ( Unary has higher precedence than *, /, % ) ( ) can be used to override default precedence. 14 7
What is stored as a result of this statement? N = 5 + 3 / 2; A. 4 B. 5 C. 6 D. 6.5 E. 26.5 15 Combination Assignment Operators It is so common to modify a variable and then store the result back into the same variable that a special set of operators exists: Operator Example Equivalent X += Y; X = X + Y; X -= Y; X = X Y; X *= Y; X = X * Y; X /= Y; X = X / Y; X %= Y; X = X % Y; X *= Y + Z; X = X * ( Y + Z ); // NOT X = X * Y + Z; Note that all assignment operators have lower precedence than any math operators. E.g. + before *= 16 8
What is stored as a result of this statement if N is originally 10? N *= 5 + 3 / 2; A. 16.5 B. 40 C. 53.2 D. 60 E. 65 17 Auto-increment (++) and Auto-decrement (--) Operators adjust integers by one: i++;, as a stand-alone statement, is equivalent to i += 1; or i = i + 1; i--;, as a stand-alone statement, is equivalent to i -= 1; or i = i - 1; Auto-increment and auto-decrement are frequently used in loops, which we will get to a little later. ( Zyante covers ++ and -- in the loop chapter. ) 18 9
++ and -- Prefix versus Postfix The auto-increment and auto-decrement operators come in two forms: Prefix puts the operator before the variable, e.g. ++N or --N Postfix puts the operator after the variable, e.g. N++ or N-- As stand-alone statements the two forms are exactly equivalent, and only change the variable. 19 The difference appears when the operator is used as part of a larger expression Postfix uses the original value of the variable: int copy, N = 3; copy = N++; // Stores 3 in copy; Changes N to 4 Prefix uses the new value of the variable: int copy, N = 3; copy = ++N; // Stores 4 in copy; Changes N to 4 20 10
Precedence and Associativity of ++ and -- Postfix N++ and N-- have higher precedence than anything we have seen, and are evaluated left to right. Prefix ++N and --N have the next lower precedence, equal to unary - and!. This group of operators is evaluated right to left. ( Example: M = - ++N; evaluates ++, then -. ) Prefix / Postfix still determines whether to use the original or new values in the expression. 21 What value is used for N in this location? int copy, N = 3; copy = 3 * N++ * 15.0 / N; A. 2 B. 3 C. 4 D. Error E. Undefined 22 11
What value is used for N in this location? int copy, N = 3; copy = 3 * N++ * 15.0 / N; A. 2 B. 3 C. 4 D. Error E. Undefined Danger! Danger! Never use the same variable more than once in the same expression if it is autoincremented or auto-decremented anywhere in the expression! 23 Review In the following statement, which of the following is the correct order in which the operators will be evaluated? A *= B + C / D E++; A. *=, +, /, -, ++ B. /, +, -, *=, ++ C. ++, /, +, -, *= D. ++, +, /, -, *= E. None of the above. The correct order of operations is not listed here. 24 12