0% found this document useful (0 votes)
21 views43 pages

Lecture3 AssignmentAndInteractiveInput

The document covers assignment operators in C++ programming, explaining how they assign values to variables and the importance of initializing variables before use. It also discusses mathematical library functions, interactive keyboard input, and common programming errors related to variable assignment and coercion of data types. Additionally, it emphasizes the need for robust programs that validate user input to prevent crashes or nonsensical output.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views43 pages

Lecture3 AssignmentAndInteractiveInput

The document covers assignment operators in C++ programming, explaining how they assign values to variables and the importance of initializing variables before use. It also discusses mathematical library functions, interactive keyboard input, and common programming errors related to variable assignment and coercion of data types. Additionally, it emphasizes the need for robust programs that validate user input to prevent crashes or nonsensical output.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Assignment and

Interactive Input
CS 52: C++ Programming
 Describe assignment operators
 Functionally look at mathematical library functions
Objectives  Get proactive with interactive keyboard input
 Wrap ourselves around symbolic constraints
 Discover common programming errors
 The assignment operator assigns values of the correct type to
variables
 Basic Assignment Operator
 Format: variable = expression;
 The equals sign in an assignment statement
Assignment  First computes value of expression on right of = sign
Operators  Then assigns the value computed in Step 1 to the variable on left side of
= sign (it stores the value in the variable location)

int length
length = 25;
“length is assigned the value 25”
 If not initialized in a declaration statement, a variable should be
assigned a value before used in any computation
 Think of the flow of control in the main function of the program
 Statements are executed one at a time, the computer has no
knowledge of what the next statement will be when it is executing the
current statement
 It cannot “look ahead” for a variable assignment when using a variable in a
calculation
Assignment  If you attempt to use a variable that was not initialized or assigned a
Operators (2) value in a computation the compiler will attempt to put whatever
value happened to be in that memory slot into your variable
producing unwanted results
 For the same reason you cannot use a variable before it has been
declared

 Variables can only store one value at a time


 Subsequent assignment statements will overwrite previously
assigned values
 Operand to right of = sign can be:
 A constant
 A variable
 A valid C++ expression

 Operand to left of = sign must be a variable


Assignment amount + 1000 = 15-2; //is invalid
 The expression on the right side of the assignment operator
Operators (3) evaluates to 13, which then to complete the operation needs to be
stored in a variable
 Since amount + 1000 is not a valid variable name the computer does
not know where to store the calculated value of 13

 If operand on right side of the = is an expression:


 All variables in expression must have a value to get a valid result
from the assignment
 EXPRESSION: any combination of constants and variables that
can be evaluated to yield a result
 Regular precedence and associativity rules apply when evaluating
the left side of an assignment operation
 Examples of valid assignment expressions with valid expressions on
the right side of the = sign

sum = 3 + 7;
Assignment
diff = 15 –6;
Operators (4) product = .05 * 14.6;
tally = count + 1;
newTotal = 18.3 + total;
average = sum / items;
slope = (y2 – y1) / (x2 – x1);
 CONCEPT: In C++ it is important to realize that the equals sign
used in the assignment statement is an operator (called the
Assignment assignment operator)

Operators (5)  The assignment operator = has a lower precedence than any other
arithmetic operator and this is why the value of the expression to
the right of the equals sign is always evaluated first
 Assignment statements themselves produce a value
#include <iostream>
using namespace std;

int main()
{
int a = 5;
Assignment
cout << "The value of the expression a=5 is " << (a = 5) <<
Operators (6) endl;

return 0;
}
 The output is: The value of the expression is 5
 The significance of this will become more apparent when we look at
relational operators and conditions for if/else statements
 The assignment operator has right to left associativity
Assignment  The statement: a = b = 5;
Operators (7)  First assigns the value of 5 to the variable b and then assigns the value
of b (which is 5) to a
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double length;
Assignment double width;
double area;
Operators length = 27.2;
width = 13.6;
Example area = length * width;
cout << fixed << setprecision(2);
cout << "The length of the rectangle is " << setw(6) << length << endl;
cout << "The width of the rectangle is " << setw(6) << width << endl;
cout << "The area of the rectangle is " << setw(6) << area << endl;
return 0;
}
 Shows an example of what would happen if values are not
