SlideShare a Scribd company logo
Introducing to Loops
Goals
By the end of this unit, you should
  understand …
• … basic loop concepts, including pretest &
  posttest loops, loop initialization ,condition
  and increment.
• … how to program a while loop.
• … how to program a do-while loop.
• … how to program a for loops.
What is a loop?
• A loop is a programming structure that
  allows an action to repeat until the
  program meets a given condition.
• After each iteration of a loop, the loop
  checks against a loop control expression
  to see if the program met the given
  condition. If it did, the loop stops. If not,
  the loop moves on to the next iteration.
Types of Loops
• C supports two categories of loops,
  based on where the program tests the
  condition:
  – Pretest Loops
  – Post-test Loops
Pretest Loops
• With each iteration, the program tests the
  condition first before executing the loop’s
  block.
• If the condition results to true, the loop
  continues and executes the block; if the
  condition results to false, the loop
  terminates.
• With a pretest loop, there is a chance the
  loop may never execute once in the program.
Post-Test Loops
• With each iteration, the program
  executes the loop’s block first and tests
  against a condition.
• If the condition tests to true, the loop
  continues and executes another
  iteration; if the condition tests to false,
  the loop terminates.
• With a post-test loop, the loop will
  always execute at least once!
Pretest vs. Post-Test Loops




   from Figure 6-2 in Forouzan & Gilberg, p. 305
Variable Initialization
• int i=5;
• I have initialized the variable i with a value i=5;
Updating a Loop
• A loop update is what happens inside a
  loop’s block that eventually causes the
  loop to satisfy the condition, thus ending
  the loop.
• Updating happens during each loop
  iteration.
• Without a loop update, the loop would be
  an infinite loop.
Initialization & Updating
12 lec 12 loop
Loop Comparison




from Table 6-1 in Forouzan & Gilberg, p. 308
C Implementation of Loops
• Pretest Loops
  – while Loop
  – for Loop
• Post-test Loop
  – do … while loop
• All loops in C execute so long as a
  condition evaluates to true and terminate
  when the condition evaluates to false.
The while Loop




from Figure 6-11 in Forouzan & Gilberg, p. 311
Example of while loop
#include<stdio.h>
#include<conio.h>
                         If we input value
