SlideShare uma empresa Scribd logo
1 de 7
Baixar para ler offline
Loops Intro to Programming
MUHAMMAD HAMMAD WASEEM 1
Loops
The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This
involves repeating some portion of the program either a specified number of times or until a particular
condition is being satisfied. This repetitive operation is done through a loop control instruction.
There are three methods by way of which we can repeat a part of program. They are:
 Using for statement
 Using a while statement
 Using a do-while statement
The for Loop
The most popular looping instruction. The for allows us to specify three things about a loop in a
single line:
 Setting a loop counter to an initial value.
 Testing the loop counter ro determine whether its value has reached the number of repetitions
desired.
 Increasing the value of loop counter each time the program segment within the loop has been
executed.
The general form of for statement is as under:
for(initialize counter; test counter; increment counter)
{
do this ;
and this ;
}
Let us write down the simple interest program using for.
/* Calculation of simple interest for 3 sets of p, n and r */
main ( )
{
int p, n, count ;
float r, si ;
for ( count = 1 ; count <= 3 ; count = count + 1 )
{
printf ( "Enter values of p, n, and r " ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "Simple Interest = Rs.%fn", si ) ;
}
}
Let us now examine how the for statement gets executed:
− When the for statement is executed for the first time, the value of count is set to an initial value 1.
− Now the condition count <= 3 is tested. Since count is 1 the condition is satisfied and the body
of the loop is executed for the first time.
− Upon reaching the closing brace of for, control is sent back to the for statement, where the value
of count gets incremented by 1.
− Again the test is performed to check whether the new value of count exceeds 3.
Loops Intro to Programming
MUHAMMAD HAMMAD WASEEM 2
− If the value of count is still within the range 1 to 3, the statements within the braces of for are
executed again.
− The body of the for loop continues to get executed till count doesn’t exceed the final value 3.
− When count reaches the value 4 the control exits from the loop and is transferred to the statement
(if any) immediately after the body of for.
The following figure would help in further clarifying the concept of execution of the for loop.
It is important to note that the initialization, testing and incrimination part of a for loop can be
replaced by any valid expression.
Let us now write down the program to print numbers from 1 to 10 in different ways.
main( )
{
int i ;
for ( i = 1 ; i <= 10 ; i = i + 1 )
printf ( "%dn", i ) ;
}
Note that the initialization, testing and incrimination of loop counter is done in the for statement
itself. Instead of i = i + 1, the statements i++ or i += 1 can also be used.
Since there is only one statement in the body of the for loop, the pair of braces have been dropped.
main( ) {
int i ;
for ( i = 1 ; i <= 10 ; )
{
printf ( "%dn", i ) ;
i = i + 1 ;
}
}
Here, the incrimination is done within the body of the for loop and not in the for statement. Note
that inspite of this the semicolon after the condition is necessary.
Loops Intro to Programming
MUHAMMAD HAMMAD WASEEM 3
main( ) {
int i = 1 ;
for ( ; i <= 10 ; i = i + 1 )
printf ( "%dn", i ) ;
}
Here the initialization is done in the declaration statement itself, but still the semicolon before
the condition is necessary.
main( )
{
int i = 1 ;
for ( ; i <= 10 ; )
{
printf ( "%dn", i ) ;
i = i + 1 ;
}
}
Here, neither the initialization, nor the incrimination is done in the for statement, but still the
two semicolons are necessary.
main( )
{
int i ;
for ( i = 0 ; i++ < 10 ; )
printf ( "%dn", i ) ;
}
Here, the comparison as well as the incrimination is done through the same statement, i++ < 10.
Since the ++ operator comes after i firstly comparison is done, followed by incrimination. Note that it is
necessary to initialize i to 0.
main( )
{
int i ;
for ( i = 0 ; ++i <= 10 ; )
printf ( "%dn", i ) ;
}
Here, both, the comparison and the incrimination is done through the same statement, ++i <=
10. Since ++ precedes i firstly incrimination is done, followed by comparison. Note that it is necessary to
initialize i to 0.
Loops Intro to Programming
MUHAMMAD HAMMAD WASEEM 4
The while Loop
It is often the case in programming that you want to do something a fixed number of times.
Perhaps you want to calculate gross salaries of ten different persons, or you want to convert
temperatures from centigrade to Fahrenheit for 15 different cities.
The while loop is ideally suited for such cases. The general syntax of while loop is:
initialize loop counter;
while(test loop counter using a condition)
{
do this;
and this;
increment loop counter;
}
Let us look at a simple example, which uses a while loop.
/* Calculation of simple interest for 3 sets of p, n and r */
main( )
{
int p, n, count ;
float r, si ;
count = 1 ;
while ( count <= 3 )
{
printf ( "nEnter values of p, n and r " ) ;
scanf ( "%d %d %f”, &p, &n, &r);
si = p*n*r/100;
printf(“Simple intrest = Rs. %f”,si);
count=count+1;
}
}
The program executes all statements after the while 3 times. The logic for calculating the simple
interest is written within a pair of braces immediately after the while keyword. These statements form
what is called the ‘body’ of the while loop. The parenthesis after the while contain a condition. So long
as this condition remains true all statements within the body of the while loop keep getting executed
repeatedly. To begin with the variable count is initialized to 1 and every time the simple interest logic is
executed the value of count is incremented by one. The variable count is many a time called either a
‘loop counter’ or an ‘index variable’.
Note the following points about while…
− The statements within while loop would keep on getting executed till the condition being tested
remains true. When the condition becomes false, the control passes to the first statement that
follows the body of the while loop.
Loops Intro to Programming
MUHAMMAD HAMMAD WASEEM 5
In place of the condition there can be any other valid expression. So long as the expression evaluates
to a non-zero value the statements within the loop would get executed.
− The condition being tested may use relational or logical operators as shown in the following
examples:
while ( i <= 10 )
while ( i >= 10 && j <= 15 )
while ( j > 10 &&(b<15||c<20)
− The statements within the loop may be a single line or a block of statements. In the first case the
parenthesis are optional. For example,
while (i<=10)
i=i+1;
is same as
while (i<=10)
{
i=i+1;
}
− As a rule the while must test a condition that will eventually become false, otherwise the loop would
be executed forever, indefinitely,
main()
{
int i=1;
while(i<=10)
printf(“%dn”,i);
}
This is an indefinite loop, since I remains equal to 1 forever. The correct form would be as under:
main()
{
int i=1;
while(i<=10)
{
printf(“%dn”,i);
i=i+1;
}
}
− Instead of incrementing a loop counter, we can even decrement it and still manage to get the body
of the loop executed repeatedly. This is shown below:
main()
{
int i=5;
while(i>=1)
{
printf(“nMake the computer literate!”);
i=i-1;
}}
Loops Intro to Programming
MUHAMMAD HAMMAD WASEEM 6
− It is not necessary that a loop counter must only be an int. it can even be a float.
main()
{
float a=10.0;
while(a<=10.5)
{
printf(“nRaindrops on roses…”);
printf(“…and whiskers on kittens”);
a=a+0.1;
}
}
The do-while Loop
The do-while loop looks like this:
do
{
this ;
and this ;
and this ;
and this ;
} while ( this condition is true ) ;
There is a minor difference between the working of while and do-while loops. This difference is
the place where the condition is tested. The while tests the condition before executing any of the
statements within the while loop. As against this, the do-while tests the condition after having executed
the statements within the loop.
The do-while would execute its statements at least once, even if the condition fails for the first
time. The while, on the other hand will not execute its statements if the condition fails for the first time.
This difference is brought about more clearly by the following program.
main( )
{
while ( 4 < 1 )
printf ( "Hello there n") ;
}
Here, since the condition fails the first time itself, the printf( ) will not get executed at all. Let's
now write the same program using a do-while loop.
main( )
{
do{
printf ( "Hello there n") ;
} while ( 4 < 1 ) ;
}
In this program the printf( ) would be executed once, since first the body of the loop is executed
and then the condition is tested.
There are some occasions when we want to execute a loop at least once no matter what.
Loops Intro to Programming
MUHAMMAD HAMMAD WASEEM 7
Nesting of Loops
The way if statements can be nested, similarly whiles and fors can also be nested. To understand
how nested loops work, look at the program given below:
/* Demonstration of nested loops */
main( )
{
int r, c, sum ;
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
{
for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */
{
sum = r + c ;
printf ( "r = %d c = %d sum = %dn", r, c, sum ) ;
}
}
}
When you run this program you will get the following output:
r = 1 c = 1 sum = 2
r = 1 c = 2 sum = 3
r = 2 c = 1 sum = 3
r = 2 c = 2 sum = 4
r = 3 c = 1 sum = 4
r = 3 c = 2 sum = 5
Here, for each value of r the inner loop is cycled through twice, with the variable c taking values
from 1 to 2. The inner loop terminates when the value of c exceeds 2, and the outer loop terminates
when the value of r exceeds 3.
As you can see, the body of the outer for loop is indented, and the body of the inner for loop is
further indented. These multiple indentations make the program easier to understand.
Instead of using two statements, one to calculate sum and another to print it out, we can
compact this into one single statement by saying:
printf ( "r = %d c = %d sum = %dn", r, c, r + c ) ;
The way for loops have been nested here, similarly, two while loops can also be nested. Not only
this, a for loop can occur within a while loop, or a while within a for.

Mais conteúdo relacionado

Mais procurados

Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++Muhammad Hammad Waseem
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements Tarun Sharma
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.Haard Shah
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cSowmya Jyothi
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++Neeru Mittal
 
Decision making statements in C programming
Decision making statements in C programmingDecision making statements in C programming
Decision making statements in C programmingRabin BK
 

Mais procurados (20)

[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Control structure
Control structureControl structure
Control structure
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
 
Ch3 selection
Ch3 selectionCh3 selection
Ch3 selection
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in c
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
Control structure in c
Control structure in cControl structure in c
Control structure in c
 
Decision making statements in C programming
Decision making statements in C programmingDecision making statements in C programming
Decision making statements in C programming
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 

Semelhante a [ITP - Lecture 11] Loops in C/C++

Semelhante a [ITP - Lecture 11] Loops in C/C++ (20)

Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopLoops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
ICP - Lecture 9
ICP - Lecture 9ICP - Lecture 9
ICP - Lecture 9
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Looping
LoopingLooping
Looping
 
M C6java6
M C6java6M C6java6
M C6java6
 
Loops in c
Loops in cLoops in c
Loops in c
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
 
loops and iteration.docx
loops and iteration.docxloops and iteration.docx
loops and iteration.docx
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
Programming Fundamentals lecture 8
Programming Fundamentals lecture 8Programming Fundamentals lecture 8
Programming Fundamentals lecture 8
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
Workbook_2_Problem_Solving_and_programming.pdf
Workbook_2_Problem_Solving_and_programming.pdfWorkbook_2_Problem_Solving_and_programming.pdf
Workbook_2_Problem_Solving_and_programming.pdf
 
UNIT 2 PPT.pdf
UNIT 2 PPT.pdfUNIT 2 PPT.pdf
UNIT 2 PPT.pdf
 

Mais de Muhammad Hammad Waseem

[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)Muhammad Hammad Waseem
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++Muhammad Hammad Waseem
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++Muhammad Hammad Waseem
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of ProgrammingMuhammad Hammad Waseem
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming LanguagesMuhammad Hammad Waseem
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnTypeMuhammad Hammad Waseem
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their AccessingMuhammad Hammad Waseem
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)Muhammad Hammad Waseem
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOPMuhammad Hammad Waseem
 

Mais de Muhammad Hammad Waseem (20)

[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
 
[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
 
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms
 
[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOP[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOP
 
[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP
 
Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]
 

Último

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 

Último (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

[ITP - Lecture 11] Loops in C/C++

  • 1. Loops Intro to Programming MUHAMMAD HAMMAD WASEEM 1 Loops The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control instruction. There are three methods by way of which we can repeat a part of program. They are:  Using for statement  Using a while statement  Using a do-while statement The for Loop The most popular looping instruction. The for allows us to specify three things about a loop in a single line:  Setting a loop counter to an initial value.  Testing the loop counter ro determine whether its value has reached the number of repetitions desired.  Increasing the value of loop counter each time the program segment within the loop has been executed. The general form of for statement is as under: for(initialize counter; test counter; increment counter) { do this ; and this ; } Let us write down the simple interest program using for. /* Calculation of simple interest for 3 sets of p, n and r */ main ( ) { int p, n, count ; float r, si ; for ( count = 1 ; count <= 3 ; count = count + 1 ) { printf ( "Enter values of p, n, and r " ) ; scanf ( "%d %d %f", &p, &n, &r ) ; si = p * n * r / 100 ; printf ( "Simple Interest = Rs.%fn", si ) ; } } Let us now examine how the for statement gets executed: − When the for statement is executed for the first time, the value of count is set to an initial value 1. − Now the condition count <= 3 is tested. Since count is 1 the condition is satisfied and the body of the loop is executed for the first time. − Upon reaching the closing brace of for, control is sent back to the for statement, where the value of count gets incremented by 1. − Again the test is performed to check whether the new value of count exceeds 3.
  • 2. Loops Intro to Programming MUHAMMAD HAMMAD WASEEM 2 − If the value of count is still within the range 1 to 3, the statements within the braces of for are executed again. − The body of the for loop continues to get executed till count doesn’t exceed the final value 3. − When count reaches the value 4 the control exits from the loop and is transferred to the statement (if any) immediately after the body of for. The following figure would help in further clarifying the concept of execution of the for loop. It is important to note that the initialization, testing and incrimination part of a for loop can be replaced by any valid expression. Let us now write down the program to print numbers from 1 to 10 in different ways. main( ) { int i ; for ( i = 1 ; i <= 10 ; i = i + 1 ) printf ( "%dn", i ) ; } Note that the initialization, testing and incrimination of loop counter is done in the for statement itself. Instead of i = i + 1, the statements i++ or i += 1 can also be used. Since there is only one statement in the body of the for loop, the pair of braces have been dropped. main( ) { int i ; for ( i = 1 ; i <= 10 ; ) { printf ( "%dn", i ) ; i = i + 1 ; } } Here, the incrimination is done within the body of the for loop and not in the for statement. Note that inspite of this the semicolon after the condition is necessary.
  • 3. Loops Intro to Programming MUHAMMAD HAMMAD WASEEM 3 main( ) { int i = 1 ; for ( ; i <= 10 ; i = i + 1 ) printf ( "%dn", i ) ; } Here the initialization is done in the declaration statement itself, but still the semicolon before the condition is necessary. main( ) { int i = 1 ; for ( ; i <= 10 ; ) { printf ( "%dn", i ) ; i = i + 1 ; } } Here, neither the initialization, nor the incrimination is done in the for statement, but still the two semicolons are necessary. main( ) { int i ; for ( i = 0 ; i++ < 10 ; ) printf ( "%dn", i ) ; } Here, the comparison as well as the incrimination is done through the same statement, i++ < 10. Since the ++ operator comes after i firstly comparison is done, followed by incrimination. Note that it is necessary to initialize i to 0. main( ) { int i ; for ( i = 0 ; ++i <= 10 ; ) printf ( "%dn", i ) ; } Here, both, the comparison and the incrimination is done through the same statement, ++i <= 10. Since ++ precedes i firstly incrimination is done, followed by comparison. Note that it is necessary to initialize i to 0.
  • 4. Loops Intro to Programming MUHAMMAD HAMMAD WASEEM 4 The while Loop It is often the case in programming that you want to do something a fixed number of times. Perhaps you want to calculate gross salaries of ten different persons, or you want to convert temperatures from centigrade to Fahrenheit for 15 different cities. The while loop is ideally suited for such cases. The general syntax of while loop is: initialize loop counter; while(test loop counter using a condition) { do this; and this; increment loop counter; } Let us look at a simple example, which uses a while loop. /* Calculation of simple interest for 3 sets of p, n and r */ main( ) { int p, n, count ; float r, si ; count = 1 ; while ( count <= 3 ) { printf ( "nEnter values of p, n and r " ) ; scanf ( "%d %d %f”, &p, &n, &r); si = p*n*r/100; printf(“Simple intrest = Rs. %f”,si); count=count+1; } } The program executes all statements after the while 3 times. The logic for calculating the simple interest is written within a pair of braces immediately after the while keyword. These statements form what is called the ‘body’ of the while loop. The parenthesis after the while contain a condition. So long as this condition remains true all statements within the body of the while loop keep getting executed repeatedly. To begin with the variable count is initialized to 1 and every time the simple interest logic is executed the value of count is incremented by one. The variable count is many a time called either a ‘loop counter’ or an ‘index variable’. Note the following points about while… − The statements within while loop would keep on getting executed till the condition being tested remains true. When the condition becomes false, the control passes to the first statement that follows the body of the while loop.
  • 5. Loops Intro to Programming MUHAMMAD HAMMAD WASEEM 5 In place of the condition there can be any other valid expression. So long as the expression evaluates to a non-zero value the statements within the loop would get executed. − The condition being tested may use relational or logical operators as shown in the following examples: while ( i <= 10 ) while ( i >= 10 && j <= 15 ) while ( j > 10 &&(b<15||c<20) − The statements within the loop may be a single line or a block of statements. In the first case the parenthesis are optional. For example, while (i<=10) i=i+1; is same as while (i<=10) { i=i+1; } − As a rule the while must test a condition that will eventually become false, otherwise the loop would be executed forever, indefinitely, main() { int i=1; while(i<=10) printf(“%dn”,i); } This is an indefinite loop, since I remains equal to 1 forever. The correct form would be as under: main() { int i=1; while(i<=10) { printf(“%dn”,i); i=i+1; } } − Instead of incrementing a loop counter, we can even decrement it and still manage to get the body of the loop executed repeatedly. This is shown below: main() { int i=5; while(i>=1) { printf(“nMake the computer literate!”); i=i-1; }}
  • 6. Loops Intro to Programming MUHAMMAD HAMMAD WASEEM 6 − It is not necessary that a loop counter must only be an int. it can even be a float. main() { float a=10.0; while(a<=10.5) { printf(“nRaindrops on roses…”); printf(“…and whiskers on kittens”); a=a+0.1; } } The do-while Loop The do-while loop looks like this: do { this ; and this ; and this ; and this ; } while ( this condition is true ) ; There is a minor difference between the working of while and do-while loops. This difference is the place where the condition is tested. The while tests the condition before executing any of the statements within the while loop. As against this, the do-while tests the condition after having executed the statements within the loop. The do-while would execute its statements at least once, even if the condition fails for the first time. The while, on the other hand will not execute its statements if the condition fails for the first time. This difference is brought about more clearly by the following program. main( ) { while ( 4 < 1 ) printf ( "Hello there n") ; } Here, since the condition fails the first time itself, the printf( ) will not get executed at all. Let's now write the same program using a do-while loop. main( ) { do{ printf ( "Hello there n") ; } while ( 4 < 1 ) ; } In this program the printf( ) would be executed once, since first the body of the loop is executed and then the condition is tested. There are some occasions when we want to execute a loop at least once no matter what.
  • 7. Loops Intro to Programming MUHAMMAD HAMMAD WASEEM 7 Nesting of Loops The way if statements can be nested, similarly whiles and fors can also be nested. To understand how nested loops work, look at the program given below: /* Demonstration of nested loops */ main( ) { int r, c, sum ; for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */ { for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */ { sum = r + c ; printf ( "r = %d c = %d sum = %dn", r, c, sum ) ; } } } When you run this program you will get the following output: r = 1 c = 1 sum = 2 r = 1 c = 2 sum = 3 r = 2 c = 1 sum = 3 r = 2 c = 2 sum = 4 r = 3 c = 1 sum = 4 r = 3 c = 2 sum = 5 Here, for each value of r the inner loop is cycled through twice, with the variable c taking values from 1 to 2. The inner loop terminates when the value of c exceeds 2, and the outer loop terminates when the value of r exceeds 3. As you can see, the body of the outer for loop is indented, and the body of the inner for loop is further indented. These multiple indentations make the program easier to understand. Instead of using two statements, one to calculate sum and another to print it out, we can compact this into one single statement by saying: printf ( "r = %d c = %d sum = %dn", r, c, r + c ) ; The way for loops have been nested here, similarly, two while loops can also be nested. Not only this, a for loop can occur within a while loop, or a while within a for.