assigned to length and width before they are used for a calculation
 Note the pattern I used for this program, this has a basic logic you
Assignment will repeat for a lot of your programs
 Declare variables needed in program: width, length, area and set
Operators initial values
Example (2)  Get user input and assign values to variables (we'll learn this in a
minute)
 Perform calculations on the input
 Display results (output)
 The value on right side of a C++ assignment expression is
converted to data type of variable on the left side
 COERCION: converting data to the type of the variable it is assigned
to (when possible)
Coercion  You need to always know what DATA type your data is…keep track
 Notice this is different from the strict typing rules of Java
 C++ allows the programmer to make data type conversions that may
result in a loss of data
 If temp is an integer variable, the assignment
temp = 25.89;
 causes integer value 25 to be stored in integer variable temp
 The assignment here truncates (doesn't round) the double value 25.89
when it is converted to an int

Coercion  If temp is a double the assignment

Example temp = 25;


 causes float value 25.0 to be stored in the float variable temp
 The .0 added to 25 indicates the conversion from an int to a double
 NOTE: Remember that even though, in this example, 25.0 is
converted to a double, cout formats it as 25 rather than 25.0 when it
outputs to the screen
 To get cout to display the .0 you need to use setprecision
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int x;
double y;
Coercion
x = 25.75;
Example #2 y = 5;
cout << "The value 25.75 was coerced to the integer value " << x <<
endl;
cout << fixed << setprecision(2)
<< "The value 5 was coerced to the double value " << y << endl;
return 0;
}
 Assignment expressions such as:
sum = sum + 25;
Assignment  This expression is evaluated in two steps (remember the two steps
for assignment)
Variations/  The first step is to calculate the value sum + 25
Shortcut  The second step is to store the computed value in the sum variable

 This type of expression can be written by using following shortcut


Operators operators:
+= -= *= /= %=
 Example:
sum = sum + 10;
 can be written as
Assignment sum += 10;
Variations/  It’s important to note that the variable to the left of the
Shortcut assignment operator is applied to the complete expression on the
right
Operators sum *= a + 10;
IS: sum = sum * (a + 10);
NOT: sum = sum * a + 10;
 Standard preprogrammed functions that can be included in a
program
Mathematical  EXAMPLE: sqrt(number) calculates the square root of number
 The number passed into the square root function is called the argument
Library of the function and constitutes the input data of the function
 Once the sqrt function receives the input data it performs
Functions mathematical operations on it and returns the number resulting from
those mathematical operations to the calling function
 Notice that the input to the sqrt function must be a real number
 Notice that the input to the sqrt function must be a real number
 The real number may be of type float, double or long double

Mathematical  This is called function overloading


 Function overloading permits the same function to be defined for
Library different argument types
 In this case, there are three functions defined for sqrt, one that takes a
Functions float argument, one that takes a double argument, and one that takes a
long double argument
 Function overloading will become an important concept to understand
as we progress in learning C++
#include <iostream>
#include <cmath>

using namespace std;


Mathematical int main()
Library {
double x;
Functions
x = sqrt(4.2);
Example
cout << "The output is " << x << '\n';

return 0;
}
 Notice the header #include <cmath> is used in this program
Mathematical  The sqrt function won't work without it because the sqrt function is
defined in the cmath library
Library  What happens if you sent an int to the sqrt function instead of a
Functions real?
 The compiler automatically promotes the integer (int) to a data type
Example (2) the function accepts
 This may differ by compiler
 Before using a C++ mathematical function the programmer must
know
 Name of the desired mathematical function
 What the function does
More on  Type of data required by the function (input)
Mathematical  Data type of the result returned by the function (output)

Library  Remember what functions are and what their point is


 A function is good if it can be reused by many programs like the sqrt
Functions function can

 In a couple of lectures, you will be writing your own functions and


people using your functions will need to know the same
information to use them properly
 To access these functions in a program, the header file cmath must
be used in your program
 Format: #include <cmath> <- no semicolon
