SlideShare a Scribd company logo
1
Fundamental C++ Types
Arithmetic
2
 C++ has a large number of fundamental or built-in types
 The fundamental types fall into one of three categories
 Integer
 Floating-point
 Character
Integer type
 The basic integer type is int
 The size of an int depends on the machine and the compiler
 On PCs it is normally 16 or 32 bits
 Other integers types
 short: typically uses less bits (often 2 bytes)
 long: typically uses more bits (often 4 bytes)
 Different types allow programmers to use resources more efficiently
 Standard arithmetic and relational operations are available for these
types
Fundamental C++ Types
3
Integer constants
 Integer constants are positive or negative whole numbers
 Integer constant forms
 Decimal
 Digits 0, 1, 2, 3, 4, 5, 6, 7
 Octal (base 8)
 Digits 0, 1, 2, 3, 4, 5, 6, 7
 Hexadecimal (base 16)
 Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a , b, c, d, e, f, A, B, C, D, E, F
 Consider
31 oct and 25 dec
Decimal Constants
 Examples
 97
 40000
 50000
 23a (illegal)
 The type of the constant depends on its size, unless the type is
specified
4
Character type
 Char is for specifying character data
 char variable may hold only a single lowercase letter, a single
upper case letter, a single digit, or a single special character
like a $, 7, *, etc.
 case sensitive, i.e. a and A are not same.
 ASCII is the dominant encoding scheme
 Examples
 ' ' encoded as 32 '+' encoded as 43
 'A' encoded as 65 'Z' encoded as 90
 'a' encoded as 97 'z' encoded as 122
5
Character type
 Explicit (literal) characters within single quotes
 'a','D','*‘
Special characters - delineated by a backslash 
 Two character sequences (escape codes)
 Some important special escape codes
 t denotes a tab n denotes a new line
  denotes a backslash ' denotes a single quote
 " denotes a double quote
 't' is the explicit tab character, 'n' is the explicit
new line character, and so on
6
Floating-point type
 Floating-point type represent real numbers
 Integer part
 Fractional part
 The number 108.1517 breaks down into the following parts
 108 - integer part
 1517 - fractional part
 C++ provides three floating-point types
 Float
 (often 4 bytes) Declares floating point numbers with up to 7 significant digits
 Double
 long double
 (often 10 bytes) Declares floating point numbers with up to 19 significant digits.
7
Memory Concepts
 Variable
 Variables are names of memory locations
 Correspond to actual locations in computer's memory
 Every variable has name, type, size and value
 When new value placed into variable, overwrites previous value
 Reading variables from memory is nondestructive
cin >> integer1;
 Assume user entered 45
cin >> integer2;
 Assume user entered 72
sum = integer1 + integer2;
integer1 45
integer2 72
integer1 45
sum 117
integer2 72
integer1 45
8
Names (naming entities)
 Used to denote program values or components
 A valid name is a sequence of
 Letters (upper and lowercase)
 A name cannot start with a digit
 Names are case sensitive
 MyObject is a different name than MYOBJECT
 There are two kinds of names
 Keywords
 Identifiers
9
Keywords
 Keywords are words reserved as part of the language
 int, return, float, double
 They cannot be used by the programmer to name things
 They consist of lowercase letters only
 They have special meaning to the compiler
10
C++ key words
C++ Keywords
Keywords common to the
C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
11
Identifiers
 Identifiers are used to name entities in c++
 It consists of letters, digits or underscore
 Starts with a letter or underscore
 Can not start with a digit
 Identifiers should be
 Short enough to be reasonable to type
 Standard abbreviations are fine (but only standard abbreviations)
 Long enough to be understandable
 When using multiple word identifiers capitalize the first letter of each
word
 Examples
 Grade
 Temperature
 CameraAngle
 IntegerValue
12
Definitions/declaration
 All objects (or variable)
that are used in a program
must be defined (declared)
 An object definition specifies
 Type
 Identifier
 General definition form
Type Id, Id, ..., Id;
Known
type
List of one or
more identifiers
(Value of an object is whatever is in
its assigned memory location)
Examples
Char Response;
int MinElement;
float Score;
float Temperature;
int i;
int n;
char c;
float x;
Location in memory
where a value can
be stored for
program use
13
Type compatibilities
 Rule is to store the values in variables of the same type
 This is a type mismatch:
int int_variable;
int_variable = 2.99;
 If your compiler allows this, int variable will
