Lesson5. Repetition
Lesson5. Repetition
Programming 2
(Java)
Dr. Marygin E. Sarmiento
Professor
Repetition Structure
Do While
While
For Loop
Learning outcomes
At the end of the lesson, the students
are expected to:
Define Repetition Concept
Enumerate the types of Repetition
Determine the Syntax of each
Repetition
Develop their own program using
Repetition
Introduction
Looping is the process of repeatedly
executing one or more steps of an
algorithm or program; it is essential in
programming, as most programs
perform repetitious tasks
Syntax:
While (condition)
Statement;// executed when the
condition is true
Example:
Example 2
import java.io.*;
public class DoWhileLoop
{
public static void main (String [] args) throws Exception
{
char alpha;
do
{
System.out.print(“Enter a character:”);
alpha = Character.toUpperCase((char)
System.in.read());
System.in.read(); System.in.read();
{
while (alpha != ‘X’);
System.out.println(“Exit program”);
}
}
Example 3
packageswitchcase_DoLoop;
import java.io.*;
public class do_switch_doLoop
{public static void main (String args[]) throws Exception
{BufferedReader input = new BufferedReader( new
InputStreamReader(System.in));
int s, r, square_area;
double pi, Circle_area;
int width, length, Rec_Area;
String ans;
do
{//begin of do
System.out.println("[C]Circle [R] Rectangle [S] Square [Q] Quit");
System.out.print("Please Enter Your Choice: ");
ans = input.readLine();
switch (ans)
{//begin of switch
case "C":{
r =100;
pi = 3.1416;
System.out.println("The Value for Radius: " + r);
System.out.println("The Value for pi: " + pi);
Circle_area = 2*pi*(r*r);
System.out.println("The area of a circle is: "+ Circle_area); }
System.out.println();
break;
case "R": {
width = 300;
length = 5;
System.out.println("The value for Width "+width);
System.out.println("The value for Length "+length);
Rec_Area = length * width;
System.out.println("The area of a rectangle is "+ Rec_Area); }
break;
case "S":{
s = 10;
System.out.println("The value for value for side is " +s);
square_area = s*s;
System.out.println("The area of a square is "+ square_area); }
break;
case "Q": System.out.println("Good Bye");
default: System.out.println("Try Again");
}//end of switch
System.out.print("Back to main menu Y/N? " );
ans = input.readLine();
}//end of do
while (!ans.equals("N"));
}//end of main
}//end of class
Output
THE FOR LOOP
Syntax:
import java.io.*;
public class nametentimes
{
public static void main (String [] args) throws Exception
{
BufferedReader input = new BufferedReader(InputStreamReader
(System.in());
String name;
do
{
System.out.print(“Enter Your Name:”);
name = input.readLine();
}
while (alpha <11);
System.out.println(“\n” + name);
}
}
ACTIVITIES
Activity # 1.
Activity # 2