SlideShare a Scribd company logo
1 of 11
ICS 103: Computer Programming in C
Handout-7 Topic: Control Structures (Repetition & Loop
Statements)
Objective:
• To know use of increment operator ++, and decrement operator --
• To know syntax of while, do-while, for statements (loops).
• To know working of above loops with examples.
Use of increment operator ++, and decrement operator -
- :
i++ means i=i+1;
i -- means i=i-1;
(For above statements in first step initial value of i will be assigned and
after that value of i will be incremented or decremented).
++i means i=i+1 ;
-- i means i=i-1 ; (But in these, in first step initial value of i will be
incremented or decremented and then value of i will be assigned ).
Examples:
#include<stdio.h>
main()
{
int i=2, r1 ;
r1=i++;
printf("Value of r1 is : %d", r1);
}
Sample Output:
Page 1 of 11
#include<stdio.h>
void main()
{
int i=2, r1 ;
r1 = ++i;
printf("Value of r1 is : %d", r1);
}
Looping Structures:
While statement:
Syntax: while (expression)
statement
A conditional loop is one whose continued execution depends on the value of
a logical expression. In the above syntax as long as the expression is true
the statement (or statements if enclosed within braces) is executed. When
the expression evaluates to false the execution of the statement(s) stops
and program continues with the other following statements.
Example:
Let number be an integer variable.
while (number > 100)
{
printf (“Enter a numbern”) ;
scanf (“%d”, &number) ;
}
Page 2 of 11
In the above example, as long as the entered value of number is greater than
100 the loop continues to ask to enter a value for number. Once a number
less than or equal to 100 is entered it stops asking. If in the beginning itself
the value of number is less than or equal to 100, then the loop is not at all
executed.
Note: In the while loop the expression is tested before the loop body
statements are entered. So, if the expression is false in the beginning the
loop body is never entered.
do…while statement :
Syntax: do
statement
while (expression) ;
Here, the expression is tested after the statement(s) are executed. So,
even if the expression is false in the beginning the loop body is entered at
least once. Here also like the while statement, as long as the expression is
true the statement (or statements if enclosed within braces) is executed.
When the expression evaluates to false the execution of the statement(s)
stops and program continues with the other following statements.
Example:
The example of while loop can be written with do…while loop as :
do
{
printf (“Enter a numbern”) ;
scanf (“%d”, &number) ;
} while (number > 100) ;
In the above example, as long as the entered value of number is greater than
100 the loop continues to ask to enter a value for number. Once a number
less than or equal to 100 is entered it stops asking.
Page 3 of 11
Note: In the conditional looping using while and do…while the number of
times the loop will be executed is not known at the start of the program.
for statement :
Syntax: for (expression 1; expression 2; expression 3)
Statement
In the iterative looping using for loop the number of times the loop will be
executed is known at the start of the program. In the above syntax, the
expression 1 is the initialization statement which assigns an initial value to
the loop variable. The expression 2 is the testing expression where the loop
variable value is checked. If it is true the loop body statement(s) are
executed and if it is false the statements(s) are not executed. The
expression 3 is usually an increment or decrement expression where the
value of the loop variable is incremented or decremented.
Example:
for (count = 0 ; count < 10 ; count++)
{
printf (“Enter a valuen”) ;
scanf (“%d”, &num) ;
num = num + 10 ;
printf (“NUM = %dn”, num) ;
}
In the above example the integer variable count is first assigned a value of
0, it is initialized. Then the value of count is checked if it is less than 10. If
it is < 10 the loop body asks to enter a value for num. Then the value of
count is incremented by 1 and again count is checked for less than 10. If it
is true the loop body is again executed and then the count is incremented by
1 and checked for < 10. It keeps on doing like this until the count is >= 10.
Then the loop stops. So, here the loop is executed 10 times.
Note: The increment operation is written as ++ and decrement operation is
written as --. The increment increases the value by 1 and decrement
decreases the value by 1.
Page 4 of 11
Useful Solved Examples using different loops:
Example 1:
Print numbers ranging from 1 to n with their squares using for loop. The
value of n is read by the program.
#include<stdio.h>
void main()
{
int num,square,limit;
printf("Please Input value of limit : ");
scanf("%d", &limit);
for (num=1; num < =limit; ++num)
{
square = num*num;
printf("%5d %5dn", num, square);
} // end of for
} // end of main
Example 2. :
/**********************************************************
Program Showing a Sentinel-Controlled for loop.
Page 5 of 11
To Compute the sum of a list of exam scores and their aerage.
***********************************************************/
#include <stdio.h>
#define SENTINEL -99
int main(void)
{
int sum = 0, /* sum of scores input so far */
score, /* current score */
count=0; /* to count the scores */
double average;
printf("Enter first score (or %d to quit)> ", SENTINEL);
for(scanf("%d", &score); score != SENTINEL; scanf("%d", &score))
{
sum += score;
count++;
printf("Enter next score (%d to quit)> ", SENTINEL);
} // end of for loop
if(count>0) {
average=sum/count;
printf("nSum of exam scores is %dn", sum);
printf(“the average of exam scores is %f”,average);
}else
printf(“no scores entered”);
return (0);
} // end of main
Page 6 of 11
Example 3 :
while loop :
/*Conditional loop Using while Statement */
#include<stdio.h>
#define RIGHT_SIZE 10
void main()
{
int diameter;
printf("Please Input Balloon's diameter > ");
scanf("%d",&diameter);
while(diameter < RIGHT_SIZE)
{
printf("Keep blowing ! n");
printf("Please Input new Balloon's diameter > ");
scanf("%d", &diameter);
} // end of while loop
printf("Stop blowing ! n");
} // end of main
Page 7 of 11
Example 4. :
do-while loop :
/* do-while loop */
#include<stdio.h>
void main()
{
int num;
do
{
printf("Please Input a number < 1 or >= 10 > ");
scanf("%d",&num);
} // end of do loop
while (num < 1 || num >=10) ;
printf("Dear , Sorry ! Your number is out of specified range in program");
} // end of main
Sample Output :
Page 8 of 11
Example 5 :
Use of Increment and Decrement operators:
/* Explanation on Increment, Decrement operators */
#include<stdio.h>
void main()
{
int n, m, p, i = 3, j = 9;
n = ++i * --j;
printf("After the statement n = ++i * --j, n=%d i=%d j=%dn", n, i, j);
m = i + j--;
printf("After the statement m = i + j--, m=%d i=%d j=%dn",m ,i ,j);
p = i + j;
printf("After the statement p = i + j, p=%d i=%d j=%dn", p, i, j);
} // end of main
Sample Output:
Page 9 of 11
Example 6
What is the output of the following program
#include <stdio.h>
int main(void) {
int number, digits,sum;
digits=sum=0;
number=345;
do {
sum+=number%10;
number=number/10;
digits++;
printf("%d*%dn",digits,sum);
}while(number>0);
return 0;
}
Example 7: Nested Loops
What is the output of the following program
#include<stdio.h>
void main(){
int i,j;
for (i=2; i<=7; i+=3) {
for (j=0;j <=i;j=j+3 )
printf("*");
printf("n");
}
printf("i=%dnj=%d",i,j);
}
Example 8:
Page 10 of 11
What is the output of the following program
#include<stdio.h>
main( )
{
int j, x=0;
for (j=-2;j<=5;j=j+2) {
switch(j-1)
{
case 0 :
case -1 :
x += 1;
break;
case 1:
case 2:
case 3:
x += 2;
break;
default:
x += 3;
}
printf("x = %dn", x);
}
}
Page 11 of 11

