Program looping - PowerPoint PPT Presentation

1 / 14
About This Presentation
Title:

Program looping

Description:

Program looping Why we need loop Make code concise for repetitive processes When to use loop Run a block of code repetitively Process multiple data using same procedure – PowerPoint PPT presentation

Number of Views:105
Avg rating:3.0/5.0
Slides: 15
Provided by: rzh8
Learn more at: https://www.cise.ufl.edu
Category:
Tags: loop | looping | program

less

Transcript and Presenter's Notes

Title: Program looping


1
Program looping
  • Why we need loop
  • Make code concise for repetitive processes
  • When to use loop
  • Run a block of code repetitively
  • Process multiple data using same procedure
  • How to use loop
  • for
  • while
  • do

2
for loop
  • Format
  • for( init_expression loop_condition
    loop_expression )
  • program statement
  • Flow

3
while loop
  • Format
  • while (loop_condition) program
    statement
  • Flow

4
for loop vs while loop
for loop
while loop
5
Convert for loop to while loop
  • while (loop_condition) program
    statement
  • for( init_expression loop_condition
    loop_expression )
  • program statement

init_expression while(loop_condition)
program statement loop_expression
6
Convert for to while Example
init_expression while(loop_condition) program
statement loop_expression
  • F 1
  • N 10
  • for(M1 MltN MM 1)
  • F F M

F 1 N 10 M 1 while(MltN)
F F M M M 1
7
do-while loop
  • Format
  • do      program statement while
    (loop_condition)

8
while and do-while loop
do      program statement while
(loop_condition)
while (loop_condition) program statement
  • In while loop, program statement may never be
    evaluated. While in do-while loop, it is
    evaluated at least once

9
Example
p 7
p 7
10
Example
p 1
p 6
11
break
  • Used to break out of a loop immediately
  • Possibly due to detection of an error

int i for(i0 i lt 3 i)
printf(here\n) break
printf(there\n)
here
12
continue
  • Used to continue at the next point
  • Possibly due to detection of an error

int i 0 for(i0 i lt 3 i)
printf(here\n) continue
printf(there\n)
here here here
13
Example summation of valid scores
  • count 0 n 10 sum 0
  • while (count lt n)
  • scanf("d", score)
  • if (score lt 0 score gt 100)
  • continue
  • count
  • sum sum score

14
Example summation of valid scores
  • count 0 n 10 sum 0
  • while (count lt n)
  • scanf("d", score)
  • if (score lt 0 score gt 100)
  • printf(Wrong data. Exiting program\n)
  • break
  • count
  • sum sum score
Write a Comment
User Comments (0)
About PowerShow.com