most likely contain the value 2, not 2.99
14
Stream extraction and assignment operator
 >> (stream extraction operator)
 When used with cin, waits for the user to input a value and
stores the value in the variable to the right of the operator
 The user types a value, then presses the Enter (Return) key to
send the data to the computer
 Example:
int myVariable;
cin >> myVariable;
 Waits for user input, then stores input in myVariable
 = (assignment operator)
 Assigns value to a variable
 Binary operator (has two operands)
 Example:
sum = variable1 + variable2;
15
A simple program to add two numbers
1 //example
2 // program to add two numbers
3 #include <iostream.h>
4
5 int main()
6 {
7 int integer1, integer2, sum; // declaration
8
9 cout << "Enter first integern"; // prompt
10 cin >> integer1; // read an integer
11 cout << "Enter second integern"; // prompt
12 cin >> integer2; // read an integer
13 sum = integer1 + integer2; // assignment of sum
14 cout << "Sum is " << sum << endl; // print sum
15
16 return 0; // indicate that program ended successfully
17 }
•Notice how cin is used to get user input.
General form is cin>>identifier;
•Cin is an I stream object
•streams input from standard input
•uses the >> (input operator)
•Note that data entered from the keyboard
must be compatible with the data type of the
variable
endl flushes the buffer and prints a
newline.
•Variables can be output using cout << variableName.
•Generl form is cout<<expression;
•An expression is any c++ expression(string constant,
identifier, formula or function call)
•Cout is an o stream object
•streams output to standard output
•uses the << (output) operator
Calculations can be performed in output statements: alternative for
lines 13 and 14:
cout << "Sum is " << integer1 + integer2 << std::endl;
Use stream extraction
operator with standard input
stream to obtain user input.
Concatenating, chaining or
cascading stream insertion
operations.
16
Output of program
17
program to find the area of rectangle
Tells the compiler to use names
in iostream in a “standard” way
18
output
19
Program to find total number of students in all sections
1. //example
2. //to find the total number of students in all sections.
3. # include <iostream> //preprocessor directive
4. int main()
5. {
6. int number_of_sections, students_per_section; //declaration
7. int total_students;
8. cout<<"enter the number of sectionsn"; //prompt to enter total number of
sections
9. cin>>number_of_sections; //reading number of sections
10. cout<<"enter the number of students per sectionn"; //prompt to enter number
11. // of students per section
12. cin>>students_per_section; //reading students per section
13.
14. total_students = number_of_sections * students_per_section; //assignment to total
students
15. cout<<"total number of students in all the sections isn"; //prompt
16. cout<<total_students; // show the number of
total students
17. return 0;
18. }
20
output
21
Arithmetic
 Arithmetic is performed with operators.
 Arithmetic operators are listed in following table
 Modulus operator returns the remainder of integer division
7 % 5 evaluates to 2
 Integer division truncates remainder
7 / 5 evaluates to 1
C++ operation Arithmetic
operator
Algebraic
expression
C++ 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
22
Results of Arithmetic operators
 Arithmetic operators can be used with any numeric type.
 An operand is a number or variable used by the operator e.g.
 integer1 + integer2
 + is operator
 integer1 and integer2 are operands
 Result of an operator depends on the types of operands
 If both operands are int, the result is int
 If one or both operands are double, the result is double
23
24
Examples comparing mathematical and C++ expressions
25
Operator precedence
 Some arithmetic operators act before others
(e.g., 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 (incorrect)
 Use: (a + b + c ) / 3 (correct)
26
Rules of operator precedence
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested,
the expression in the innermost pair is evaluated
first. If there are several pairs of parentheses “on
the same level” (i.e., not nested), they are
evaluated left to right.
*, /, or % Multiplication Division
Modulus
Evaluated second. If there are several, they are
evaluated left to right.
+ or - Addition
Subtraction
Evaluated last. If there are several,
they are evaluated left to right.
27
Operator Precedence
An example to understand operator precedence.
20 - 4 / 5 * 2 + 3 * 5 % 4
(4 / 5)
((4 / 5) * 2)
((4 / 5) * 2) (3 * 5)
((4 / 5) * 2) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) + ((3 * 5) % 4)
28
Assignment operators
 = is the assignment operator
 Used to assign a value to a variable
 An assignment statement changes the value of a variable
 General Form:
identifier = expression;
 The single variable to be changed is always on the left
