SlideShare a Scribd company logo
1 of 38
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

What's hot

Tokens expressionsin C++
Tokens expressionsin C++Tokens expressionsin C++
Tokens expressionsin C++HalaiHansaika
 
C programming session 05
C programming session 05C programming session 05
C programming session 05Dushmanta Nath
 
C programming session 09
C programming session 09C programming session 09
C programming session 09Dushmanta Nath
 
C++
C++C++
C++k v
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III TermAndrew Raj
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in CSahithi Naraparaju
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C ProgrammingQazi Shahzad Ali
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteachingeteaching
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_outputAnil Dutt
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C ProgrammingKamal Acharya
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 

What's hot (20)

Tokens expressionsin C++
Tokens expressionsin C++Tokens expressionsin C++
Tokens expressionsin C++
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
 
C++
C++C++
C++
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III Term
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
 
Labsheet1stud
Labsheet1studLabsheet1stud
Labsheet1stud
 
C language basics
C language basicsC language basics
C language basics
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
 
C intro
C introC intro
C intro
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
C++ Version 2
C++  Version 2C++  Version 2
C++ Version 2
 

Viewers also liked

operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++sanya6900
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++amber chaudary
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++Praveen M Jigajinni
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++rohassanie
 
Can you learn to love? The science and experience of human attachment
Can you learn to love? The science and experience of human attachmentCan you learn to love? The science and experience of human attachment
Can you learn to love? The science and experience of human attachmentDr. Jonathan Mall
 
Girls vs boys
Girls vs boysGirls vs boys
Girls vs boyscarlyrelf
 
SSRP Self Learning Guide Maths Class 10 - In Hindi
SSRP Self Learning Guide Maths Class 10 - In HindiSSRP Self Learning Guide Maths Class 10 - In Hindi
SSRP Self Learning Guide Maths Class 10 - In Hindikusumafoundation
 
Introduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented LanguagesIntroduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented LanguagesGuido Wachsmuth
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingHaris Bin Zahid
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented languagefarhan amjad
 
Cbse class 10 hindi course b model answers by candidates 2015
Cbse class 10 hindi course b model answers by candidates 2015Cbse class 10 hindi course b model answers by candidates 2015
Cbse class 10 hindi course b model answers by candidates 2015Saurabh Singh Negi
 
Object Oriented Language
Object Oriented LanguageObject Oriented Language
Object Oriented Languagedheva B
 
हिन्दी व्याकरण
हिन्दी व्याकरणहिन्दी व्याकरण
हिन्दी व्याकरणChintan Patel
 

Viewers also liked (20)

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

Similar to 02a fundamental c++ types, arithmetic

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

Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
L03vars
L03varsL03vars
L03vars
 
keyword
keywordkeyword
keyword
 
keyword
keywordkeyword
keyword
 
C++ programming
C++ programmingC++ programming
C++ programming
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
 
Chapter2
Chapter2Chapter2
Chapter2
 
Pengaturcaraan asas
Pengaturcaraan asasPengaturcaraan asas
Pengaturcaraan asas
 
Ch02
Ch02Ch02
Ch02
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Getting started with c++.pptx
Getting started with c++.pptxGetting started with c++.pptx
Getting started with c++.pptx
 
Basic of c &c++
Basic of c &c++Basic of c &c++
Basic of c &c++
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
C program
C programC program
C program
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
 

More from Manzoor ALam

8085 microprocessor ramesh gaonkar
8085 microprocessor   ramesh gaonkar8085 microprocessor   ramesh gaonkar
8085 microprocessor ramesh gaonkarManzoor ALam
 
01 introduction to cpp
01   introduction to cpp01   introduction to cpp
01 introduction to cppManzoor ALam
 
03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loopsManzoor ALam
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 

More from Manzoor ALam (6)

8085 microprocessor ramesh gaonkar
8085 microprocessor   ramesh gaonkar8085 microprocessor   ramesh gaonkar
8085 microprocessor ramesh gaonkar
 
01 introduction to cpp
01   introduction to cpp01   introduction to cpp
01 introduction to cpp
 
03b loops
03b   loops03b   loops
03b loops
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 

Recently uploaded

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 

Recently uploaded (20)

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 

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