Infinite for Loop - PowerPoint PPT Presentation

1 / 8
About This Presentation
Title:

Infinite for Loop

Description:

... for(;;) { cout – PowerPoint PPT presentation

Number of Views:12
Avg rating:3.0/5.0
Slides: 9
Provided by: DrKamalS8
Learn more at: https://www.kean.edu
Category:
Tags: infinite | loop

less

Transcript and Presenter's Notes

Title: Infinite for Loop


1
Infinite for Loop
  • If you omit the test condition, the value is
    assumed to be TRUE so the loop will continue
    indefinitely unless you provide some other means
    of exiting.

2
Example 18
  • includeltiostream.hgt
  • int main()
  • double value 0.0
  • double sum 0.0
  • int i 0
  • char indicator 'n'
  • for()
  • cout ltltendl
  • ltlt"Enter a value"
  • cingtgtvalue
  • i
  • sum value
  • cout ltltendl
  • ltlt"Do you want to enter another value (enter n
    to end)?"
  • cingtgtindicator
  • if ((indicator 'n') (indicator 'N'))
  • break

3
Continue Statement
  • Executing continue within a loop starts the next
    loop iteration immediately, skipping over any
    statements remaining in the current iteration.

4
Example19
  • includeltiostream.hgt
  • int main()
  • int i0, value0,product1
  • for (i1 ilt10 i)
  • cout ltlt"Enter value " ltlti ltltendl
  • cout ltlt"\t\t" ltlti ltlt" number is "
  • cingtgtvalue
  • if (value 0)
  • continue
  • product value
  • cout ltltendl
  • cout ltlt"Product (ignoring zero)" ltltproduct
    ltltendl
  • ltltendl
  • return 0

5
The while Loop
  • A while loop causes the program to repeat a
    sequence of statements as long as the starting
    condition remains true.
  • The general form of the while loop is
  • while (condition)
  • statement

6
Example 20
  • includeltiostream.hgt
  • int main()
  • double value 0.0, sum0.0
  • int i0
  • char indicator 'y'
  • while (indicator 'y')
  • cout ltlt endl ltlt"Enter a value"
  • cin gtgt value
  • i
  • sum value
  • cout ltltendl ltlt"Do you want to enter another
    value (enter y for yes or n to end)?"
  • cin gtgt indicator
  • cout ltltendl ltlt"The average of the " ltlt i
  • ltlt " value you entered is " ltltsum/i ltlt"."
    ltltendl
  • return 0

7
Exercise
  • Write a program that asks the user to enter a two
    digit grade (such as 80 or 75) and then display
    the corresponding single digit grade (such as 2
    or 3). Use the following grade ranges
  • 90 - 100 4 60 - 69 1
  • 80 - 89 3 59 and less 0
  • 70 - 79 2

8
Exercise
  • Write a program which reads number from cin, and
    adds them, stopping when 0 has been entered.
    Construct two versions of this program, using for
    and while loop.
Write a Comment
User Comments (0)
About PowerShow.com