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.

Slides:



Advertisements
Similar presentations
Chapter 3: Expressions and Interactivity. Outline cin object Mathematical expressions Type Conversion and Some coding styles.
Advertisements

CS1 Lesson 3 Expressions and Interactivity CS1 -- John Cole1.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Copyright © 2012 Pearson Education, Inc. Chapter 3: Expressions and Interactivity.
1 Engineering Problem Solving with C++ An Object Based Approach Chapter 2 Simple C++ Programs.
Chapter 3 Assignment and Interactive Input
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 3: Expressions and Interactivity.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
Basic Elements of C++ Chapter 2.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
Operaciones y Variables
Chapter 3 COMPLETING THE BASICS Programming Fundamentals with C++1.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
計算機程式語言 Lecture 03-1 國立臺灣大學生物機電系 3 3 Assignment, Formatting, and Interactive Input.
CSE1222: Lecture 3The Ohio State University1. Assignment Operations  The C++ assignment operator is: =  Examples: x = 3 * 5; y = x – 7; y = y + 4; Do.
Basic Elements of C++ Chapter 1.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
C++ Programming: Basic Elements of C++.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
A FIRST BOOK OF C++ CHAPTER 3 ASSIGNMENT AND INTERACTIVE INPUT.
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
C++ Programming, Namiq Sultan1 Chapter 3 Expressions and Interactivity Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin.
Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 3 Expressions and Interactivity.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
Expressions and Interactivity. 3.1 The cin Object.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
Programming Fundamentals with C++1 Chapter 3 COMPLETING THE BASICS.
Recap……Last Time [Variables, Data Types and Constants]
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
2/4/2016Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
Chapter 3 – Variables and Arithmetic Operations. First Program – volume of a box /************************************************************/ /* Program.
Last Time…. Operators Arithmetic Operators Assignment Operators Increment/Decrement Operators Relational Operators Logical Operators Expression Statements.
Expressions Version Topics Arithmetic expressions Conversions Operator precedence String class 2.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Chapter 4: Introduction To C++ (Part 3). The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Information.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
Bill Tucker Austin Community College COSC 1315
Chapter 9: Value-Returning Functions
Arithmetic Expressions
Chapter Topics The Basics of a C++ Program Data Types
Computing and Statistical Data Analysis Lecture 2
Chapter 3 Assignment and Interactive Input.
Programming Fundamentals
Basic Elements of C++.
Chapter 2 Assignment and Interactive Input
Basic Elements of C++ Chapter 2.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
Chapter 7 Additional Control Structures
A First Book of ANSI C Fourth Edition
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
elementary programming
Elementary Programming (C++)
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
C++ for Engineers and Scientists Second Edition
Assignment Operators Topics Increment and Decrement Operators
Presentation transcript:

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 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.

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.

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 ( ) * 5 principal * interest_rate // What is value of the expression? * 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

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 " << ( * radius * radius ); …

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).

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 = * radius * radius; double tax, cost, tax_rate; cost = 50; tax_rate =.07; tax = cost * tax_rate; …

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)

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;

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.

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.

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 += -= *= /= %=

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

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- -.

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; }

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 count; … return 0; }

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.

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

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.

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.

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; }

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 ( * 3.7); u = sqrt ( x * y – z / 3.0 );

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; }

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.

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.

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; }

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; }

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?

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; }

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 = ; // pi is declared and initialized Note that the variable name is arbitrary. We choose pi for obvious reason.