More Related Content

What's hot

Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
Jeya Lakshmi
 

What's hot (20)

Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 
7 functions
7  functions7  functions
7 functions
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
 
8 arrays and pointers
8  arrays and pointers8  arrays and pointers
8 arrays and pointers
 
For Loop
For LoopFor Loop
For Loop
 
1 introducing c language
1  introducing c language1  introducing c language
1 introducing c language
 
C if else
C if elseC if else
C if else
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
Ch3 selection
Ch3 selectionCh3 selection
Ch3 selection
 
C Programming Language Part 9
C Programming Language Part 9C Programming Language Part 9
C Programming Language Part 9
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 
C++ control loops
C++ control loopsC++ control loops
C++ control loops
 
CONDITIONAL STATEMENT IN C LANGUAGE
CONDITIONAL STATEMENT IN C LANGUAGECONDITIONAL STATEMENT IN C LANGUAGE
CONDITIONAL STATEMENT IN C LANGUAGE
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 

Viewers also liked

Chapter 1-hr-overview
Chapter 1-hr-overviewChapter 1-hr-overview
Chapter 1-hr-overview
altwirqi
 
Presentation1
Presentation1Presentation1
Presentation1
f721
 
Designing informationfinalwaugh
Designing informationfinalwaughDesigning informationfinalwaugh
Designing informationfinalwaugh
patricktwaugh
 
