ITC Lect 08 (C++ - II)
ITC Lect 08 (C++ - II)
C++
Shahab Haider
Welcome to C++!
10}
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 operators:
C ++ operation Arithmetic Algebraic C ++ expression
operator expression
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)
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
4 #include <iostream>
10 int main()
11 {
13
26 3 is less than 7
27 if ( num1 > num2 )
28 cout << num1 << " is greater than " << num2 << endl;
29
33
34 if ( num1 >= num2 )
35 cout << num1 << " is greater than or equal to "
36 << num2 << endl;
37
38 return 0; // indicate that program ended successfully
39 }
Errors
• Types are
• Syntax error
» Compiler error
• Linker error
• Semantic error
» Runtime error / Exception
» Logical error
Decisions
• If statement
• If else statement
• Switch statement
References
Dietal and Dietal : How to Program C++
3rd Edition