Professional Documents
Culture Documents
Objectives: Midterm Laboratory No. 1: Loop Structures
Objectives: Midterm Laboratory No. 1: Loop Structures
Objectives
1. To understand the concepts and theory of 3 different loop structures.
2. To build programs using 3 different loop structures
3. To know how to trace the program using different loops
Background
1. for loop
2. while loop
3. do-while loop
The Java for loop is used to iterate a part of the program several times. If the number
of iteration is fixed, it is recommended to use for loop.
while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it
is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after
loop body.
General Instructions:
SCP-CC103 | 1
ST. JOHN PAUL II COLLEGE OF DAVAO
COLLEGE OF INFORMATION AND
COMMUNICATIONS TECHNOLOGY
Activity 1.1. Write a program that prints all even numbers from 1 to 50 inclusive using the for
loop, while loop, and do…while loop. The class name is EvenNum. (20PTS)
Expected output:
SCP-CC103 | 2
ST. JOHN PAUL II COLLEGE OF DAVAO
COLLEGE OF INFORMATION AND
COMMUNICATIONS TECHNOLOGY
int i =2;
while(i<=n){
if(i % 2 == 0){
System.out.print(i +" ");
i = i + 2;
}
}
System.out.println("");
System.out.println("--Using do-while loop--");
i = 2;
do{
if(i % 2 ==0){
System.out.print(i + " ");
i = i + 2;
}
}
while(i<=50);
}
}
Your Output:
SCP-CC103 | 3
ST. JOHN PAUL II COLLEGE OF DAVAO
COLLEGE OF INFORMATION AND
COMMUNICATIONS TECHNOLOGY
Activity 1.2. Write a program that sums the integers from 1 to 50 using any looping
statement. The class name is Sum50. (20PTS)
Expected output:
}
System.out.println("The sum of numbers from 1 to 50 is " + sum);
}
Your Output:
Activity 1.3. Write a program that prints every integer value from 1 to 20 along with its squared
value using the following looping structures (for, while, and do-while loop). The class name is
TableOfSquares. (30PTS)
Expected output:
SCP-CC103 | 4
ST. JOHN PAUL II COLLEGE OF DAVAO
COLLEGE OF INFORMATION AND
COMMUNICATIONS TECHNOLOGY
SCP-CC103 | 5
ST. JOHN PAUL II COLLEGE OF DAVAO
COLLEGE OF INFORMATION AND
COMMUNICATIONS TECHNOLOGY
Expected Output:
sum+=2*i-1;
}
}
}
Your Output:
SCP-CC103 | 6
ST. JOHN PAUL II COLLEGE OF DAVAO
COLLEGE OF INFORMATION AND
COMMUNICATIONS TECHNOLOGY
Activity 1.5. Write a for statement to compute the sum of an N as an entered integer 1
+ 2² + 3² + 4² + 5² + ... + N². (50PTS)
Expected Output:
int i;
int sum = 0;
for( i = 1; i <= n; i++)
{
sum+=(i* i);
}
}
}
Your Output:
SCP-CC103 | 7