SlideShare a Scribd company logo
Loops in C Programming
Computer Programming
PREPARED BY
PRIYOM MAJUMDER
BACHELOR OF COMMERCE (HONS.), 6TH SEM
ITM UNIVERSITY, GWALIOR
priyom99anms@gmail.com
Loops in C Programming
1 | P a g e
LOOPS IN C PROGRAMMING
Loops
The versatility of computer lies in its ability to perform a set of instructions
repeatedly. This involves repeating some portion of the programs either a
specified number of times or until a particular condition is satisfied. This
repetitive operation is done through a loop control instructions. There are three
methods by way of which we can repeat a part of program. They are:
a. Using for statement
b. Using a while statement
c. Using a do-while statement
The - for loop:
The most popular looping is instructions. The for allows us to specify three
things about loop in a single line:
a. Setting a loop counter to an initial value.
b. Testing the loop counter to determine whether its value has reached the
number of repetitions desired.
c. 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.
Loops in C Programming
2 | P a g e
Let us now examine how the for statement gets executed:
 When the for statement is executed for first time, the value of count is
set to an initial value of 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 of count exceeds 3.
 If the value of count is still within the range 1 to 3, the statements
within the brace of for are executed again.
 The body of the for loop continuous to get executed till count doesn’t
exceed final value of 3.
 When count reaches the value 4 the control exits from 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.
Loops in C Programming
3 | P a g e
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+1, the statements of i++ and 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 loop and not in the for
statement. Note that in spite of this the semicolon after 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 statement,
but still the two semicolons are necessary.
main()
{
int i;
for(i=0; i++<10;)
printf(“%dn”, i);
}
Loops in C Programming
4 | P a g e
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.
The -while loop:
It is often the case in programming that you want to do something a fixed
numbers 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 condition)
{
do this;
and this;
increment loop counter;
}
Let us look at a simple example, which uses while loop.
Loops in C Programming
5 | P a g e
The above 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
loop. The parenthesis after the while contain a condition. So long as this
condition remains true all statements within the body of 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 to 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 statements that follows the body of while
loop. In place of the condition there can be any other valid expression. So
long as the expression evaluates to a non-zero values the statements
within the loop would get executed.
 The condition being tested may use relational or logical operators as
shown in the following examples:
o while(i<=10)
o while(i>=10 && j<=15)
o while(j>10 && (b<15||c<20)
 The statements within the loop may be 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 result 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);
}
Loops in C Programming
6 | P a g e
This is an indefinite loop, since i remain equal to 1 forever. The correct
would be as under:
main()
{
int i=1;
while(i<=10)
{
printf(“%dn”, i);
i++;
}
}
 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(“%dn”, i);
