Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Assignment and Interactive Input. Variable Named memory location in which a value can be stored. The stored value may be changed through the.

Similar presentations


Presentation on theme: "Chapter 3 Assignment and Interactive Input. Variable Named memory location in which a value can be stored. The stored value may be changed through the."— Presentation transcript:

1 Chapter 3 Assignment and Interactive Input

2 Variable Named memory location in which a value can be stored. The stored value may be changed through the use of assignment and other statements or instructions. (Is it one of the reasons that the named location is called variable?) The location can be conveniently visualized as a box. The size of the box depends on the type of value (data type) such as char (1 byte), int (2 bytes), and double (8 bytes). The physical address of the variable is the address of the first byte of the box.

3 Arithmetic expression A proper combination of numeric constants, arithmetic operators, variables (which store constants), and built-in or library functions. No matter how complex an arithmetic expression may be, it is evaluated to a constant. As a direct consequence, the simplest arithmetic expression is a single constant.

4 Examples of arithmetic expressions In the following examples, we assume that are variables have been declared and initialized (or defined, meaning a value has already been stored in the varible ). 25 // The simplest arithmetic expression 50.0 * 0.07 ( 2 + 3 ) * 5 principal * interest_rate // What is value of the expression? 3.14159 * radius * radius // area of a circle width * height * length // volume of rectangular block (- b - sqrt ( b * b – 4.0 * a * c)) / ( 2.0 * a ) // root of a quadratic equation

5 How Is an Expression Used Used in conjunction with cout object (an ostream object) and << (the insertion operator): cout << "2 + 3 = " << ( 2 + 3); cout << "There are " << 5 << "students."; cout << "The area of the circle is " << (3.14159 * radius * radius ); …

6 How Is an arithmetic expression used continued Although arithmetic expressions can be used with cout <<, they are most commonly used with an assignment statement with the general format: variable = arithmetic expression;// semicolon! where the = is not an equal to operator (which is = =), instead it is an assignment operator (binary, left-to-right association, and has a priority lower than all arithmetic operators that may appear in the arithmetic expression. The statement will be executes as follows: the arithmetic expression will be evaluated to a single value, the value will then be assigned (or stored in the variable).

7 Examples of assignment statement double length, width, height, volume; length = 25; width = 17.5; height = 3.45; volume = length * width * height; double radius, area; area = 3.14159 * radius * radius; double tax, cost, tax_rate; cost = 50; tax_rate =.07; tax = cost * tax_rate; …

8 Some observations = is not equal to operator, e.g., int m = 5; // m is initialized to 5 m = m + 1; // obviously, m cannot be equal to m + 1 An un-signed variable is the only legal entity that can appear to the left of =, e.g., - m = 12; // illegal! 12 = m; // illegal! Lvalue violation! (see sidebar on p94)

9 Multiple assignment statements Multiple assignment statments int a, b, c; a = 25; b = a; a = b; The above three assignment statements is equivalent to a single multiple assignments a = b = c = 25;

10 Counter: a variable of integer type used for the purpose of counting: illustrated with an example #include int main( ) { int s1, s2, s3, count = 0; // variable counter stores the total number of scores that have been defined. s1 = 75; count = count + 1; // value in counter is 1 s2 = 88; count = count + 1; // value in counter is 2 s3 = 97; count = count + 1; // value in counter is 3 … return 0; } Note that a counter must be initialized, usually to 0.

11 Accumulator: a numeric variable of either integer or floating-point type that is used for the purpose of accumulating or totaling a set of values, one-by-one #include int main( ) { int s1, s2, s3, count = 0, total = 0; // variable counter stores the total number of scores that have been defined. s1 = 75; count = count + 1; total = total + s1;// total stores the running sum, 75 now s2 = 88; count = count + 1; total = total + s2; // total is now 163 s3 = 97; total = total + s3; // total is now 260 count = count + 1; … return 0; } Note that an accumulator must be initialized, usually to 0.