of the assignment operator ‘=‘
 On the right of the assignment operator can be
 Constants
 For example age = 21;
 Variables
 For example my_cost = your_cost;
 Expressions
 For example circumference = diameter * 3.14159;
29
Assignment operators
 The ‘=‘ operator in C++ is not an equal sign
 The following statement cannot be necessarily true in algebra
number_of_bars = number_of_bars + 3;
 In C++ it means the new value of number_of_bars
is the previous value of number_of_bars plus 3
30
Assignment expression abbreviations
 Program can be written and compiled a bit faster by the use of abbreviated
assignment operators
 C++ provides several assignment operators for abbreviating assignment
expressions.
 Addition assignment operator
c = c + 3; abbreviated to
c += 3;
 Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
 Other assignment operators
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
31
Arithmetic assignment operators
Assignment
operator
Sample
expression
Explanation Assigns
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
/= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g
32
Increment and Decrement Operators
 Increment and decrement operators are unary operators as they
require only one operand.
 ++ unary increment operator
 Adds 1 to the value of a variable
x ++;
is equivalent to x = x + 1;
 Pre-increment
 When the operator is used before the variable (++c)
 Variable is changed, then the expression it is in is
evaluated
 Post-increment
 When the operator is used after the variable (c++)
 Expression the variable is in executes, then the variable is
changed.
33
Increment and Decrement Operators
 -- -- unary decrement operator
 Subtracts 1 from the value of a variable
x --;
is equivalent to x = x – 1;
 Pre-decrement
 When the operator is used before the variable (--c)
 Variable is changed, then the expression it is in is
evaluated.
 Post-decrement
 When the operator is used after the variable (c--)
 Expression the variable is in executes, then the variable is
changed.
34
Increment and Decrement Operators
 Example
 If c = 5, then
 cout << ++c;
 c is changed to 6, then printed out
 cout << c++;
 Prints out 5 (cout is executed before the increment)
 c then becomes 6
 When variable not in expression
 Preincrementing and postincrementing have same effect
++c;
cout << c;
and
c++;
cout << c;
are the same
35
Summarizing increment and decrement operators in a table
Operator Called Sample expression Explanation
++ preincrement ++a Increment a by 1, then use the new value
of a in the expression in which a resides.
++ postincrement a++ Use the current value of a in the expression
in which a resides, then increment a by 1.
-- predecrement --b Decrement b by 1, then use the new value
of b in the expression in which b resides.
-- postdecrement b-- Use the current value of b in the expression
in which b resides, then decrement b by 1.
The associativity of these unary operators is from right to left
36
An example to understand the effect of pre-
increment and post-increment
1 // example
2 // Pre incrementing and post incrementing.
3 #include <iostream.h>
4
5
8 // function main begins program execution
9 int main()
10 {
11 int c; // declare variable
12
13 // demonstrate pos tincrement
14 c = 5; // assign 5 to c
15 cout << c << endl; // print 5
16 cout << c++ << endl; // print 5 then post increment
17 cout << c << endl << endl; // print 6
18
19 // demonstrate pre increment
20 c = 5; // assign 5 to c
21 cout << c << endl; // print 5
22 cout << ++c << endl; // pre increment then print 6
 cout << c << endl; // print 6
24
25 return 0; // indicate successful termination
26
27 } // end function main
37
output
Cout<<c prints c =5
Cout<<c++ prints c =5 then increment c by 1 to 6
Cout<<c prints c =6
Cout<<c prints c =5
Cout<<++c first increment c by one to to 6 then prints c =6
Cout<<c prints c =6
38
Precedence of the operators encountered so far
Operators Associativity Type
() left to right parentheses
++ -- static_cast<type>() left to right unary (postfix)
++ -- + - right to left unary (prefix)
* / % left to right multiplicative
+ - left to right additive
<< >> left to right insertion/extraction
< <= > >= left to right relational
== != left to right equality
?: right to left conditional
= += -= *= /= %= right to left assignment
, left to right comma

More Related Content

PPT
Getting started with c++
PPS
C programming session 02
PPT
Data type in c
PPS
C programming session 04
PPS
C programming session 01
PPTX
datatypes and variables in c language
PPTX
Chapter 2.datatypes and operators
PDF
2 expressions (ppt-2) in C++
Getting started with c++
C programming session 02
Data type in c
C programming session 04
C programming session 01
datatypes and variables in c language
Chapter 2.datatypes and operators
2 expressions (ppt-2) in C++