i--;
}
}
 It is not necessary that a loop counter must only be an int. It can 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;
}while(this condition is true);
Loops in C Programming
7 | P a g e
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. The difference is brought
about clearly by the following program.
main()
{
while(4<1)
printf(“n Hello There”);
}
Here, since the condition fails the first time itself, printf() will not get executed
at all. Let’s now write the same program using a do-while loop.
main()
{
do
{
printf(“Hello Theren”);
}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.
Nesting of loops:
The way if statements can be nested, similarly whiles and for’s can also be
nested. To understand how nested loops work; look at the program given in the
next page.
Loops in C Programming
8 | P a g e
When you run the program you get the following output:
Here, for each of i the inner loop is cycled through 4 times, with the variable j
taking values from 1 to 4. The inner loop terminates when the value of j
exceeds 4, and the outer loop terminates when the value of i 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 indentions 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 saying:
printf(“i=%d j=%d sum=%dn”, i, j, i+j);
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.

More Related Content

What's hot (20)

Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
Haitham El-Ghareeb
 
Python Programming language
Python Programming languagePython Programming language
Python Programming language
HadeelAlbedah
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program
Leela Koneru
 
Dining philosopher problem operating system
Dining philosopher problem operating system Dining philosopher problem operating system
Dining philosopher problem operating system
anushkashastri
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
Harjinder Singh
 
File Management in C
File Management in CFile Management in C
File Management in C
Paurav Shah
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
nitamhaske
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
Kevin Jadiya
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
AbhayDhupar
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
File Handling in Python
File Handling in PythonFile Handling in Python
File Handling in Python
International Institute of Information Technology (I²IT)
 
control statements in python.pptx
control statements in python.pptxcontrol statements in python.pptx
control statements in python.pptx
Anshu Varma
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
avikdhupar
 
System Software /Operating System Lab Report
System Software /Operating System Lab ReportSystem Software /Operating System Lab Report
System Software /Operating System Lab Report
Vishnu K N
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
Sowmya Jyothi
 
Input-Buffering
Input-BufferingInput-Buffering
Input-Buffering
Dattatray Gandhmal
 
Loops in c programming
Loops in c programmingLoops in c programming
Loops in c programming
CHANDAN KUMAR
 
Python Programming language
Python Programming languagePython Programming language
Python Programming language
HadeelAlbedah
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program
Leela Koneru
 
Dining philosopher problem operating system
Dining philosopher problem operating system Dining philosopher problem operating system
Dining philosopher problem operating system
anushkashastri
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
Harjinder Singh
 
File Management in C
File Management in CFile Management in C
File Management in C
Paurav Shah
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
nitamhaske
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
Kevin Jadiya
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
AbhayDhupar
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
control statements in python.pptx
control statements in python.pptxcontrol statements in python.pptx
control statements in python.pptx
Anshu Varma
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
avikdhupar
 
System Software /Operating System Lab Report
System Software /Operating System Lab ReportSystem Software /Operating System Lab Report
System Software /Operating System Lab Report
Vishnu K N
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
Sowmya Jyothi
 
Loops in c programming
Loops in c programmingLoops in c programming
Loops in c programming
CHANDAN KUMAR
 

Similar to Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop (20)

[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
tanmaymodi4
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
Tanmay Modi
 
Loops in c
Loops in cLoops in c
Loops in c
shubhampandav3
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
JayBhavsar68
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
Hattori Sidek
 
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
DrDineshenScientist
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Vikram Nandini
 
ICP - Lecture 9
ICP - Lecture 9ICP - Lecture 9
ICP - Lecture 9
hassaanciit
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
Amrit Kaur
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
altwirqi
 
Looping statements
Looping statementsLooping statements
Looping statements
Chukka Nikhil Chakravarthy
 
CS305PC_C++_UNIT 2.pdf jntuh third semester
CS305PC_C++_UNIT 2.pdf jntuh third semesterCS305PC_C++_UNIT 2.pdf jntuh third semester
CS305PC_C++_UNIT 2.pdf jntuh third semester
VeeraswamyDasari2
 
Controls & Loops in C
Controls & Loops in C Controls & Loops in C
Controls & Loops in C
Thesis Scientist Private Limited
 
Ch05
Ch05Ch05
Ch05
Arriz San Juan
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
sana shaikh
 
Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
loops and iteration.docx
loops and iteration.docxloops and iteration.docx
loops and iteration.docx
JavvajiVenkat
 
Managing input and output operations & Decision making and branching and looping
Managing input and output operations & Decision making and branching and loopingManaging input and output operations & Decision making and branching and looping
Managing input and output operations & Decision making and branching and looping
letheyabala
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
tanmaymodi4
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
Tanmay Modi
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
JayBhavsar68
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
Hattori Sidek
 
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
DrDineshenScientist
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Vikram Nandini
 
ICP - Lecture 9
ICP - Lecture 9ICP - Lecture 9
ICP - Lecture 9
hassaanciit
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
Amrit Kaur
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
altwirqi
 
CS305PC_C++_UNIT 2.pdf jntuh third semester
CS305PC_C++_UNIT 2.pdf jntuh third semesterCS305PC_C++_UNIT 2.pdf jntuh third semester
CS305PC_C++_UNIT 2.pdf jntuh third semester
VeeraswamyDasari2
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
sana shaikh
 
loops and iteration.docx
loops and iteration.docxloops and iteration.docx
loops and iteration.docx
JavvajiVenkat
 
Managing input and output operations & Decision making and branching and looping
Managing input and output operations & Decision making and branching and loopingManaging input and output operations & Decision making and branching and looping
Managing input and output operations & Decision making and branching and looping
letheyabala
 
Ad

More from Priyom Majumder (8)

Auditing
AuditingAuditing
Auditing
Priyom Majumder
 
Ecommerce
EcommerceEcommerce
Ecommerce
Priyom Majumder
 
THOSE WHO FALL IN LOVE - SAMPLE
THOSE WHO FALL IN LOVE - SAMPLETHOSE WHO FALL IN LOVE - SAMPLE
THOSE WHO FALL IN LOVE - SAMPLE
Priyom Majumder
 
CSR of Amul
CSR of AmulCSR of Amul
CSR of Amul
Priyom Majumder
 
Marine insurance
Marine insuranceMarine insurance
Marine insurance
Priyom Majumder
 
Form of retail outlet
Form of retail outletForm of retail outlet
Form of retail outlet
Priyom Majumder
 
Comparison of cash flow of idea and airtel
Comparison of cash flow of idea and airtelComparison of cash flow of idea and airtel
Comparison of cash flow of idea and airtel
Priyom Majumder
 
Effect of demonization on retailers
Effect of demonization on retailersEffect of demonization on retailers
Effect of demonization on retailers
Priyom Majumder
 
THOSE WHO FALL IN LOVE - SAMPLE
THOSE WHO FALL IN LOVE - SAMPLETHOSE WHO FALL IN LOVE - SAMPLE
THOSE WHO FALL IN LOVE - SAMPLE
Priyom Majumder
 
Form of retail outlet
Form of retail outletForm of retail outlet
Form of retail outlet
Priyom Majumder
 
Comparison of cash flow of idea and airtel
Comparison of cash flow of idea and airtelComparison of cash flow of idea and airtel
Comparison of cash flow of idea and airtel
Priyom Majumder
 
Effect of demonization on retailers
Effect of demonization on retailersEffect of demonization on retailers
Effect of demonization on retailers
Priyom Majumder
 
Ad

Recently uploaded (20)

GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdfGEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke WarnerPublishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptxBINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 EmployeesOverview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil DisobediencePaper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdfGEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke WarnerPublishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptxBINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 EmployeesOverview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil DisobediencePaper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 

Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop

  • 1. Loops in C Programming Computer Programming PREPARED BY PRIYOM MAJUMDER BACHELOR OF COMMERCE (HONS.), 6TH SEM ITM UNIVERSITY, GWALIOR [email protected]
  • 2. Loops in C Programming 1 | P a g e LOOPS IN C PROGRAMMING Loops The versatility of computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the programs either a specified number of times or until a particular condition is satisfied. This repetitive operation is done through a loop control instructions. There are three methods by way of which we can repeat a part of program. They are: a. Using for statement b. Using a while statement c. Using a do-while statement The - for loop: The most popular looping is instructions. The for allows us to specify three things about loop in a single line: a. Setting a loop counter to an initial value. b. Testing the loop counter to determine whether its value has reached the number of repetitions desired. c. 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.
  • 3. Loops in C Programming 2 | P a g e Let us now examine how the for statement gets executed:  When the for statement is executed for first time, the value of count is set to an initial value of 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 of count exceeds 3.  If the value of count is still within the range 1 to 3, the statements within the brace of for are executed again.  The body of the for loop continuous to get executed till count doesn’t exceed final value of 3.  When count reaches the value 4 the control exits from 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.
  • 4. Loops in C Programming 3 | P a g e 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+1, the statements of i++ and 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 loop and not in the for statement. Note that in spite of this the semicolon after 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 statement, but still the two semicolons are necessary. main() { int i; for(i=0; i++<10;) printf(“%dn”, i); }
  • 5. Loops in C Programming 4 | P a g e 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. The -while loop: It is often the case in programming that you want to do something a fixed numbers 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 condition) { do this; and this; increment loop counter; } Let us look at a simple example, which uses while loop.
  • 6. Loops in C Programming 5 | P a g e The above 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 loop. The parenthesis after the while contain a condition. So long as this condition remains true all statements within the body of 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 to 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 statements that follows the body of while loop. In place of the condition there can be any other valid expression. So long as the expression evaluates to a non-zero values the statements within the loop would get executed.  The condition being tested may use relational or logical operators as shown in the following examples: o while(i<=10) o while(i>=10 && j<=15) o while(j>10 && (b<15||c<20)  The statements within the loop may be 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 result 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); }
  • 7. Loops in C Programming 6 | P a g e This is an indefinite loop, since i remain equal to 1 forever. The correct would be as under: main() { int i=1; while(i<=10) { printf(“%dn”, i); i++; } }  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(“%dn”, i); i--; } }  It is not necessary that a loop counter must only be an int. It can 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; }while(this condition is true);
  • 8. Loops in C Programming 7 | P a g e 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. The difference is brought about clearly by the following program. main() { while(4<1) printf(“n Hello There”); } Here, since the condition fails the first time itself, printf() will not get executed at all. Let’s now write the same program using a do-while loop. main() { do { printf(“Hello Theren”); }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. Nesting of loops: The way if statements can be nested, similarly whiles and for’s can also be nested. To understand how nested loops work; look at the program given in the next page.
  • 9. Loops in C Programming 8 | P a g e When you run the program you get the following output: Here, for each of i the inner loop is cycled through 4 times, with the variable j taking values from 1 to 4. The inner loop terminates when the value of j exceeds 4, and the outer loop terminates when the value of i 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 indentions 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 saying: printf(“i=%d j=%d sum=%dn”, i, j, i+j); 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.