int main()
                         of end as 10 then
{                        output will be 1 to
int start, end;          10
scanf("%d",&end);
start = 0;
 while ( start < end)
{
start++;
printf("%dn", start);
 }
return 0;
Example
#include<stdio.h>             The output of the postfix and
                              prefix increment example will
int main()                    look like this:
 { int i;                      1
                               2
i = 0;                         3
                               4
while(i++ < 5)
                               5
{ printf("%dn", i);
}                              1
printf("n");                  2
                               3
 i = 0;                        4
while(++i < 5)
 { printf("%dn", i); }
return 0; }
The for Loop
• A for loop is a pretest loop that includes three
  expressions in its header:
   –   Loop initialization statement
   –   Limit test expression(condition)
   –   Loop update statement


• The for loop is often used as a start-controlled
  loop since we can accurately predict the
  maximum number of iterations.
The for Loop
Comparing while with for
Comparing while with for
i = 1;               sum = 0;
sum =0;              for (i = 1; i <= 20; i++)
while (i <= 20)      {
{                      scanf(“%d”, &a);
  scanf(“%d”, &a);     sum = sum+a;
  sum = sum+a;       }//end for
  i++
}//end while
 The while Loop            The for Loop
Example of for loop
main ( )
{
int p, n, count ;
float r, si ;
for ( count = 1 ; count <= 3 ; count = count + 1 )
{
printf ( "Enter values of p, n, and r " ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = (p * n * r) / 100 ;
printf ( "Simple Interest = Rs.%fn", si ) ;
}
}
Example
#include <stdio.h>
 #include<conio.h>
void main()
{
   int i = 0, j = 8;
   printf("Times 8 Tablen");
   for(i = 0; i <= 12; i = i + 1)
   {
    printf("%d x %d = %dn", i, j, j*i);
    }
    printf("n");
}
Nested for Loops
• We can nest any statement, even
  another for loop, inside the body of
  a parent for loop.
• When we nest a child for loop, it
  iterates all of it’s cycles for each
  iteration of the parent.
Example of nested for loop
• /* Demonstration of nested loops */
                                              When you run this
main( )                                       program you will get the
{                                             following output:
                                              r = 1 c = 1 sum = 2
int r, c, sum ;                               r = 1 c = 2 sum = 3
                                              r = 2 c = 1 sum = 3
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */ r = 2 c = 2 sum = 4
{                                             r = 3 c = 1 sum = 4
                                              r = 3 c = 2 sum = 5
for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */
{
sum = r + c ;
printf ( "r = %d c = %d sum = %dn", r, c, sum ) ;
}
}
}
The do … while Loop
• C implements a post-test loop using a
  structure called a do … while loop.
• In the do … while, the loop begins with
  the keyword do, followed by the body,
  followed by the keyword while and the
  loop expression.
• A semi-colon (;) follows the loop
  expression.
The do … while Loop
Example of do-while
/* Execution of a loop an unknown number of time*/
main( )
{
                                     Output:
char another ;                       Enter a number 5
int num ;                            square of 5 is 25
                                     Want to enter another number y/n y
do                                   Enter a number 7
                                     square of 7 is 49
{                                    Want to enter another number y/n n
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
} while ( another == 'y' ) ;}
Same using for loop
/* odd loop using a for loop */
main( )
{
char another = 'y' ;
int num ;
for ( ; another == 'y' ; )
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
Same using while loop
/* odd loop using a while loop */
main( )
{
char another = 'y' ;
int num ;
while ( another == 'y' )
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
}}
Comparing
do … while with while
The break Statement in Loops
• We often come across situations where we want
  to jump out of a loop instantly, without waiting to
  get back to the conditional test.
• The keyword break allows us to do this.
• When break is encountered inside any loop,
  control automatically passes to the first
  statement after the loop.
Example of break
• Write a program to determine whether a number is
  prime or not. A prime number is one, which is
  divisible only by 1 or itself.
• All we have to do to test whether a number is prime or
  not, is to divide it successively by all numbers from 2 to
  one less than itself.
• If remainder of any of these divisions is zero, the number
  is not a prime. If no division yields a zero then the
  number is a prime number.
Example
main( )
{int num, i ;
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
i=2;
while ( i <= num - 1 )
{if ( num % i == 0 )
{
printf ( "Not a prime number" ) ;
break ;
}
i++ ;
} if ( i == num )
printf ( "Prime number" ) ;
}
Example
                          main( )
The keyword break
  breaks the              {
  control only            int i = 1 , j = 1 ;
  from the while in       while ( i++ <= 100 )
  which it is placed.     {
                          while ( j++ <= 200 )
                          {
                          if ( j == 150 )
                          break ;
                          else
                          printf ( "%d %dn", i, j ) ;
                          }
                          }
                          }
The continue Statement
• In some programming situations we want to take
  the control to the beginning of the loop,
  bypassing the statements inside the loop,
   which have not yet been executed. The keyword
  continue allows us to do this.
• When continue is encountered inside any
  loop, control automatically passes to the
  beginning of the loop.
Example of continue statement
main( )
{
                                 The output of the
int i, j ;
                                 above program would
for ( i = 1 ; i <= 2 ; i++ )     be...
{                                12
for ( j = 1 ; j <= 2 ; j++ )     21
{
if ( i == j )
continue ;
printf ( "n%d %dn", i, j ) ;
}
}

More Related Content

PPT
Time complexity
PPTX
Asymptotic notations
PDF
Sql server windowing functions
PPTX
Tree traversal techniques
PPTX
Dfs presentation
PPTX
Daa:Dynamic Programing
PDF
[APJ] Common Table Expressions (CTEs) in SQL
 
PPT
context free language
Time complexity
Asymptotic notations
Sql server windowing functions
Tree traversal techniques
Dfs presentation
Daa:Dynamic Programing
[APJ] Common Table Expressions (CTEs) in SQL
 
context free language

What's hot (20)

PPT
Graph algorithm
PPTX
php user defined functions
PPT
Lecture 14 - Scope Rules
DOCX
DAA Lab File C Programs
PPTX
Isomorphic graph
PPT
Bellman Ford's Algorithm
PPT
1 - Introduction to Compilers.ppt
DOCX
Data Structure in C (Lab Programs)
PPT
Strongly Connected Components
PPT
DATA STRUCTURES
PPTX
Loops in C Programming
DOCX
Best,worst,average case .17581556 045
PPTX
Graph in data structure
PDF
PPTX
Quick sort
PPT
Greedy algorithms
PPTX
Euler graph
PPTX
QUEUE.pptx
PPT
Application of dfs
PDF
Problem solving
Graph algorithm
php user defined functions
Lecture 14 - Scope Rules
DAA Lab File C Programs
Isomorphic graph
Bellman Ford's Algorithm
1 - Introduction to Compilers.ppt
Data Structure in C (Lab Programs)
Strongly Connected Components
DATA STRUCTURES
Loops in C Programming
Best,worst,average case .17581556 045
Graph in data structure
Quick sort
Greedy algorithms
Euler graph
QUEUE.pptx
Application of dfs
Problem solving
Ad

Viewers also liked (8)

DOC
Cmp 104
PDF
Programming in c++
PPT
04 control structures 1
PPT
Control structures in C++ Programming Language
PPSX
Control Structures in Visual Basic
PDF
Control statements
PPTX
Loops c++
PPT
C++ programming
Cmp 104
Programming in c++
04 control structures 1
Control structures in C++ Programming Language
Control Structures in Visual Basic
Control statements
Loops c++
C++ programming
Ad

Similar to 12 lec 12 loop (20)

PPSX
C lecture 3 control statements slideshare
PPTX
Decision Making and Looping
PPT
Lecture 13 Loops1 with C++ programming.PPT
DOC
Slide07 repetitions
DOCX
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
PPTX
All type looping information and clearly
PPTX
Looping statements.pptx for basic in c language
PPTX
Looping statements c language basics ppt with example
PPT
Mesics lecture 7 iteration and repetitive executions
PPT
Chapter06.PPT
PDF
Cse115 lecture08repetitionstructures part02
PDF
Workbook_2_Problem_Solving_and_programming.pdf
PDF
04-Looping( For , while and do while looping) .pdf
PDF
Chapter 13.1.5
PDF
5 c control statements looping
PPSX
C lecture 4 nested loops and jumping statements slideshare
PDF
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
PDF
Unit II chapter 4 Loops in C
PDF
[ITP - Lecture 11] Loops in C/C++
C lecture 3 control statements slideshare
Decision Making and Looping
Lecture 13 Loops1 with C++ programming.PPT
Slide07 repetitions
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
All type looping information and clearly
Looping statements.pptx for basic in c language
Looping statements c language basics ppt with example
Mesics lecture 7 iteration and repetitive executions
Chapter06.PPT
Cse115 lecture08repetitionstructures part02
Workbook_2_Problem_Solving_and_programming.pdf
04-Looping( For , while and do while looping) .pdf
Chapter 13.1.5
5 c control statements looping
C lecture 4 nested loops and jumping statements slideshare
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Unit II chapter 4 Loops in C
[ITP - Lecture 11] Loops in C/C++

More from kapil078 (12)

PPTX
11 lec 11 storage class
PPT
Lec 10
DOC
Btech 1st yr midterm 1st
PPTX
Lec9
PPT
Cmp104 lec 7 algorithm and flowcharts
PPT
Cmp104 lec 6 computer lang
PPT
Cmp104 lec 2 number system
PPT
Cmp104 lec 6 computer lang
PPTX
Cmp104 lec 4 types of computer
PPT
Cmp104 lec 3 component of computer
PPT
Cmp104 lec 1
PPTX
cmp104 lec 8
11 lec 11 storage class
Lec 10
Btech 1st yr midterm 1st
Lec9
Cmp104 lec 7 algorithm and flowcharts
Cmp104 lec 6 computer lang
Cmp104 lec 2 number system
Cmp104 lec 6 computer lang
Cmp104 lec 4 types of computer
Cmp104 lec 3 component of computer
Cmp104 lec 1
cmp104 lec 8

Recently uploaded (20)

PPTX
GDM (1) (1).pptx small presentation for students
PDF
RMMM.pdf make it easy to upload and study
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Classroom Observation Tools for Teachers
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Complications of Minimal Access Surgery at WLH
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Institutional Correction lecture only . . .
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Lesson notes of climatology university.
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
GDM (1) (1).pptx small presentation for students
RMMM.pdf make it easy to upload and study
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Classroom Observation Tools for Teachers
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Supply Chain Operations Speaking Notes -ICLT Program
Module 4: Burden of Disease Tutorial Slides S2 2025
Complications of Minimal Access Surgery at WLH
STATICS OF THE RIGID BODIES Hibbelers.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Institutional Correction lecture only . . .
Final Presentation General Medicine 03-08-2024.pptx
Microbial diseases, their pathogenesis and prophylaxis
Microbial disease of the cardiovascular and lymphatic systems
Lesson notes of climatology university.
102 student loan defaulters named and shamed – Is someone you know on the list?
O5-L3 Freight Transport Ops (International) V1.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf

12 lec 12 loop

  • 2. Goals By the end of this unit, you should understand … • … basic loop concepts, including pretest & posttest loops, loop initialization ,condition and increment. • … how to program a while loop. • … how to program a do-while loop. • … how to program a for loops.
  • 3. What is a loop? • A loop is a programming structure that allows an action to repeat until the program meets a given condition. • After each iteration of a loop, the loop checks against a loop control expression to see if the program met the given condition. If it did, the loop stops. If not, the loop moves on to the next iteration.
  • 4. Types of Loops • C supports two categories of loops, based on where the program tests the condition: – Pretest Loops – Post-test Loops
  • 5. Pretest Loops • With each iteration, the program tests the condition first before executing the loop’s block. • If the condition results to true, the loop continues and executes the block; if the condition results to false, the loop terminates. • With a pretest loop, there is a chance the loop may never execute once in the program.
  • 6. Post-Test Loops • With each iteration, the program executes the loop’s block first and tests against a condition. • If the condition tests to true, the loop continues and executes another iteration; if the condition tests to false, the loop terminates. • With a post-test loop, the loop will always execute at least once!
  • 7. Pretest vs. Post-Test Loops from Figure 6-2 in Forouzan & Gilberg, p. 305
  • 8. Variable Initialization • int i=5; • I have initialized the variable i with a value i=5;
  • 9. Updating a Loop • A loop update is what happens inside a loop’s block that eventually causes the loop to satisfy the condition, thus ending the loop. • Updating happens during each loop iteration. • Without a loop update, the loop would be an infinite loop.
  • 12. Loop Comparison from Table 6-1 in Forouzan & Gilberg, p. 308
  • 13. C Implementation of Loops • Pretest Loops – while Loop – for Loop • Post-test Loop – do … while loop • All loops in C execute so long as a condition evaluates to true and terminate when the condition evaluates to false.
  • 14. The while Loop from Figure 6-11 in Forouzan & Gilberg, p. 311
  • 15. Example of while loop #include<stdio.h> #include<conio.h> If we input value int main() of end as 10 then { output will be 1 to int start, end; 10 scanf("%d",&end); start = 0; while ( start < end) { start++; printf("%dn", start); } return 0;
  • 16. Example #include<stdio.h> The output of the postfix and prefix increment example will int main() look like this: { int i; 1 2 i = 0; 3 4 while(i++ < 5) 5 { printf("%dn", i); } 1 printf("n"); 2 3 i = 0; 4 while(++i < 5) { printf("%dn", i); } return 0; }
  • 17. The for Loop • A for loop is a pretest loop that includes three expressions in its header: – Loop initialization statement – Limit test expression(condition) – Loop update statement • The for loop is often used as a start-controlled loop since we can accurately predict the maximum number of iterations.
  • 20. Comparing while with for i = 1; sum = 0; sum =0; for (i = 1; i <= 20; i++) while (i <= 20) { { scanf(“%d”, &a); scanf(“%d”, &a); sum = sum+a; sum = sum+a; }//end for i++ }//end while The while Loop The for Loop
  • 21. Example of for loop main ( ) { int p, n, count ; float r, si ; for ( count = 1 ; count <= 3 ; count = count + 1 ) { printf ( "Enter values of p, n, and r " ) ; scanf ( "%d %d %f", &p, &n, &r ) ; si = (p * n * r) / 100 ; printf ( "Simple Interest = Rs.%fn", si ) ; } }
  • 22. Example #include <stdio.h> #include<conio.h> void main() { int i = 0, j = 8; printf("Times 8 Tablen"); for(i = 0; i <= 12; i = i + 1) { printf("%d x %d = %dn", i, j, j*i); } printf("n"); }
  • 23. Nested for Loops • We can nest any statement, even another for loop, inside the body of a parent for loop. • When we nest a child for loop, it iterates all of it’s cycles for each iteration of the parent.
  • 24. Example of nested for loop • /* Demonstration of nested loops */ When you run this main( ) program you will get the { following output: r = 1 c = 1 sum = 2 int r, c, sum ; r = 1 c = 2 sum = 3 r = 2 c = 1 sum = 3 for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */ r = 2 c = 2 sum = 4 { r = 3 c = 1 sum = 4 r = 3 c = 2 sum = 5 for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */ { sum = r + c ; printf ( "r = %d c = %d sum = %dn", r, c, sum ) ; } } }
  • 25. The do … while Loop • C implements a post-test loop using a structure called a do … while loop. • In the do … while, the loop begins with the keyword do, followed by the body, followed by the keyword while and the loop expression. • A semi-colon (;) follows the loop expression.
  • 26. The do … while Loop
  • 27. Example of do-while /* Execution of a loop an unknown number of time*/ main( ) { Output: char another ; Enter a number 5 int num ; square of 5 is 25 Want to enter another number y/n y do Enter a number 7 square of 7 is 49 { Want to enter another number y/n n printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ; } while ( another == 'y' ) ;}
  • 28. Same using for loop /* odd loop using a for loop */ main( ) { char another = 'y' ; int num ; for ( ; another == 'y' ; ) { printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ;
  • 29. Same using while loop /* odd loop using a while loop */ main( ) { char another = 'y' ; int num ; while ( another == 'y' ) { printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ; }}
  • 31. The break Statement in Loops • We often come across situations where we want to jump out of a loop instantly, without waiting to get back to the conditional test. • The keyword break allows us to do this. • When break is encountered inside any loop, control automatically passes to the first statement after the loop.
  • 32. Example of break • Write a program to determine whether a number is prime or not. A prime number is one, which is divisible only by 1 or itself. • All we have to do to test whether a number is prime or not, is to divide it successively by all numbers from 2 to one less than itself. • If remainder of any of these divisions is zero, the number is not a prime. If no division yields a zero then the number is a prime number.
  • 33. Example main( ) {int num, i ; printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; i=2; while ( i <= num - 1 ) {if ( num % i == 0 ) { printf ( "Not a prime number" ) ; break ; } i++ ; } if ( i == num ) printf ( "Prime number" ) ; }
  • 34. Example main( ) The keyword break breaks the { control only int i = 1 , j = 1 ; from the while in while ( i++ <= 100 ) which it is placed. { while ( j++ <= 200 ) { if ( j == 150 ) break ; else printf ( "%d %dn", i, j ) ; } } }
  • 35. The continue Statement • In some programming situations we want to take the control to the beginning of the loop, bypassing the statements inside the loop, which have not yet been executed. The keyword continue allows us to do this. • When continue is encountered inside any loop, control automatically passes to the beginning of the loop.
  • 36. Example of continue statement main( ) { The output of the int i, j ; above program would for ( i = 1 ; i <= 2 ; i++ ) be... { 12 for ( j = 1 ; j <= 2 ; j++ ) 21 { if ( i == j ) continue ; printf ( "n%d %dn", i, j ) ; } }

Editor's Notes