0% found this document useful (0 votes)
9 views80 pages

Introduction of OOPs and C++

Introduction of oops and c++ Learn about OOPS concept in c++
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views80 pages

Introduction of OOPs and C++

Introduction of oops and c++ Learn about OOPS concept in c++
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Object Oriented

Programming with C++

9/19/2024 Dr. ASHISH KUMAR SAHU 1


Introduction to C++

• Programming Concept
• Basic C++
• C++ Extension from C

9/19/2024 Dr. ASHISH KUMAR SAHU 2


Focus
• Focus on
• Programming Concepts
• Programming Design Techniques

9/19/2024 Dr. ASHISH KUMAR SAHU 3


What is programming?
Programming is taking
A problem
Find the area of a rectangle
A set of data
length
width
A set of functions
area = length * width
Then,
Applying functions to data to solve the
problem

9/19/2024 Dr. ASHISH KUMAR SAHU 4


Programming Concept Evolution
• Procedural
• Object-Oriented

9/19/2024 Dr. ASHISH KUMAR SAHU 5


Procedural Concept

• The main program coordinates calls to procedures


and hands over appropriate data as parameters.

9/19/2024 Dr. ASHISH KUMAR SAHU 6


Procedural Concept (II)
• Procedural Languages
• C, Pascal, Basic, Fortran
• Facilities to
• Pass arguments to functions
• Return values from functions
• For the rectangle problem, we develop a function
int compute_area (int l, int w){
return ( l * w );
}

9/19/2024 Dr. ASHISH KUMAR SAHU 7


Object-Oriented Concept

• Objects of the program interact by sending messages to


each other
9/19/2024 Dr. ASHISH KUMAR SAHU 8
Objects
An object is an encapsulation of both functions and data
• Objects are an Abstraction
• represent real world entities
• Classes are data types that define shared common properties or attributes
• Objects are instances of a class
• Objects have State
• have a value at a particular time
• Objects have Operations
• associated set of operations called methods that describe how to carry out
operations
• Objects have Messages
• request an object to carry out one of its operations by sending it a message
• messages are the means by which we exchange data between objects

9/19/2024 Dr. ASHISH KUMAR SAHU 9


OO Perspective
Let's look at the Rectangle through object oriented eyes:
• Define a new type Rectangle (a class)
• Data
• width, length
• Function
• area()
• Create an instance of the class (an object)
• Request the object for its area

In C++, rather than writing a procedure, we define a class


that encapsulates the knowledge necessary to answer
the question - here, what is the area of the rectangle.
9/19/2024 Dr. ASHISH KUMAR SAHU 10
Object-Oriented Programming Languages

• Characteristics of OOPL:
• Encapsulation
• Inheritance
• Polymorphism
• OOPLs support :
• Modular Programming
• Ease of Development
• Maintainability

9/19/2024 Dr. ASHISH KUMAR SAHU 11


Characteristics of OOPL
• Encapsulation: Combining data structure with actions
• Data structure: represents the properties, the state, or characteristics of objects
• Actions: permissible behaviors that are controlled through the member
functions
Data hiding: Process of making certain data inaccessible
• Inheritance: Ability to derive new objects from old ones
• permits objects of a more specific class to inherit the properties (data) and
behaviors (functions) of a more general/base class
• ability to define a hierarchical relationship between objects
• Polymorphism: Ability for different objects to interpret
functions differently

9/19/2024 Dr. ASHISH KUMAR SAHU 12


Encapsulation
• Encapsulation
• Encapsulation allows the programmer to group data and the subroutines that
operate on them together in one place, and to hide irrelevant details from
the user.

• Information Hiding
• Making objects and algorithms invisible to portions of the system that do not
need them.

9/19/2024 Dr. ASHISH KUMAR SAHU 13


Inheritance Concepts

• Derive a new class (subclass) from an existing


class (base class or superclass).

• Inheritance creates a hierarchy of related


classes (types) which share code and
interface.

9/19/2024 Dr. ASHISH KUMAR SAHU 14


3. Inheritance Examples
Base Class Derived Classes
Student CommuterStudent
ResidentStudent
Shape Circle
Triangle
Rectangle
Loan CarLoan
HomeImprovementLoan
MortgageLoan
9/19/2024 Dr. ASHISH KUMAR SAHU 15
More Examples
Base Class Derived Classes
Employee Manager
Researcher
Worker
Account CheckingAccount
SavingAccount

