The for Loop - PowerPoint PPT Presentation

About This Presentation
Title:

The for Loop

Description:

The for Loop Syntax: for (expression1;condition; expression2) statement; for (expression1;condition; expression2) {statement; statement;} Same as: expression1; – PowerPoint PPT presentation

Number of Views:21
Avg rating:3.0/5.0
Slides: 11
Provided by: Jon1158
Learn more at: http://www.cs.iit.edu
Category:

less

Transcript and Presenter's Notes

Title: The for Loop


1
The for Loop
  • Syntax
  • for (expression1condition expression2)
  • statement
  • for (expression1condition expression2)
  • statement
  • statement
  • Same as
  • expression1
  • while (condition)
  • statement
  • expression2

2
Example for Loop
  • int numEmployees,curNum
  • System.out.print(Enter Number of Employees )
  • numEmployees scan.nextInt()
  • if (numEmployees gt 0)
  • for (curNum 0 curNum lt numEmployeescurNum)
  • System.out.println( Welcome to CorpLand! )

3
Looping for Input
  • char letterEntered A
  • String stringE
  • while (letterEntered ! Z)
  • System.out.print(Enter a letter )
  • stringE scan.next()
  • letterEntered stringE.charAt(0)

4
Looping until Flag
  • boolean noMoreData()
  • boolean done false
  • while (!done)
  • // do a bunch of stuff
  • if (noMoreData() true)
  • done true
  • System.out.println( Were all through thank
    you!)

5
Nested Loops
  • int i , j
  • for (i0 i lt 10 i)
  • for (j0 j lt 10 j)
  • System.out.print(i)
  • System.out.print(j)
  • System.out.print( )
  • System.out.println()

6
The do-while Loop
  • Syntax
  • do
  • statement
  • while (condition)
  • do
  • statement
  • statement
  • while (condition)

7
do-while Example
  • char letterEntered
  • String stringE
  • do
  • System.out.print(Enter a letter )
  • stringE scan.next()
  • letterEntered stringE.charAt(0)
  • while (letterEntered ! Z)

8
What Is This?
  • while (!stringEntered.equals(apple))
  • System.out.println( Enter a red fruit )
  • stringEntered scan.next()
  • while (!stringEntered.equals(banana))
  • System.out.println(Enter a yellow fruit )
  • stringEntered scan.next()
  • while (!stringEntered.equals(pomegranate))
  • System.out.println(Enter a random fruit )
  • stringEntered scan.next()

9
What Is This?
  • for (i 0 i lt 10 i)
  • System.out.println( Interesting, isnt it?)
  • while (answer.charAt(0) ! D)
  • System.out.print( Enter an answer )
  • answer scan.next()
  • while (answer.charAt(0) ! D)
  • System.out.print( Enter an answer )
  • answer scan.next()

10
What Is This?
  • void
  • kingsChair(int loopCounter)
  • int num
  • for(num 0 num lt loopCounter num)
  • System.out.println(AAAAAAAAAAAAAAAAAAAAAAAA
    AA)
Write a Comment
User Comments (0)
About PowerShow.com