Lesson Set 6

Lesson Set 6 - CS 1136 Lab 6 While, Do-While and For Loops...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CS 1136 Lab 6 While, Do-While and For Loops While Loops If statements allow the program to skip the execution of a statement or choose between one of two statements to be executed based on the value of a Boolean expression. In contrast, the while statement allows a program to continue executing a statement as long as the value of a Boolean expression is true. When the Boolean expression becomes false, the execution of the program continues with the statement immediately following the while statement. What would happen in this program if value were initialized to 1 instead of 0? Scanner keyboard = new Scanner(System.in()); int value = 0; while (value >= 0) { System.out.println( “Please enter a number.” ); value = keyboard.nextInt(); } System.out.println( “You entered a negative number” ); For obvious reasons, the while statement is called a loop. The statements that are being executed within the loop are called the body of the loop. There are three basic steps that must be done for a loop to execute properly. 1. The variables in the while expression ( value in the above example) must be initialized before the while statement is executed the first time. 2. The variables in the while expression must test the status of the expression correctly so that the body of the loop executes when it is supposed to and terminates at the proper time. 3.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

Lesson Set 6 - CS 1136 Lab 6 While, Do-While and For Loops...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online