What's hot (20)

PPTX
Tokens expressionsin C++
PPS
C programming session 05
PPS
C programming session 09
PPTX
C++
 
PDF
C programming | Class 8 | III Term
PPT
constants, variables and datatypes in C
DOC
Labsheet1stud
PPT
C language basics
PPTX
Data Type in C Programming
PDF
C intro
PPS
basics of C and c++ by eteaching
PPTX
Structure of c_program_to_input_output
PPT
Getting Started with C++
PPTX
Data Types and Variables In C Programming
PDF
Python Programming
PDF
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
PDF
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
PPTX
C++ Basics
PDF
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
PDF
C++ Version 2
Tokens expressionsin C++
C programming session 05
C programming session 09
C++
 
C programming | Class 8 | III Term
constants, variables and datatypes in C
Labsheet1stud
C language basics
Data Type in C Programming
C intro
basics of C and c++ by eteaching
Structure of c_program_to_input_output
Getting Started with C++
Data Types and Variables In C Programming
Python Programming
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
C++ Basics
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
C++ Version 2
Ad

Viewers also liked (20)

PPT
operators and expressions in c++
PPTX
Conditional statement c++
PPT
Operators and Expressions in C++
DOC
Introduction to C++
PDF
Java Technicalities
PDF
Can you learn to love? The science and experience of human attachment
PDF
Girls vs boys
PPTX
Unit i
PDF
SSRP Self Learning Guide Maths Class 10 - In Hindi
DOC
Labsheet2
DOC
Labsheet_3
PPT
Oops Concepts
PDF
Introduction - Imperative and Object-Oriented Languages
PPTX
Object Oriented Programming
PPTX
Introduction to object oriented language
PDF
Cbse class 10 hindi course b model answers by candidates 2015
PPT
Object Oriented Language
PPT
Basics of c++
PPTX
हिन्दी व्याकरण
operators and expressions in c++
Conditional statement c++
Operators and Expressions in C++
Introduction to C++
Java Technicalities
Can you learn to love? The science and experience of human attachment
Girls vs boys
Unit i
SSRP Self Learning Guide Maths Class 10 - In Hindi
Labsheet2
Labsheet_3
Oops Concepts
Introduction - Imperative and Object-Oriented Languages
Object Oriented Programming
Introduction to object oriented language
Cbse class 10 hindi course b model answers by candidates 2015
Object Oriented Language
Basics of c++
हिन्दी व्याकरण
Ad

Similar to 02a fundamental c++ types, arithmetic (20)

PPT
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
PPT
Chapter02-S11.ppt
PPT
Chapter 2 Introduction to C++
PPTX
#Code2 create c++ for beginners
PPT
Chapter 3 Expressions and Inteactivity
PPT
Basics of c++ Programming Language
PPT
Chapter2
PDF
BASIC C++ PROGRAMMING
PPTX
Programming Fundamentals
PDF
THE C++ LECTURE 2 ON DATA STRUCTURES OF C++
PPT
Pengaturcaraan asas
PPTX
lec 2.pptx
PPTX
C++ lecture 01
PPTX
POLITEKNIK MALAYSIA
PPT
C++ basic.ppt
PPTX
Chapter1.pptx
PPT
Lecture#2 Computer languages computer system and Programming EC-105
PDF
Lecture1
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
Chapter02-S11.ppt
Chapter 2 Introduction to C++
#Code2 create c++ for beginners
Chapter 3 Expressions and Inteactivity
Basics of c++ Programming Language
Chapter2
BASIC C++ PROGRAMMING
Programming Fundamentals
THE C++ LECTURE 2 ON DATA STRUCTURES OF C++
Pengaturcaraan asas
lec 2.pptx
C++ lecture 01
POLITEKNIK MALAYSIA
C++ basic.ppt
Chapter1.pptx
Lecture#2 Computer languages computer system and Programming EC-105
Lecture1

More from Manzoor ALam (6)

PDF
8085 microprocessor ramesh gaonkar
PPT
01 introduction to cpp
PPT
03b loops
PPT
03a control structures
PPT
03 conditions loops
PPT
02 functions, variables, basic input and output of c++
8085 microprocessor ramesh gaonkar
01 introduction to cpp
03b loops
03a control structures
03 conditions loops
02 functions, variables, basic input and output of c++

Recently uploaded (20)

