ITC Lect 08 (C++ - II)
ITC Lect 08 (C++ - II)
C++
Welcome to C++!
Welcome
to
C++!
Multiple lines can be printed with one
statement.
Lecture 08: C++ CS 101: Introduction7to Computing
Another Simple Program:
Adding Two Integers
• Variables
– Location in memory where a value can be stored for use by a program
– Must be declared with a name and a data type before they can be used
– Some common data types are:
• int - integer numbers
• char - characters
• double - floating point numbers
– Example: int myvariable;
• Declares a variable named myvariable of type int
– Example: int variable1, variable2;
• Declares two variables, each of type int
Enter first integer Variables can be output using std::cout << variableName
45
Enter second integer
72
Lecture 08: C++ CS 101: Introduction10
to Computing
Memory Concepts
• Variable names
– Correspond to locations in the computer's memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable, it replaces the previous
value - it is destroyed
– Reading variables from memory does not change them
• A visual representation
integer1 45
Arithmetic
• Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithmetic operators act before others (i.e., multiplication before
addition)
• Be sure to use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 08: C++ CS 101: Introduction12
to Computing
Arithmetic
• Arithmetic operators:
C++ o p era tio n Arithm etic Alg eb ra ic C++ exp ressio n
o p era to r exp ressio n
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y
Modulus % r mod s r % s
• Rules of operator precedence:
Operator(s) Operation(s) Order of evaluation (precedence)
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
References
Dietal and Dietal : How to Program C++
3rd Edition