12 Shorthand notations for assignment and arithmetic operators count = cout + 1; // standard notation count += 1; // shorthand notation total = total + score; // standard notation total += score; // shorthand notation Summary += -= *= /= %=

13 Increment and decrement operators If the value is to be increased or decreased by 1 for an integer variable, one can use the following: ++ count;// pre-increment operator count++;// post-increment operator -- count;// pre-decrement operator count--;// post-decrement operator

14 What is the difference between pre- and post-? … int m = 5, n1 = 6, n2 = 6; n1 += ++m; // what are m and n1 after the execution of the instruction? n2 += m++; // what are m and n2 after the execution of the instruction? … Similarly for - - m and m- -.

15 Rewrite previous two programs #include int main( ) { int s1, s2, s3, count = 0; // variable counter stores the total number of scores that have been defined. s1 = 75; ++count; // or count++; or count += 1; value in counter is 1 s2 = 88; ++count; // value in count is 2 s3 = 97; ++count; // value in count is 3 … return 0; }

16 Rewrite previous two programs #include int main( ) { int s1, s2, s3, count = 0, total = 0; // variable counter stores the total number of scores that have been defined. s1 = 75; ++count; total += s1;// total stores the running sum, 75 now s2 = 88; ++count; total += s2; // total is now 163 s3 = 97; total += s3; // total is now 260 ++count; … return 0; }

17 Another definition for a program We've defined tokens of C/C++ and said that tokens are the building blocks of a C/C++ program (fine-grain). On a larger scale (coarse-grain), a program consists of one or more functions (of course, each function is composed of tokens). A function is simply a block of code that usually performs a well defined task. Every program must have one function whose name is main where execution of the program begins. Often, functions are coded by a programmer for a particular tack. But for some common tasks, C/C++ provides many categories of the so called built-in or library functions that are pre-programmed can be used (called into action) by a programmer.

18 Built-in or library functions Each built-in function has a unique name and belongs in a particular category. A built-in function is identified by a header file (usually has a.h extension, the.h extension is dropped in the newest ANSI C++ standard) that must be included through the use of a #include preprocessing directive. The signature of a function: name of the function, and the number and types of augments identifies a function. As an example: sqrt (x) is a library function belonging in the math category and is defined in the math.h header file; sqrt is the name of the function and x is any argument that must be passed to the function when the function is called or invoked. Most functions return a single value (result). In the case of sqrt(x), the square root of x is returned to the the caller (or calling line), as illustrated in the following example

19 Example: how sqrt(x) is called and the resulting value returned #include int main() { double y = 4.0, result; result = sqrt( y ); // calling line; y is the argument; square root is returned and assigned // or stored in variable result. Note that sqrt is a block code defined by // the system cout << "square root of " << y << "= " << result; return 0; } Note that a function can be called as many times as needed. Yet it needs to be defined only once. There is however an overhead on its execution; branching out to the function and returning back from the function.

20 Mechanisms of Passing value(s) to a called function: call-by-value There are several ways to pass a value or a set of values to a function. In the previous example, the mechanism is known as call- by-value. Later, we'll learn a different mechanism known as call-by-reference. As implied by its name, call-by-value allows a value or a set of value to be passed directly to a function, as illustrated in the next example.

21 Call-by-value #include int main() { double result; result = sqrt( 4.0 ); // value 4.0 is directly written in place of y cout << "square root of " << y << "= " << result; return 0; }

22 Other commonly used math functions namedescriptionretuned value abs(x)absolute valuesame data type as argument pow(x1, x2)x1 raised to x2 powerdata type of argument x1 sqrt(x)square root of x, x >= 0same data type as x sin(x)sine of x (x in radians)double cos(x)cosine of x ( x in radians)double tan(x)tangent of x (x in radians)double log(x)natural log of x, x > 0double log10(x)common log of x, x > 0double exp(x)e raised to the x powerdouble Note: in place of each argument, one can enter an arithmetic expression. For example the following function call is valid (assuming all variables are declared and defined) z = sqrt ( 4.0 + 5.3 * 3.7); u = sqrt ( x * y – z / 3.0 );

