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

Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02Suhail Akraam
 
Program flowchart
Program flowchartProgram flowchart
Program flowchartSowri Rajan
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string libraryMomenMostafa
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C LanguageShaina Arora
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statementsMomenMostafa
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in CJeya Lakshmi
 
8 arrays and pointers
8  arrays and pointers8  arrays and pointers
8 arrays and pointersMomenMostafa
 
1 introducing c language
1  introducing c language1  introducing c language
1 introducing c languageMomenMostafa
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements Tarun Sharma
 
C Programming Language Part 9
C Programming Language Part 9C Programming Language Part 9
C Programming Language Part 9Rumman Ansari
 
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 Hemantha Kulathilake
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 

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

Lab test 2
Lab test 2Lab test 2
Lab test 2altwirqi
 
Chapter 1-hr-overview
Chapter 1-hr-overviewChapter 1-hr-overview
Chapter 1-hr-overviewaltwirqi
 
Presentation1
Presentation1Presentation1
Presentation1f721
 
Designing informationfinalwaugh
Designing informationfinalwaughDesigning informationfinalwaugh
Designing informationfinalwaughpatricktwaugh
 
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 algDe Zwerm Groep
 
Design portfolio waugh
Design portfolio waughDesign portfolio waugh
Design portfolio waughpatricktwaugh
 
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 2009altwirqi
 
Reesbook presentation
Reesbook presentationReesbook presentation
Reesbook presentationandresipm
 
50 common-english-phrasal-verbs
50 common-english-phrasal-verbs50 common-english-phrasal-verbs
50 common-english-phrasal-verbsaltwirqi
 
Trimetrix talenten ontwikkling
Trimetrix talenten ontwikklingTrimetrix talenten ontwikkling
Trimetrix talenten ontwikklingDe Zwerm Groep
 
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 gedragDe Zwerm Groep
 
Brandstorm Creative Group Portfolio
Brandstorm Creative Group PortfolioBrandstorm Creative Group Portfolio
Brandstorm Creative Group Portfolioandresipm
 

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

C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptxDEEPAK948083
 
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.pdfDrDineshenScientist
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languagetanmaymodi4
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languageTanmay Modi
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptxeaglesniper008
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
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 LoopPriyom Majumder
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
Loop control structure
Loop control structureLoop control structure
Loop control structureKaran Pandey
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Chapter 13.1.5
Chapter 13.1.5Chapter 13.1.5
Chapter 13.1.5patcha535
 

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

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
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 writingTeacherCyreneCayanan
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
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 ConsultingTechSoup
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
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 GraphThiyagu K
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
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
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 

Recently uploaded (20)

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
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
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
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
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).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
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
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
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
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
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 

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