9/19/2024 Dr. ASHISH KUMAR SAHU 16


University community members
CommunityMember

Employee Student

Faculty Staff

Administrator Teacher

9/19/2024 Dr. ASHISH KUMAR SAHU 17


Shape class hierarchy
Shape

TwoDimensionalShape ThreeDimensionalShape

Circle Square Triangle Sphere Cube Tetrahedron

9/19/2024 Dr. ASHISH KUMAR SAHU 18


Credit cards
logo
card
owner’s name
inherits
from (isa)

visa master american


card card express

hologram pin category

9/19/2024 Dr. ASHISH KUMAR SAHU 19


Simple C++ Program

9/19/2024 Dr. ASHISH KUMAR SAHU 20


A Simple C++ Program
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
return 0;
}
▪ iostream is just like we include stdio.h in c program.
▪ It contains declarations for the identifier cout and the insertion
operator <<.
▪ iostream should be included at the beginning of all programs
that use input/output statements.

9/19/2024 Dr. ASHISH KUMAR SAHU 21


A Simple
#includeC++ Program
<iostream> (Cont…)
//include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
return 0;
}
▪ A namespace is a declarative region.
▪ A namespace is a part of the program in which certain names are
recognized; outside of the namespace they’re unknown.
▪ namespace defines a scope for the identifies that are used in a
program.
▪ using and namespace are the keywords of C++.

9/19/2024 Dr. ASHISH KUMAR SAHU 22


A Simple
#includeC++ Program
<iostream> (Cont…)
//include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
return 0;
}
▪ std is the namespace where C++ standard class libraries are
defined.
▪ Various program components such as cout, cin, endl are
defined within std namespace.
▪ If we don’t use the using directive at top, we have to add the std
followed by :: in the program before identifier.
std::cout << “Hello World”;
9/19/2024 Dr. ASHISH KUMAR SAHU 23
A Simple
#includeC++ Program
<iostream> (Cont…)
//include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
return 0;
}
▪ In C++, main() returns an integer type value.
▪ Therefore, every main() in C++ should end with a return 0;
statement; otherwise error will occur.
▪ The return value from the main() function is used by the
runtime library as the exit code for the process.

9/19/2024 Dr. ASHISH KUMAR SAHU 24


Insertion Operator <<
cout << "Hello World";

▪ The operator << is called the


insertion operator.
▪ It inserts the contents of the
variable on its right to the object
on its left.
▪ The identifier cout is a predefined
object that represents standard
output stream in C++.
▪ Here, Screen represents the
output. We can also redirect the
output to other output devices. Output Using Insertion Operator
▪ The operator << is used as bitwise
left shift operator also.

9/19/2024 Dr. ASHISH KUMAR SAHU 25


Program: Basic
Write aC++ program
C++ Program to print following
Name: Ashish Kumar Sahu
City: MANIT BHOPAL
Country: India

9/19/2024 Dr. ASHISH KUMAR SAHU 26


#include <iostream>
Program: Basic C++ program
using namespace std;
int main()
{
cout << "Name: Ashish Kumar Sahu";
cout << "City: MANIT BHOPAL";
cout << "Country: India";
return 0;
}

9/19/2024 Dr. ASHISH KUMAR SAHU 27


Extraction Operator >>
cin >> number1;
▪ The operator >> is called the
extraction operator.
▪ It extracts (or takes) the value Object Extraction Operator
from keyboard and assigns it to
cin >> number1
the variable on its right.
▪ The identifier cin is a predefined Variable
object that represents standard
input stream in C++.
▪ Here, standard input stream KeyBoard
represents the Keyboard.
▪ The operator >> is used as
bitwise right shift operator also.

9/19/2024 Dr. ASHISH KUMAR SAHU 28


Program: Basic C++ program
#include<iostream>
using namespace std;
int main()
{
int number1,number2;

cout<<"Enter First Number: ";


cin>>number1; //accept first number

cout<<"Enter Second Number: ";


cin>>number2; //accept first number

cout<<"Addition : ";
cout<<number1+number2; //Display Addition
return 0;
}

9/19/2024 Dr. ASHISH KUMAR SAHU 29


C++ Tokens

9/19/2024 Dr. ASHISH KUMAR SAHU 30


C++ Tokens
• The smallest individual unit of a program is known as token.
#include <iostream>
• C++ has the following tokens:
using namespace std;
− Keywords int main()
− Identifiers {
− Constants cout << "Hello World";
− Strings return 0;
− Special Symbols }
− Operators

