Introduction to
Programming II
Lecture 4
Outline
C++ Input / Output :
Input / Output Operations
Using iostream
Output Stream
Input Stream
C++ Operators
Arithmetic Operators
Assignment Operator
Increment/Decrement Operators
Compound Assignment Operators
Relational Operators
Logical Operators
Order of Precedence
2
The Insertion Operator (<<)
• To send output to the screen we use the insertion
operator on the object cout
• Format: cout << Expression;
• The compiler figures out the type of the object and
prints it out appropriately
cout << 5; // Outputs 5
cout << 4.1; // Outputs 4.1
cout << “String”; // Outputs String
cout << ‘\n’; // Outputs a newline
3
Stream-Insertion Operator
– cout << ‘\n’;
• Prints newline character
– cout << endl;
• endl is a stream manipulator that issues a newline character
Cascading Stream-Insertion/Extraction
Operators
– This enables cascading
cout << "How" << " are" << " you?";
Make sure to use parenthesis:
cout << "1 + 2 = " << (1 + 2);
NOT
cout << "1 4+ 2 = " << 1 + 2;
Printing Variables
– int x =12; cout << x; // prints 12
– cout << “x”; // prints x
I. Manipulators
• C++ manipulators
– Manipulators are functions specifically designed to be
used in conjunction with the insertion (<<) and extraction
(>>) operators on stream objects.
– must include iomanip to use
– several are provided to do useful things
5
Output Manipulators (no args)
Manipulators included like arguments in extraction
endl - outputs a new line character, flushes output
dec - sets int output to decimal
hex - sets int output to hexadecimal
oct - sets int output to octal
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int x = 42;
cout << oct << x << endl; // Outputs 52\n
cout << hex << x << endl; // Outputs 2a\n
cout << dec << x << endl; // Outputs 42\n
6
II. Setting the Width & Setting the Fill Character
• You can use the width(int) function to set the width
for printing a value, but it only works for the next
insertion command :
int x = 42;
cout.width(5);
cout << x << ‘\n’; // Outputs 42
Cout << x << ‘\n’; // Outputs 42
Use the fill(char) function to set the fill character.
int x = 42;
cout.width(5);
cout.fill(‘*’);
cout << x << ‘\n’; // Outputs ***42
7
Escape Sequence
All escape sequences
8
should be written within single quotes ‘ ‘
Examples
cout<<"Please enter the student's grades:”;
Please enter the student's grades:
cout<<"The class average is “<< average;
The class average is 95.5
cout<<“The total area is “<< area<< “and the total cost is “<< cost << “$.”;
The total area is 60.2 and the total cost is 4530 $.
Cout<<"The student received an”<< grade << “ grade in the course.";
The student received an A grade in the course.
9
Examples (Con.)
Cout<<”The grade is “<< grade << gradesymb;
The grade is A+
Cout<<"I am the first line\n”;
Cout<<“\n I am the second line\n";
I am the first line
I am the second line
10
Input Stream
The Extraction Operator (>>)
• To get input from the keyboard we use the
extraction operator and the object cin
• Format: cin >> Variable;
• No need for & in front of variable
• The compiler figures out the type of the variable and
reads in the appropriate type
int X;
float Y;
cin >> X; // Reads in an integer
cin >> Y; // Reads in a float
11
Stream Input
• >> (stream-extraction)
– Used to perform stream input
– Normally ignores whitespaces (spaces, tabs, newlines)
– Returns zero (false) when EOF is encountered,
otherwise returns reference to the object from which
it was invoked (i.e. cin)
• This enables cascaded input
cin >> x >> y;
cin inputs ints, chars, null-terminated
strings, string objects
12
Chaining Calls
• Multiple uses of the insertion and extraction
operator can be chained together:
cout << E1 << E2 << E3 << … ;
cin >> V1 >> V2 >> V3 >> …;
• Equivalent to performing the set of insertion or
extraction operators one at a time
• Example
cout << “Total sales are $” << sales << ‘\n’;
cin >> Sales1 >> Sales2 >> Sales3;
13
Extraction/Insertion Example
cout << “Hello world!”;
int i=5;
cout << “The value of i is “ << i << endl;
OUTPUT:
Hello World! The value of i is 5 //endl puts a new line
Char letter;
cout << “Please enter the first letter of your name: “;
cin >> letter;
Cout<< “Your name starts with“ << letter;
OUTPUT:
Please enter the first letter of your name: F
Your name starts with F
14
Example: area f circle
#include <iostream>
using namespace std;
int main()
{
float area;
int r;
cout << "Enter the radius of circle: " << endl;
cin>> r;
area=3.14*r*r;
cout << "The area of circle is: " << area <<endl;
return 0;
}
Operators
• Operators are special symbols used for:
– arithmetic calculations
– assignment statements
– logical comparisons
• Examples of operators:
– 3+5 // uses + operator
– 14 + 5 – 4 * (5 – 3) // uses +, -, * operators
• Expressions: can be combinations of variables and
operators that result in a value
16
C++ Operators
• In C++, there are 6 different groups of
operators:
– Arithmetic Operators
– Assignment Operator
– Increment / Decrement Operators
– Compound Assignment Operators
– Relational Operators
– Logical Operators
17
C++ Operators: Arithmetic Operators
18
C++ Operators: Arithmetic Operators
• Implicit casting:
– is an automatic type conversion by the compiler.
– If operands of mixed types are used, the compiler will convert
one operand to agree with the other. To do this, it uses a
hierarchy of data types:
• Long double (highest)
• Double
• Float
• Unsigned long int
• Long int
• Unsigned int
• Int (lowest)
– boolean, character, wide character, enumeration, and short
integer data types are promoted to int
19
C++ Operators: Arithmetic Operators
• Implicit casting:
– Example(1): 5+23.67 The compiler will converts 5
to floating point number because it’s higher than
int in the data type hierarchy
– Example(2):
short a=2000;
int b;
b=a; the value of a has been promoted
from short to int
20
C++ Operators: Arithmetic Operators
• Explicit casting:
– Performed by placing (data type) prior the intended
variable|value|expression
– Example(1):
short a=2000;
int b;
b = (int) a;
– Example(2):
int nValue1 = 10;
int nValue2 = 4;
float fValue = (float) (nValue1 / nValue2);
21
C++ Operators: Arithmetic Operators
Type Cast Explicit casting:
converting an expression to a different type by writing the desired type
in parentheses in front of the expression or the variable.
• Example:
Rounding a number 35.51 is rounded to 36 35.12 is rounded to 35
double x; 35.51 35.12
int rounded_x +0.50 +0.50
/* code to give x a value 36.01 35.62
omitted*/
rounded_x = (int) (x + 0.5);
22
Division Example
• Example of division issues:
10 / 3 gives 3
10.0 / 3 gives 3.33333
• As we can see,
• if we divide two integers we get an integer result.
• if one or both operands is a floating-point value we
get a floating-point result.
• If the operands are from different data type, especially
dividing floating-point number by an integer or vice a
versa the result will be a floating-point number
23
Modulus Example
Generates the remainder when you divide two
integer values.
• 5%3 gives 2 5%4 gives 1
• 5%5 gives 0 5%10 gives 5
Modulus operator is most commonly used with
integer operands. If we attempt to use the modulus
operator on floating-point values we will garbage!
(Why?)
Page 24
C++ Operators: Assignment Operator
• We assign a value to a variable using the basic assignment
operator (=).
• Assignment operator:
– Stores a value in a memory.
– Basically used in C++ to initialize a variable with a value OR to
update it’s content with a new value
– It’s syntax is as following
leftSide = rightSide ;
It is either a literal , a
It is always a variable
variable identifier , or an
identifier.
expression.
25
C++ Operators: Assignment Operator
• The assignment operator (=) assigns the value
on the right side of the operator to the
variable appearing on the left side of the
operator.
• The right side may be either:
1. Literal: e.g. i = 1;
2. Variable identifier: e.g. start = i;
3. Expression: e.g. sum = first + second;
26
1.Assigning Literals
• In this case, the literal is stored in the
memory space allocated for the variable on
the left side. A. Variables are
allocated in memory.
firstNumber 1
A
secondNumber ???
int firstNumber=1, secondNumber;
firstNumber = 234;
secondNumber = 87; B B. Literals are
assigned to variables.
firstNumber 234
Code secondNumber 87
State of Memory
27
2.Assigning Variables
• In this case, the value of the variable on the right side is
stored in the memory space allocated for the variable on
the left side.
A. Variables are
allocated in memory.
A firstNumber 1
int firstNumber=1, i; i ???
firstNumber = 234;
i = firstNumber; B B. values are assigned
to variables.
firstNumber 234
Code i 234
28 State of Memory
3.Assigning Expressions
• In this case, the result of evaluating the expression (on the right
side) is stored in the memory space allocated for the variable (on
the left side). A. Variables are
allocated in memory.
first ??? second ???
A
int first, second, sum; sum ???
first = 234;
second = 87; B B. Values are assigned
Sum = first + second to variables.
first 234 second 87
Code
sum 321
State of Memory
29
Example of Initializing and Updating Data using
assignment operator
A. The variable
is allocated in
memory and
initializes with the
value 100
int number=100; A number 100
number = 237; B B. The value 237
overwrites the
number = 35; C previous value 100
number 237
C. The value 35
overwrites the
previous value 237.
number 35
Code
30 State of Memory
Mixed Data Types in an Assignment
Statement
• The variable to the left of the equals sign determines the data types
of an expression.
If both operands of an expression are integer→ then the data type of
such an expression will be integer.
If both operands of an expression are double→ then the data type of
such an expression will be double.
An expression that has operands of both type integer and double is a
mixed-type expression. The data type of such a mixed-type expression
→ will be double.
31 C Language Elements
Mixed Data Types in an Assignment
Statement
32
• Example: if x is int and y is double then
x = 7 * 0.5; 3
y = 7 * 0.5; 3.50
x = 100/5; 20
y = 100/5; 20.00
C Language Elements