CPSC 233 Tutorial 5 February 2 th /3 th, 2015
Java Loop Statements A portion of a program that repeats a statement or a group of statements is called a loop. The statement or group of statements to be repeated is called the body of the loop.
Java Loop Statements The while statement The do-while statement The for Statement
The while Statement
The do-while Statement Similar to a while statement, except that the loop body is executed at least once
The for Statement
Exercise 1 Write a fragment of code that will read words from the keyboard until the word done is entered. For each word except done, report whether its first character is equal to its last character.
Exercise Description Prompt the user to enter a word Read words from the keyboard until the word done is entered For the required loop you can use a a)while statement b)do-while statement Check if the word’s first character is equal to its last character or not
1th Solution using while statement
2th Solution using do-while Statement
Exercise 2 Write a loop that will create a string that is the reverse of a string the user indicates.
Exercise2 Description Prompt the user to enter a string Read String from the keyboard Create a loop that iterates over individual string characters in reverse sequence
Exercise2 Solution
Exercise 3 Write a program that will read from the keyboard until the user enters a positive number. Then it computes the sum of the first n positive odd integers. For example, if n = 5, then you should compute
Exercise3 Description Prompt the user to enter a positive number Read from the keyboard until the user enters a positive number compute the sum of the first n positive odd integers
Exercise3 Description