9/19/2024 Dr. ASHISH KUMAR SAHU 31


Keywords and Identifier
• C++ reserves a set of 84 words for its own use.
• These words are called keywords (or reserved words), and
each of these keywords has a special meaning within the C++
language.
• Identifiers are names that are given to various user defined
program elements, such as variable, function and arrays.
• Some of Predefined identifiers are cout, cin, main

❑ We cannot use Keyword as user defined identifier.

9/19/2024 Dr. ASHISH KUMAR SAHU 32


Keywords
asm in C++
double new switch
auto else operator template
break enum private this
case extern protected throw
catch float public try
char for register typeof
class friend return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while
9/19/2024 Dr. ASHISH KUMAR SAHU 33
Rules for naming identifiers in C++
1. First Character must be an alphabet or underscore.
2. It can contain only letters(a..z A..Z), digits(0 to 9) or underscore(_).
3. Identifier name cannot be keyword.
4. Only first 31 characters are significant.

9/19/2024 Dr. ASHISH KUMAR SAHU 34


Valid, Invalid Identifiers
1) Darshan Valid 12) xyz123 Valid
2) A Valid 13) part#2 Invalid
3) Age 14) "char"
Valid Invalid
4) void 15) #include
Invalid
5) MAX-ENTRIES Reserved word 16) This_is_a_
6) double Invalid 17) _xyz Valid
7) time Reserved word 18) 9xyz Valid
8) G 19) main Invalid
Valid
9) Sue's 20) mutable
Valid Standard identifier
10) return 21) double
11) cout Invalid 22) max?out
Reserved word
Reserved word Reserved word
Standard identifier Invalid
9/19/2024 Dr. ASHISH KUMAR SAHU 35
Constants
▪ Constants/inLiterals
C++ refer to fixed values that do not change during
execution of program.

CONSTANTS

NUMERIC CHARACTER
CONSTANTS CONSTANTS

SINGLE
INTEGER REAL STRING
CHARACTER
CONSTANTS CONSTANTS CONSTANTS
CONSTANTS
i.e. i.e. i.e.
i.e.
123,-321, 6543 0.0083, -0.75 “Hello”, “197”
‘5’, ‘X’, ‘;’
9/19/2024 Dr. ASHISH KUMAR SAHU 36
C++ Operators

9/19/2024 Dr. ASHISH KUMAR SAHU 37


C++• Operators
All C language operators are valid in C++.
1. Arithmetic operators (+, - , *, /, %)
2. Relational operators (<, <=, >, >=, ==, !=)
3. Logical operators (&&, ||, !)
4. Assignment operators (+=, -=, *=, /=)
5. Increment and decrement operators (++, --)
6. Conditional operators (?:)
7. Bitwise operators (&, |, ^, <<, >>)
8. Special operators ()

9/19/2024 Dr. ASHISH KUMAR SAHU 38


Arithmetic Operators
Operator example Meaning
+ a+b Addition
- a–b Subtraction
* a*b Multiplication
/ a/b Division
% a%b Modulo division- remainder

9/19/2024 Dr. ASHISH KUMAR SAHU 39


Relational Operators
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Equal to
!= Not equal to

9/19/2024 Dr. ASHISH KUMAR SAHU 40


LogicalOperator
Operators
Meaning
&& Logical AND
|| Logical OR
! Logical NOT
a b a && b a || b
true true true true
true false false true
false true false true
false false false false

❑ a && b : returns false if any of the expression is false


❑ a || b : returns true if any of the expression is true
9/19/2024 Dr. ASHISH KUMAR SAHU 41
Assignment operator
• We assign a value to a variable using the basic assignment operator
(=).
• Assignment operator stores a value in memory.
• The syntax is
leftSide = rightSide ;
It is either a literal |
Always it is a
a variable identifier |
variable identifier.
an expression.

Literal: ex. i = 1;
Variable identifier: ex. start = i;
Expression: ex. sum = first + second;
9/19/2024 Dr. ASHISH KUMAR SAHU 42
Assignment
Syntax: Operators (Shorthand)
leftSide Op= rightSide ;
It is an arithmetic
operator.

Ex: Simple assignment