Function Name Description Returned Value
Commonly abs(x) Absolute value Same data type as argument
pow(x1, x2) x1 raised to the x2 power Data type argument of x1
Used sqrt(x) Square root of x double
Mathematical sin(x) Sine of x (x in radians) double
Library cos(x) Cosine of x (x in radians) double
tan(x) Tangent of x (x in radians) double
Functions log(x) Natural logarithm of x double
log10(x) Common log (base 10) of x double
exp(x) e raised to the x power double
 CAST: forces conversion of a value to another data type
 Two versions: compile-time and run-time

 COMPILE-TIME CAST: unary operator with syntax


dataType(expression)
 expression converted to data type of dataType
Casts  Old C-style compile time casting may also be used
(dataType)(expression)

 RUN-TIME CAST: requested conversion checked at runtime,


applied if valid
 SYNTAX: staticCast<dataType>(expression)
 expression converted to data type of dataType
#include <iostream>
using namespace std;

int main()
{
double x;
Casts Example x = 4.2;

cout << "When x is cast to an int the value is " << (int)x << '\n';

return 0;
}
 A good program needs to be able to get input from the user
 cin object: used to enter data while a program is executing
Interactive  Example: cin >> num1;
 Statement stops program execution and accepts data from the
Keyboard keyboard
Input  The cin object allows the user to enter a value at the terminal
(keyboard)
 The value the user enters is then directly stored in a variable
#include <iostream>
using namespace std;
int main()
{
double num1;
double num2;
double product;
Interactive //prompt the user for information
cout << "Please input a number: ";
Keyboard cin >> num1;
cout << "Please input another number: ";
cin >> num2;
Input Example
//use input received from the user for the computation of the product
product = num1 * num2;
//output results
cout << num1 << " times " << num2 << " is " << product << endl;
return 0;
}
 First cout statement in Example program prints a string
 Tells the person at the terminal what to type
 A string used in this manner is called a prompt
About the  Next statement, cin, pauses computer (what cin does)
Interactive  Waits for user to type a value
 User signals the end of data entry by pressing Enter key
Keyboard  Entered value stored in variable to right of extraction symbol
Input Example  >> is called an extraction symbol, as it extracts a stream of data from
the keyboard and puts the data into a variable

 Computer comes out of pause and goes to next cout statement


which in this program is another prompt
 In general basic programs will follow this sort of pattern:
 Declare variables
 Prompt user for input
 Get user input
 Perform some sort of computations on user input
Continuing on  Output the results
 The cin statement can also be used to enter and store as many
Interactive values as there are extraction symbols >>
Keyboard  Example: cin >> num1 >> num2;
 This results in two values being read from the terminal and into the
Input variables num1 and num2
 When the numbers are being entered into the keyboard at least one
space must be put between them in order for them to be read into
the two variables
 Inserting more than one space has no effect on cin
 As long as no space is entered the program stays in pause mode
waiting for the second number to be input
 When invalid input is entered into cin the operator can do some
simple conversions but these conversions can cause results that
are not desired
Continuing on  For example, if num1 above was an int and num2 was a double and
Interactive the data input into the keyboard was:
22.83 1
Keyboard  The computer would stop reading after the decimal point in the 22
Input (2) assuming the decimal point indicated the end of the integer
 22 would be stored in num1
 .83 would be stored into num2
 1 would be considered extra input an would be ignored
#include <iostream>
using namespace std;
int main()
{
double num1;
double num2;
Interactive double sum;

Keyboard //prompt the user for information


cout << "Please input two numbers: ";
Input Example cin >> num1 >> num2;

#2 //use input received from the user for the computation of the sum
sum = num1 + num2;
//output results
cout << num1 << " plus " << num2 << " is " << sum << endl;
return 0;
}
 A well-constructed program should validate all user input
 Ensures that program does not crash or produce nonsensical output

 ROBUST PROGRAMS: programs that detect and respond


effectively to unexpected user input
A First Look at  Also known as bullet-proof programs
User-Input  USER-INPUT VALIDATION: validating entered data and providing
Validation user with a way to re-enter invalid data
 A simple way to check input in your programs is to use a cout
statement to print the value in the variables you read in
 So if your program is not working properly this is one way you can