PPT
Mechanical Engineering MATERIALS Selection
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Geodesy 1.pptx...............................................
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Sustainable Sites - Green Building Construction
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Well-logging-methods_new................
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPTX
Construction Project Organization Group 2.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
Mechanical Engineering MATERIALS Selection
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Model Code of Practice - Construction Work - 21102022 .pdf
Geodesy 1.pptx...............................................
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Sustainable Sites - Green Building Construction
Operating System & Kernel Study Guide-1 - converted.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Well-logging-methods_new................
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Internet of Things (IOT) - A guide to understanding
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Arduino robotics embedded978-1-4302-3184-4.pdf
Construction Project Organization Group 2.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Strings in CPP - Strings in C++ are sequences of characters used to store and...
CYBER-CRIMES AND SECURITY A guide to understanding

02a fundamental c++ types, arithmetic

  • 2. 2  C++ has a large number of fundamental or built-in types  The fundamental types fall into one of three categories  Integer  Floating-point  Character Integer type  The basic integer type is int  The size of an int depends on the machine and the compiler  On PCs it is normally 16 or 32 bits  Other integers types  short: typically uses less bits (often 2 bytes)  long: typically uses more bits (often 4 bytes)  Different types allow programmers to use resources more efficiently  Standard arithmetic and relational operations are available for these types Fundamental C++ Types
  • 3. 3 Integer constants  Integer constants are positive or negative whole numbers  Integer constant forms  Decimal  Digits 0, 1, 2, 3, 4, 5, 6, 7  Octal (base 8)  Digits 0, 1, 2, 3, 4, 5, 6, 7  Hexadecimal (base 16)  Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a , b, c, d, e, f, A, B, C, D, E, F  Consider 31 oct and 25 dec Decimal Constants  Examples  97  40000  50000  23a (illegal)  The type of the constant depends on its size, unless the type is specified
  • 4. 4 Character type  Char is for specifying character data  char variable may hold only a single lowercase letter, a single upper case letter, a single digit, or a single special character like a $, 7, *, etc.  case sensitive, i.e. a and A are not same.  ASCII is the dominant encoding scheme  Examples  ' ' encoded as 32 '+' encoded as 43  'A' encoded as 65 'Z' encoded as 90  'a' encoded as 97 'z' encoded as 122
  • 5. 5 Character type  Explicit (literal) characters within single quotes  'a','D','*‘ Special characters - delineated by a backslash  Two character sequences (escape codes)  Some important special escape codes  t denotes a tab n denotes a new line  denotes a backslash ' denotes a single quote  " denotes a double quote  't' is the explicit tab character, 'n' is the explicit new line character, and so on
  • 6. 6 Floating-point type  Floating-point type represent real numbers  Integer part  Fractional part  The number 108.1517 breaks down into the following parts  108 - integer part  1517 - fractional part  C++ provides three floating-point types  Float  (often 4 bytes) Declares floating point numbers with up to 7 significant digits  Double  long double  (often 10 bytes) Declares floating point numbers with up to 19 significant digits.
  • 7. 7 Memory Concepts  Variable  Variables are names of memory locations  Correspond to actual locations in computer's memory  Every variable has name, type, size and value  When new value placed into variable, overwrites previous value  Reading variables from memory is nondestructive cin >> integer1;  Assume user entered 45 cin >> integer2;  Assume user entered 72 sum = integer1 + integer2; integer1 45 integer2 72 integer1 45 sum 117 integer2 72 integer1 45
  • 8. 8 Names (naming entities)  Used to denote program values or components  A valid name is a sequence of  Letters (upper and lowercase)  A name cannot start with a digit  Names are case sensitive  MyObject is a different name than MYOBJECT  There are two kinds of names  Keywords  Identifiers
  • 9. 9 Keywords  Keywords are words reserved as part of the language  int, return, float, double  They cannot be used by the programmer to name things  They consist of lowercase letters only  They have special meaning to the compiler
  • 10. 10 C++ key words C++ Keywords Keywords common to the C and C++ programming languages auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C++ only keywords asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t
  • 11. 11 Identifiers  Identifiers are used to name entities in c++  It consists of letters, digits or underscore  Starts with a letter or underscore  Can not start with a digit  Identifiers should be  Short enough to be reasonable to type  Standard abbreviations are fine (but only standard abbreviations)  Long enough to be understandable  When using multiple word identifiers capitalize the first letter of each word  Examples  Grade  Temperature  CameraAngle  IntegerValue
  • 12. 12 Definitions/declaration  All objects (or variable) that are used in a program must be defined (declared)  An object definition specifies  Type  Identifier  General definition form Type Id, Id, ..., Id; Known type List of one or more identifiers (Value of an object is whatever is in its assigned memory location) Examples Char Response; int MinElement; float Score; float Temperature; int i; int n; char c; float x; Location in memory where a value can be stored for program use
  • 13. 13 Type compatibilities  Rule is to store the values in variables of the same type  This is a type mismatch: int int_variable; int_variable = 2.99;  If your compiler allows this, int variable will most likely contain the value 2, not 2.99
  • 14. 14 Stream extraction and assignment operator  >> (stream extraction operator)  When used with cin, waits for the user to input a value and stores the value in the variable to the right of the operator  The user types a value, then presses the Enter (Return) key to send the data to the computer  Example: int myVariable; cin >> myVariable;  Waits for user input, then stores input in myVariable  = (assignment operator)  Assigns value to a variable  Binary operator (has two operands)  Example: sum = variable1 + variable2;
  • 15. 15 A simple program to add two numbers 1 //example 2 // program to add two numbers 3 #include <iostream.h> 4 5 int main() 6 { 7 int integer1, integer2, sum; // declaration 8 9 cout << "Enter first integern"; // prompt 10 cin >> integer1; // read an integer 11 cout << "Enter second integern"; // prompt 12 cin >> integer2; // read an integer 13 sum = integer1 + integer2; // assignment of sum 14 cout << "Sum is " << sum << endl; // print sum 15 16 return 0; // indicate that program ended successfully 17 } •Notice how cin is used to get user input. General form is cin>>identifier; •Cin is an I stream object •streams input from standard input •uses the >> (input operator) •Note that data entered from the keyboard must be compatible with the data type of the variable endl flushes the buffer and prints a newline. •Variables can be output using cout << variableName. •Generl form is cout<<expression; •An expression is any c++ expression(string constant, identifier, formula or function call) •Cout is an o stream object •streams output to standard output •uses the << (output) operator Calculations can be performed in output statements: alternative for lines 13 and 14: cout << "Sum is " << integer1 + integer2 << std::endl; Use stream extraction operator with standard input stream to obtain user input. Concatenating, chaining or cascading stream insertion operations.
  • 17. 17 program to find the area of rectangle Tells the compiler to use names in iostream in a “standard” way
  • 19. 19 Program to find total number of students in all sections 1. //example 2. //to find the total number of students in all sections. 3. # include <iostream> //preprocessor directive 4. int main() 5. { 6. int number_of_sections, students_per_section; //declaration 7. int total_students; 8. cout<<"enter the number of sectionsn"; //prompt to enter total number of sections 9. cin>>number_of_sections; //reading number of sections 10. cout<<"enter the number of students per sectionn"; //prompt to enter number 11. // of students per section 12. cin>>students_per_section; //reading students per section 13. 14. total_students = number_of_sections * students_per_section; //assignment to total students 15. cout<<"total number of students in all the sections isn"; //prompt 16. cout<<total_students; // show the number of total students 17. return 0; 18. }
  • 21. 21 Arithmetic  Arithmetic is performed with operators.  Arithmetic operators are listed in following table  Modulus operator returns the remainder of integer division 7 % 5 evaluates to 2  Integer division truncates remainder 7 / 5 evaluates to 1 C++ operation Arithmetic operator Algebraic expression C++ 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
  • 22. 22 Results of Arithmetic operators  Arithmetic operators can be used with any numeric type.  An operand is a number or variable used by the operator e.g.  integer1 + integer2  + is operator  integer1 and integer2 are operands  Result of an operator depends on the types of operands  If both operands are int, the result is int  If one or both operands are double, the result is double
  • 23. 23
  • 24. 24 Examples comparing mathematical and C++ expressions
  • 25. 25 Operator precedence  Some arithmetic operators act before others (e.g., 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 (incorrect)  Use: (a + b + c ) / 3 (correct)
  • 26. 26 Rules of operator precedence Operator(s) Operation(s) Order of evaluation (precedence) () Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right. *, /, or % Multiplication Division Modulus Evaluated second. If there are several, they are evaluated left to right. + or - Addition Subtraction Evaluated last. If there are several, they are evaluated left to right.
  • 27. 27 Operator Precedence An example to understand operator precedence. 20 - 4 / 5 * 2 + 3 * 5 % 4 (4 / 5) ((4 / 5) * 2) ((4 / 5) * 2) (3 * 5) ((4 / 5) * 2) ((3 * 5) % 4) (20 -((4 / 5) * 2)) ((3 * 5) % 4) (20 -((4 / 5) * 2)) + ((3 * 5) % 4)
  • 28. 28 Assignment operators  = is the assignment operator  Used to assign a value to a variable  An assignment statement changes the value of a variable  General Form: identifier = expression;  The single variable to be changed is always on the left of the assignment operator ‘=‘  On the right of the assignment operator can be  Constants  For example age = 21;  Variables  For example my_cost = your_cost;  Expressions  For example circumference = diameter * 3.14159;
  • 29. 29 Assignment operators  The ‘=‘ operator in C++ is not an equal sign  The following statement cannot be necessarily true in algebra number_of_bars = number_of_bars + 3;  In C++ it means the new value of number_of_bars is the previous value of number_of_bars plus 3
  • 30. 30 Assignment expression abbreviations  Program can be written and compiled a bit faster by the use of abbreviated assignment operators  C++ provides several assignment operators for abbreviating assignment expressions.  Addition assignment operator c = c + 3; abbreviated to c += 3;  Statements of the form variable = variable operator expression; can be rewritten as variable operator= expression;  Other assignment operators d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9)
  • 31. 31 Arithmetic assignment operators Assignment operator Sample expression Explanation Assigns Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += 7 c = c + 7 10 to c -= d -= 4 d = d - 4 1 to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f %= g %= 9 g = g % 9 3 to g
  • 32. 32 Increment and Decrement Operators  Increment and decrement operators are unary operators as they require only one operand.  ++ unary increment operator  Adds 1 to the value of a variable x ++; is equivalent to x = x + 1;  Pre-increment  When the operator is used before the variable (++c)  Variable is changed, then the expression it is in is evaluated  Post-increment  When the operator is used after the variable (c++)  Expression the variable is in executes, then the variable is changed.
  • 33. 33 Increment and Decrement Operators  -- -- unary decrement operator  Subtracts 1 from the value of a variable x --; is equivalent to x = x – 1;  Pre-decrement  When the operator is used before the variable (--c)  Variable is changed, then the expression it is in is evaluated.  Post-decrement  When the operator is used after the variable (c--)  Expression the variable is in executes, then the variable is changed.
  • 34. 34 Increment and Decrement Operators  Example  If c = 5, then  cout << ++c;  c is changed to 6, then printed out  cout << c++;  Prints out 5 (cout is executed before the increment)  c then becomes 6  When variable not in expression  Preincrementing and postincrementing have same effect ++c; cout << c; and c++; cout << c; are the same
  • 35. 35 Summarizing increment and decrement operators in a table Operator Called Sample expression Explanation ++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides. ++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1. -- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides. -- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1. The associativity of these unary operators is from right to left
  • 36. 36 An example to understand the effect of pre- increment and post-increment 1 // example 2 // Pre incrementing and post incrementing. 3 #include <iostream.h> 4 5 8 // function main begins program execution 9 int main() 10 { 11 int c; // declare variable 12 13 // demonstrate pos tincrement 14 c = 5; // assign 5 to c 15 cout << c << endl; // print 5 16 cout << c++ << endl; // print 5 then post increment 17 cout << c << endl << endl; // print 6 18 19 // demonstrate pre increment 20 c = 5; // assign 5 to c 21 cout << c << endl; // print 5 22 cout << ++c << endl; // pre increment then print 6  cout << c << endl; // print 6 24 25 return 0; // indicate successful termination 26 27 } // end function main
  • 37. 37 output Cout<<c prints c =5 Cout<<c++ prints c =5 then increment c by 1 to 6 Cout<<c prints c =6 Cout<<c prints c =5 Cout<<++c first increment c by one to to 6 then prints c =6 Cout<<c prints c =6
  • 38. 38 Precedence of the operators encountered so far Operators Associativity Type () left to right parentheses ++ -- static_cast<type>() left to right unary (postfix) ++ -- + - right to left unary (prefix) * / % left to right multiplicative + - left to right additive << >> left to right insertion/extraction < <= > >= left to right relational == != left to right equality ?: right to left conditional = += -= *= /= %= right to left assignment , left to right comma