23 Example: compute the length of hypotenuse of a right-angle triangle #include int main( ) { double a, b, c; // c is the hypotenuse a = 3.0; b = 4.0; c = sqrt ( a * a + b * b ); cout << "Given a = " << a << " and b = " << b << "\nThe hypotenuse c = " << c << endl; return 0; }

24 Data promotion, demotion, and the cast operation: illustrated with examples int m, n; double x = 3.5, y; y = 2 * x; // 2 will be automatically promoted to double before computation m = 45 / x; // What about this one? n = 45 / int ( x ); // x is "casted" to int type; cast has higher priority than / ! m = x; // What is assigned to m? n = int ( x ); // what is assigned to n? Note that there are four different kinds of cast operations as defined in the new C++ standard. The one that accomplishes the above has the following format: static_cast ( variable ); Go to CS240 web folder for more details.

25 Programming input with the cin object cin is an input stream object and is used in conjunction with the extraction operator >> to extract value(s) from input stream originated from the keyboard (standard input device). The extracted value(s) will be stored in variable(s) that appears after the >> operator. Since cin >> extracted values originated from keyboard (not from an existing data file) at execution time, the process is interactive, namely, the user of the program will be prompted to enter data when the program is running or executing, as illustrated in the following example.

26 Example: interactive input with cin >> #include int main( ) { double a, b, c; // c is the hypotenuse cout << "Please enter the \"a\" side of a right angle triangle: "; cin >> a; cout <<"\n Please enter the \"b\" side of a right angle triangle: "; cin >> b; c = sqrt ( a * a + b * b ); cout << "\n\nGiven a = " << a << " and b = " << b << "\nThe hypotenuse c = " << c << endl; return 0; }

27 Cascading the >> operator #include int main( ) { double a, b, c; // c is the hypotenuse cout << "Please enter the a and b sides of a right angle triangle: "; cin >> a >> b; c = sqrt ( a * a + b * b ); cout << "\n\nGiven a = " << a << " and b = " << b << "\nThe hypotenuse c = " << c << endl; return 0; }

28 Another example: two roots of a quadratic equation #include int main( ) { double a, b, c, r1, r2; // coefficients for ax 2 +bx+c = 0 cout << "Please enter three values for the quadratic eq: "; cin >> a >> b >> c; r1 = ( -b + sqrt ( b * b – 4.0 * a * c)) / ( 2.0 * a); r2 = ( -b – sqrt ( b * b – 4.0 * a * c)) / ( 2.0 * a); cout << "\n\nRoot1 = " << r1; cout << "\nRoot2 = " << r2; return 0; } Observations: 1) above program is not efficient, why? 2) The program may have run-time or execution-time error, why?

29 Input character type of data with cin >> #include int main( ) { char c1, c2, c3, c4; cout << "Enter 4 characters: "; cin >> c1 >> c2 >> c3 >> c4; cout << "\n\nThe four characters that you entered are: " << c1 << '\t' << c2 << '\t' << c3 << '\t' << c4 << endl; return 0; }

30 The const qualifier Constants such as  (note that  is not a valid variable name!) can be stored in a variable preceded by a const qualifier. The content or the value of such a variable cannot be changed throughout the program; it is a protective measure to prevent the from being inadvertently or maliciously altered. The value of a const variable must be initialized at the time the variable is declared. For example: const pi = 3.14159; // pi is declared and initialized Note that the variable name is arbitrary. We choose pi for obvious reason.


Download ppt "Chapter 3 Assignment and Interactive Input. Variable Named memory location in which a value can be stored. The stored value may be changed through the."

Similar presentations


Ads by Google