persoonlijke effectiviteit in de installatie branche alg
persoonlijke effectiviteit in de installatie branche algpersoonlijke effectiviteit in de installatie branche alg
persoonlijke effectiviteit in de installatie branche alg
De Zwerm Groep
 
Design portfolio waugh
Design portfolio waughDesign portfolio waugh
Design portfolio waugh
patricktwaugh
 
01 intro erp using gbi 1.0, stefan weidner, nov 2009
01 intro erp using gbi 1.0, stefan weidner, nov 200901 intro erp using gbi 1.0, stefan weidner, nov 2009
01 intro erp using gbi 1.0, stefan weidner, nov 2009
altwirqi
 
Reesbook presentation
Reesbook presentationReesbook presentation
Reesbook presentation
andresipm
 
50 common-english-phrasal-verbs
50 common-english-phrasal-verbs50 common-english-phrasal-verbs
50 common-english-phrasal-verbs
altwirqi
 
Brandstorm Creative Group Portfolio
Brandstorm Creative Group PortfolioBrandstorm Creative Group Portfolio
Brandstorm Creative Group Portfolio
andresipm
 

Viewers also liked (19)

Lab test 2
Lab test 2Lab test 2
Lab test 2
 
Chapter 1-hr-overview
Chapter 1-hr-overviewChapter 1-hr-overview
Chapter 1-hr-overview
 
Presentation1
Presentation1Presentation1
Presentation1
 
Designing informationfinalwaugh
Designing informationfinalwaughDesigning informationfinalwaugh
Designing informationfinalwaugh
 
Normal
NormalNormal
Normal
 
persoonlijke effectiviteit in de installatie branche alg
persoonlijke effectiviteit in de installatie branche algpersoonlijke effectiviteit in de installatie branche alg
persoonlijke effectiviteit in de installatie branche alg
 
0104testr
0104testr0104testr
0104testr
 
Design portfolio waugh
Design portfolio waughDesign portfolio waugh
Design portfolio waugh
 
Coachi online coachen
Coachi online coachenCoachi online coachen
Coachi online coachen
 
Methode GoldenBox
Methode GoldenBoxMethode GoldenBox
Methode GoldenBox
 
01 intro erp using gbi 1.0, stefan weidner, nov 2009
01 intro erp using gbi 1.0, stefan weidner, nov 200901 intro erp using gbi 1.0, stefan weidner, nov 2009
01 intro erp using gbi 1.0, stefan weidner, nov 2009
 
Reesbook presentation
Reesbook presentationReesbook presentation
Reesbook presentation
 
Exam1 011
Exam1 011Exam1 011
Exam1 011
 
50 common-english-phrasal-verbs
50 common-english-phrasal-verbs50 common-english-phrasal-verbs
50 common-english-phrasal-verbs
 
Trimetrix talenten ontwikkling
Trimetrix talenten ontwikklingTrimetrix talenten ontwikkling
Trimetrix talenten ontwikkling
 
CS Unit Project
CS Unit ProjectCS Unit Project
CS Unit Project
 
Design info work
Design info workDesign info work
Design info work
 
Persoonlijke effectiviteit met een focus op houding en gedrag
Persoonlijke effectiviteit met een focus op houding en gedragPersoonlijke effectiviteit met een focus op houding en gedrag
Persoonlijke effectiviteit met een focus op houding en gedrag
 