Shorthand operator
x=x+3; operator
x+=3; a = a+1 a += 1
a = a-1 a -= 1
a = a * (m+n) a *= m+n
a = a / (m+n) a /= m+n
a = a % b a %= b
9/19/2024 Dr. ASHISH KUMAR SAHU 43
Increment
▪ Incrementand
++ Decrement Operators
The ++ operator used to increase the value of the variable by one
▪ Decrement ─ ─
The ─ ─ operator used to decrease the value of the variable by one
Example:
x=100;
x++;
After the execution the value of x will be 101.
Example:
x=100;
x--;
After the execution the value of x will be 99.

9/19/2024 Dr. ASHISH KUMAR SAHU 44


Pre Operator
& Post IncrementDescription
operator
Pre increment operator (++x) value of x is incremented before assigning
it to the variable on the left

x = 10 ; After execution
p = ++x; x will be 11
First increment value of p will be 11
x by one

Operator Description
Post increment operator (x++) value of x is incremented after assigning it
to the variable on the left

x = 10 ; After execution
p = x++; x will be 11
p will be 10
First assign value of x
9/19/2024 Dr. ASHISH KUMAR SAHU 45
What is the output of this program?
#include <iostream>
using namespace std;
int main ()
{
int x, y;
x = 5;
y = ++x * ++x;
cout << x << y;
x = 5;
y = x++ * ++x;
cout << x << y;
}

(A) 749735
(B) 736749
(C) 367497
(D) none of the mentioned
9/19/2024 Dr. ASHISH KUMAR SAHU 46
Conditional
Syntax: Operator
exp1 ? exp2 : exp3
Working of the ? Operator:
▪ exp1 is evaluated first
• if exp1 is true(nonzero) then
- exp2 is evaluated and its value becomes the value of the expression
• If exp1 is false(zero) then
- exp3 is evaluated and its value becomes the value of the expression
Ex: Ex:
m=2; m=2;
n=3; n=3;
r=(m>n) ? m : n; r=(m<n) ? m : n;
Value of r will be 3 Value of r will be 2
9/19/2024 Dr. ASHISH KUMAR SAHU 47
Bitwise Operator
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right

9/19/2024 Dr. ASHISH KUMAR SAHU 48


Bitwise Operator
8 =Examples
1000 (In Binary)
6 = 0110 (In Binary)
Bitwise & (AND) Bitwise | (OR)
int a=8,b=6,c; int a=8,b=6,c;
c = a & b; c = a | b;
cout<<"Output ="<< c; cout<<"Output ="<< c;
Output = 0 Output = 14
Bitwise << (Shift Left) Bitwise >> (Shift Right)
int a=8,b=6,c; int a=8,b=6,c;
c = a << 1; c = a >> 1;
cout<<"Output ="<< c; cout<<"Output ="<< c;
Output = 16 Output = 4
left shifting is the equivalent of right shifting is the equivalent
multiplying a by a power of two of dividing a by a power of two
9/19/2024 Dr. ASHISH KUMAR SAHU 49
New Operators in C++ It allows to access to the global
version of variable
:: Scope Resolution Declares a pointer to a member of
a class
::* Pointer-to-member declarator
->* Pointer-to-member operator To access pointer to class members

.* Pointer-to-member operator To access pointer to data members


of class
new Memory allocation operator
Allocates memory at run time
delete Memory release operator
endl Line feed operator Deallocates memory at run time

setw Field width operator It is a manipulator causes a linefeed


to be inserted
It is a manipulator specifies a field
width for printing value
9/19/2024 Dr. ASHISH KUMAR SAHU 50
C++ Data Types

9/19/2024 Dr. ASHISH KUMAR SAHU 51


Basic Data types C++ datatypes

User-defined Built-in Derived


structure array
union function
class pointer
enumeration reference

Integral Void Floating

int char float double

9/19/2024 Dr. ASHISH KUMAR SAHU 52


Built inData
DataType
types
Size (bytes) Range
char 1 -128 to 127
unsigned char 1 0 to 255
short or int 2 -32,768 to 32,767
unsigned int 2 0 to 65535
long 4 -2147483648 to 2147483647
unsigned long 4 0 to 4294967295
float 4 3.4e-38 to 3.4e+308
double 8 1.7e-308 to 1.7e+308
long double 10 3.4e-4932 to 1.1e+4932
9/19/2024 Dr. ASHISH KUMAR SAHU 53
Reference Vs Pointer
References Pointers
int i; int *p = &i;
int &r = i;

p
addr

r i
addr
A reference is a A pointer is a variable
variable which refers which stores the address
to another variable. of another variable.
9/19/2024 Dr. ASHISH KUMAR SAHU 54
Control Structures