quickly check to see if you have a data input problem
 CONCEPT: Constants may be given names that symbolically
represent them in a program
 MAGIC NUMBERS: literal data used in a program over and over
 Some have general meaning in context of program
 Tax rate in a program to calculate taxes
Symbolic  Others have general meaning beyond the context of the program
Constants  π = 3.1416
 Euler’s number = 2.71828

 Constants can be assigned symbolic names


const float PI = 3.1416f;
const double SALESTAX = 0.05;
 const: qualifier specifies that the declared variable and the value
assigned to it cannot be changed
 Once you have specified the identifier that is tied to the literal it
cannot be changed in the program by any type of operation
Symbolic
 A const identifier can be used in any C++ statement in place of
Constants (2) number it represents
circum = 2 * PI * radius;
amount = SALESTAX * purchase;
 const identifiers commonly referred to as symbolic constants
 Advantages of using a symbolic constant
 Named constants
Symbolic  If it is used several times in the program and its value changes (like a
sales tax rate) you only have to change it once
Constants (3)  This prevents mistakes in trying to change it several times and
possibly missing a case
 This also saves time
#include <iostream>
#include <iomanip>

using namespace std;

int main()
Symbolic {
const double SALES_TAX = .05;
Constants
Example double amount;
double taxes;
double total;

//prompt the user for information


cout << "Enter the amount of your purchase before sales tax $:";
cin >> amount;
//use input received from the user for the computation of the total
price
taxes = amount * SALES_TAX;
total = amount + taxes;

Symbolic //output results


cout << fixed << setprecision(2);
Constants cout <<"\nThe taxes at a sales tax rate of " << SALES_TAX << " is "
Example (2) << taxes;

cout <<"\nThe total price including taxes is $" << total << endl;

return 0;
}
 A variable or symbolic constant must be declared before it is used
 C++ permits preprocessor directives and variable declaration
Placement of statements to be placed anywhere in program
 Doing so results in very poor program structure
Statements  It's always best to structure your program with preprocessor
directives at the top and symbolic constants and variables at the top
of the function they belong to
 As a matter of good programming practice, the order of
statements should be:
preprocessor directives
int main()
{
Placement of symbolic constants
Statements (2) variable declarations
other executable statements
return value
}
Common  Forgetting to assign or initialize values for all variables before they
are used in an expression
Programming  Forgetting to separate all variables passed to cin with an
Errors extraction symbol, >>
 EXPRESSION: sequence of operands separated by operators
 Expressions are evaluated according to precedence and
associativity of its operands
 The assignment symbol, =, is an operator
 Assigns a value to variable
 Multiple assignments allowed in one statement
Summary
 C++ provides library functions for various mathematical functions
 These functions operate on their arguments to calculate a single
value
 Arguments, separated by commas, included within parentheses
following function’s name

 Functions may be included within larger expressions


 cin object used for data input
 cin temporarily suspends statement execution until data entered
for variables in cin function
 Good programming practice: prior to a cin statement, display
message alerting user to type and number of data items to be
Summary (2) entered
 Message called a prompt

 Values can be equated to a single constant by using the const


keyword
 ARGUMENTS: items that are passed to a function through
parentheses
 Think of arguments as the input to a function
 This input will then have calculations performed on it and some sort
of result will be passed back to the program using the function.

 ASSIGNMENT STATEMENT: a C++ statement that tells the


Summary (3) – computer to determine the value of the operand to the right of
the equals sign and then store (or assign) that value in the
Key Terms locations associated with the variable to the left of the equals sign
 CAST: the operator used to force the conversion of a value to
another data type
 COERCION: a conversion of the value of the expression on the
right side of the assignment to the data type of the variable to the
left of the assignment operator
 EXPRESSION: any combination of constants and variables that
can be evaluated to yield a result
 LITERAL: a data element within a program that explicitly
identifies itself
 OVERLOADING: a property that permits the same function to be
Summary (4) – defined for different argument data types
Key Terms  ROBUST PROGRAM: a program that detects and responds
effectively to unexpected user input
 SYMBOLIC CONSTANT: an identifier that has been equated to a
constant in a declaration statement
 TRUNCATION: discarding or losing the fractional part of a value

You might also like