Brandstorm Creative Group Portfolio
Brandstorm Creative Group PortfolioBrandstorm Creative Group Portfolio
Brandstorm Creative Group Portfolio
 

Similar to Slide07 repetitions

Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
Vince Vo
 
Chapter 13.1.5
Chapter 13.1.5Chapter 13.1.5
Chapter 13.1.5
patcha535
 

Similar to Slide07 repetitions (20)

C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptx
 
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
 
Loops in c
Loops in cLoops in c
Loops in c
 
[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++
 
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
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
ICP - Lecture 9
ICP - Lecture 9ICP - Lecture 9
ICP - Lecture 9
 
Looping
LoopingLooping
Looping
 
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
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Loop control structure
Loop control structureLoop control structure
Loop control structure
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Chapter 13.1.5
Chapter 13.1.5Chapter 13.1.5
Chapter 13.1.5
 

Recently uploaded

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 

Recently uploaded (20)

INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.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
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 

Slide07 repetitions

  • 1. ICS 103: Computer Programming in C Handout-7 Topic: Control Structures (Repetition & Loop Statements) Objective: • To know use of increment operator ++, and decrement operator -- • To know syntax of while, do-while, for statements (loops). • To know working of above loops with examples. Use of increment operator ++, and decrement operator - - : i++ means i=i+1; i -- means i=i-1; (For above statements in first step initial value of i will be assigned and after that value of i will be incremented or decremented). ++i means i=i+1 ; -- i means i=i-1 ; (But in these, in first step initial value of i will be incremented or decremented and then value of i will be assigned ). Examples: #include<stdio.h> main() { int i=2, r1 ; r1=i++; printf("Value of r1 is : %d", r1); } Sample Output: Page 1 of 11
  • 2. #include<stdio.h> void main() { int i=2, r1 ; r1 = ++i; printf("Value of r1 is : %d", r1); } Looping Structures: While statement: Syntax: while (expression) statement A conditional loop is one whose continued execution depends on the value of a logical expression. In the above syntax as long as the expression is true the statement (or statements if enclosed within braces) is executed. When the expression evaluates to false the execution of the statement(s) stops and program continues with the other following statements. Example: Let number be an integer variable. while (number > 100) { printf (“Enter a numbern”) ; scanf (“%d”, &number) ; } Page 2 of 11
  • 3. In the above example, as long as the entered value of number is greater than 100 the loop continues to ask to enter a value for number. Once a number less than or equal to 100 is entered it stops asking. If in the beginning itself the value of number is less than or equal to 100, then the loop is not at all executed. Note: In the while loop the expression is tested before the loop body statements are entered. So, if the expression is false in the beginning the loop body is never entered. do…while statement : Syntax: do statement while (expression) ; Here, the expression is tested after the statement(s) are executed. So, even if the expression is false in the beginning the loop body is entered at least once. Here also like the while statement, as long as the expression is true the statement (or statements if enclosed within braces) is executed. When the expression evaluates to false the execution of the statement(s) stops and program continues with the other following statements. Example: The example of while loop can be written with do…while loop as : do { printf (“Enter a numbern”) ; scanf (“%d”, &number) ; } while (number > 100) ; In the above example, as long as the entered value of number is greater than 100 the loop continues to ask to enter a value for number. Once a number less than or equal to 100 is entered it stops asking. Page 3 of 11
  • 4. Note: In the conditional looping using while and do…while the number of times the loop will be executed is not known at the start of the program. for statement : Syntax: for (expression 1; expression 2; expression 3) Statement In the iterative looping using for loop the number of times the loop will be executed is known at the start of the program. In the above syntax, the expression 1 is the initialization statement which assigns an initial value to the loop variable. The expression 2 is the testing expression where the loop variable value is checked. If it is true the loop body statement(s) are executed and if it is false the statements(s) are not executed. The expression 3 is usually an increment or decrement expression where the value of the loop variable is incremented or decremented. Example: for (count = 0 ; count < 10 ; count++) { printf (“Enter a valuen”) ; scanf (“%d”, &num) ; num = num + 10 ; printf (“NUM = %dn”, num) ; } In the above example the integer variable count is first assigned a value of 0, it is initialized. Then the value of count is checked if it is less than 10. If it is < 10 the loop body asks to enter a value for num. Then the value of count is incremented by 1 and again count is checked for less than 10. If it is true the loop body is again executed and then the count is incremented by 1 and checked for < 10. It keeps on doing like this until the count is >= 10. Then the loop stops. So, here the loop is executed 10 times. Note: The increment operation is written as ++ and decrement operation is written as --. The increment increases the value by 1 and decrement decreases the value by 1. Page 4 of 11
  • 5. Useful Solved Examples using different loops: Example 1: Print numbers ranging from 1 to n with their squares using for loop. The value of n is read by the program. #include<stdio.h> void main() { int num,square,limit; printf("Please Input value of limit : "); scanf("%d", &limit); for (num=1; num < =limit; ++num) { square = num*num; printf("%5d %5dn", num, square); } // end of for } // end of main Example 2. : /********************************************************** Program Showing a Sentinel-Controlled for loop. Page 5 of 11
  • 6. To Compute the sum of a list of exam scores and their aerage. ***********************************************************/ #include <stdio.h> #define SENTINEL -99 int main(void) { int sum = 0, /* sum of scores input so far */ score, /* current score */ count=0; /* to count the scores */ double average; printf("Enter first score (or %d to quit)> ", SENTINEL); for(scanf("%d", &score); score != SENTINEL; scanf("%d", &score)) { sum += score; count++; printf("Enter next score (%d to quit)> ", SENTINEL); } // end of for loop if(count>0) { average=sum/count; printf("nSum of exam scores is %dn", sum); printf(“the average of exam scores is %f”,average); }else printf(“no scores entered”); return (0); } // end of main Page 6 of 11
  • 7. Example 3 : while loop : /*Conditional loop Using while Statement */ #include<stdio.h> #define RIGHT_SIZE 10 void main() { int diameter; printf("Please Input Balloon's diameter > "); scanf("%d",&diameter); while(diameter < RIGHT_SIZE) { printf("Keep blowing ! n"); printf("Please Input new Balloon's diameter > "); scanf("%d", &diameter); } // end of while loop printf("Stop blowing ! n"); } // end of main Page 7 of 11
  • 8. Example 4. : do-while loop : /* do-while loop */ #include<stdio.h> void main() { int num; do { printf("Please Input a number < 1 or >= 10 > "); scanf("%d",&num); } // end of do loop while (num < 1 || num >=10) ; printf("Dear , Sorry ! Your number is out of specified range in program"); } // end of main Sample Output : Page 8 of 11
  • 9. Example 5 : Use of Increment and Decrement operators: /* Explanation on Increment, Decrement operators */ #include<stdio.h> void main() { int n, m, p, i = 3, j = 9; n = ++i * --j; printf("After the statement n = ++i * --j, n=%d i=%d j=%dn", n, i, j); m = i + j--; printf("After the statement m = i + j--, m=%d i=%d j=%dn",m ,i ,j); p = i + j; printf("After the statement p = i + j, p=%d i=%d j=%dn", p, i, j); } // end of main Sample Output: Page 9 of 11
  • 10. Example 6 What is the output of the following program #include <stdio.h> int main(void) { int number, digits,sum; digits=sum=0; number=345; do { sum+=number%10; number=number/10; digits++; printf("%d*%dn",digits,sum); }while(number>0); return 0; } Example 7: Nested Loops What is the output of the following program #include<stdio.h> void main(){ int i,j; for (i=2; i<=7; i+=3) { for (j=0;j <=i;j=j+3 ) printf("*"); printf("n"); } printf("i=%dnj=%d",i,j); } Example 8: Page 10 of 11
  • 11. What is the output of the following program #include<stdio.h> main( ) { int j, x=0; for (j=-2;j<=5;j=j+2) { switch(j-1) { case 0 : case -1 : x += 1; break; case 1: case 2: case 3: x += 2; break; default: x += 3; } printf("x = %dn", x); } } Page 11 of 11