9/19/2024 Dr. ASHISH KUMAR SAHU 55


Control Structures
• The if statement:
• Simple if statement
• if…else statement
• else…if ladder
• if…else nested
• The switch statement :
• The do-while statement: An exit controlled loop
• The while Statement: An entry controlled loop
• The for statement: An entry controlled loop

9/19/2024 Dr. ASHISH KUMAR SAHU 56


Control Structures
Selection: else/if, switch, do-while, while and for
structures

9/19/2024 Dr. ASHISH KUMAR SAHU 57


1. if Selection Structure
• Selection structure
• Choose among alternative courses of action
• Pseudocode example:
If student’s grade is greater than or equal to 60
Print “Passed”
• If the condition is true
• Print statement executed, program continues to next statement
• If the condition is false
• Print statement ignored, program continues
• Indenting makes programs easier to read
• C++ ignores whitespace characters (tabs, spaces, etc.)

9/19/2024 Dr. ASHISH KUMAR SAHU 58


Cont…

• Translation into C++


If student’s grade is greater than or equal to 60
Print “Passed”

if ( grade >= 60 )
cout << "Passed";

• Diamond symbol (decision symbol)


• Indicates decision is to be made
• Contains an expression that can be true or false
• Test condition, follow path
• if structure
• Single-entry/single-exit

9/19/2024 Dr. ASHISH KUMAR SAHU 59


Cont…
• Flowchart of pseudocode statement
A decision can be made on
any expression.

true zero - false


grade >= 60 print “Passed”
nonzero - true
Example:
false 3 - 4 is true

9/19/2024 Dr. ASHISH KUMAR SAHU 60


2. if/else Selection Structure
• if
• Performs action if condition true
• if/else
• Different actions if conditions true or false
• Pseudocode
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
• C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";

9/19/2024 Dr. ASHISH KUMAR SAHU 61


Cont…
• Nested if/else structures
• One inside another, test for multiple cases
• Once condition met, other statements skipped
if student’s grade is greater than or equal to 90
Print “A”
else
if student’s grade is greater than or equal to 80
Print “B”
else
if student’s grade is greater than or equal to 70
Print “C”
else
if student’s grade is greater than or equal to 60
Print “D”
else
Print “F”

9/19/2024 Dr. ASHISH KUMAR SAHU 62


Cont…
• Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";

9/19/2024 Dr. ASHISH KUMAR SAHU 63


Importance of Curly Braces
• Print “We have a problem” if examGrade < 60
• Print “We have a real problem” if examGrade < 60 and quizGrade < 10
• Print “Ok” if examGrade >= 60
int examGrade, quizGrade;
if (examGrade < 60)
cout << “We have a problem” << endl;
if (quizGrade < 10)
cout << “We have a real problem” << endl;
else
cout << “Ok”;

9/19/2024 Dr. ASHISH KUMAR SAHU 64


Exam Grade Flowchart int examGrade, quizGrade;
if (examGrade < 60)
cout << “We have a problem” << endl;
if (quizGrade < 10)
cout << “We have a real problem” << endl;
else
cout << “Ok”;

true
examGrade < 60

“We have a problem”

false true
quizGrade < 10

“Ok” “We have a real problem”

9/19/2024 Dr. ASHISH KUMAR SAHU 65


Writing Cases
• Print “We have a problem” if examGrade < 60
• Print “We have a real problem” if examGrade < 60 and quizGrade < 10
• Print “Ok” if examGrade >= 60

examGrade < 60 quizGrade < 10 Action


Case 1 true false “We have a problem”
Case 2 true true “We have a problem” and
“We have a real problem”
Case 3 false true/false “Ok”

9/19/2024 Dr. ASHISH KUMAR SAHU 66


Putting it all together
examGrade < 60 quizGrade < 10 Action
Case 1 true false “We have a problem”
Case 2 true true “We have a problem” and
“We have a real problem”
Case 3 false true/false “Ok”
int examGrade,
int examGrade,quizGrade;
quizGrade;
if
if (examGrade
(examGrade< <60)
60) {
System.out.println(“We have a problem”);
cout << “We have a problem” << endl;
if (quizGrade < 10)< 10)
if (quizGrade
System.out.printl(“We have a real problem”);
cout << “We have a real problem” << endl;
else
} System.out.println(“Ok”);
else
cout << “Ok”;

9/19/2024 Dr. ASHISH KUMAR SAHU 67


Playing Cards
• Exercise with playing cards
• Numbers represent the rank and suit of cards
// Codes for suits
const int SPADES = 0;
const int HEARTS = 1;
const int DIAMONDS = 2;
const int CLUBS = 3;

// Codes for nonnumeric ranks


const int ACE = 1;
const int JACK = 11;
const int QUEEN = 12;
const int KING = 13;

9/19/2024 Dr. ASHISH KUMAR SAHU 68


Prints a Card Name
• Print “rank of suit”
• Consider just the rank part
if (rank == JACK) Notice:
cout << "Jack"; comparing rank to
else if (rank == QUEEN) a number of
cout << "Queen"; different value
else if (rank == KING;
cout << "King";
else if (rank == ACE)
cout << "Ace";
else
cout << rank;

9/19/2024 Dr. ASHISH KUMAR SAHU 69


3. switch Multiple-Selection Structure
• switch
• Test variable for multiple values
• Series of case labels and optional default case
switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch

case value2:
case value3: // taken if variable == value2 or == value3
statements
break;

default: // taken if variable matches no other cases


statements
break;
}

9/19/2024 Dr. ASHISH KUMAR SAHU 70


Cont…
true
case a case a action(s) break

false

true
case b case b action(s) break

false

.
.
.

true
case z case z action(s) break
false

default action(s)

9/19/2024 Dr. ASHISH KUMAR SAHU 71


Cont…
switch (rank)
{
if (rank == JACK) case JACK:
cout << "Jack"; cout << "Jack";
break;
else if (rank == QUEEN) case QUEEN:
cout << "Queen"; cout << "Queen";
break;
else if (rank == KING; case KING:
cout << "King"; cout << "King";
break;
else if (rank == ACE) case ACE:
cout << "Ace"; cout << "Ace";
break;
else default:
cout << rank;
cout << rank;
}

9/19/2024 Dr. ASHISH KUMAR SAHU 72


4 while Repetition Structure
• Repetition structure
• Action repeated while some condition remains true
• Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list
• while loop repeated until condition becomes false
• Example
int product = 2;
while ( product <= 1000 )
poduct = 2 * product;

9/19/2024 Dr. ASHISH KUMAR SAHU 73


Cont…
• Counter-controlled repetition
• Loop repeated until counter reaches certain value
• Definite repetition
• Number of repetitions known
• Example
A class of ten students took a quiz. The grades (integers in the range 0 to 100)
for this quiz are available to you. Determine the class average on the quiz.

9/19/2024 Dr. ASHISH KUMAR SAHU 74


5 for• General
Repetition Structure
format when using for loops
for ( initialization; LoopContinuationTest;
increment )
statement
• Example
for( int counter = 1; counter <= 10;
counter++ )
cout << counter << endl;
• Prints integers from one to ten No
semicolo
n after
last
statement

9/19/2024 Dr. ASHISH KUMAR SAHU 75


Cont…
• for loops can usually be rewritten as while loops
initialization;
while ( loopContinuationTest){
statement
increment;
}
• Initialization and increment
• For multiple variables, use comma-separated lists
for (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl;

9/19/2024 Dr. ASHISH KUMAR SAHU 76


Cont…
• Vary the control variable from 1 to 100 in increments of 1

• Vary the control variable from 100 to 1 in increments of -1(decrements of 1)

• Vary the control variable from 7 to 77 in steps of 7

• Vary the control variable from 20 to 2 in steps of -2

• Vary the control variable over the following sequence: 2, 5, 8, 11, 14, 17, 20

• Vary the control variable over the following sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0

9/19/2024 Dr. ASHISH KUMAR SAHU 77


Cont…
• Program to calculate compound interest
• A person invests $1000.00 in a savings account yielding 5 percent interest. Assuming that all
interest is left on deposit in the account, calculate and print the amount of money in the
account at the end of each year for 10 years. Use the following formula for determining these
amounts:
a = p(1+r)n
• p is the original amount invested (i.e., the principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the nth year

9/19/2024 Dr. ASHISH KUMAR SAHU 78


6 do/while Repetition Structure
• Similar to while structure
• Makes loop continuation test at end, not beginning
• Loop body executes at least once
• Format
do {
action(s)
statement
} while ( condition );
true
condition

false

9/19/2024 Dr. ASHISH KUMAR SAHU 79


Thank You

9/19/2024 Dr. ASHISH KUMAR SAHU 80

You might also like