Loops in Java

In this article, I will discuss what loops are in JAVA, which are used for performing repetitive tasks, and how they are utilized. Generally, we will examine for and while loops.

When writing code in JAVA, there may be repetitive tasks within our code. For example, let’s say we want to print numbers from 1 to 10 on the screen. In this case, without using a loop, we would need to use the System.out.println() function 10 times. For example:

INPUT:

public class Main {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
System.out.println(6);
System.out.println(7);
System.out.println(8);
System.out.println(9);
System.out.println(10);
}
}

OUTPUT:

1
2
3
4
5
6
7
8
9
10

However, manually performing this task is not ideal because we would have to manually rewrite lines of code containing the same operations each time we write code. This will lead to both wasting time and making our code more complex and longer. Therefore, we should write our code with less effort and be able to perform more tasks with fewer lines of code. For this reason, we use loops for repetitive tasks. The purpose of loops is to repeat the same or similar code several times. This repetition can continue for a certain number of times or until a condition is met. There are two types of loops in JAVA. These are the for loop and the while loop.

First, let’s talk about the while loop.

WHILE Loop

The while loop is a type of loop that continues to execute the operations inside the code block as long as the condition we specify in the loop is true. The while loop is written as follows:

public class Main {
public static void main(String[] args) {
while (condition) {
// Code block to be executed if the specified condition is true
}
}
}

Examples of the usage of the while loop are as follows:

INPUT:

public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("i value: " + i);
i += 1;
}

}
}

OUTPUT:

i value: 0
i value: 1
i value: 2
i value: 3
i value: 4
INPUT:

public class Main {
public static void main(String[] args) {
boolean value = true;
int result = 0;
while (value == true) {
result += 3;
if(result > 40) {
System.out.println("Limit Exceeded! Last Value: " + result);
value = false;
}
}
}

}

OUTPUT:

Limit Exceeded! Last Value: 42

In the while loop, the code block runs if the condition is true. If we want the code block to be executed at least once regardless of whether the condition in the loop is true or false, we need to use the dowhile loop. The usage and logic of the dowhile loop are similar to the while loop. However, the difference is that it executes the code block once regardless of the condition. The dowhile loop is written as follows:

public class Main {
public static void main(String[] args) {
do {
// Code block to be executed
}
while (condition);

}

}

An example of using the dowhile loop is as follows:

INPUT:

public class Main {
public static void main(String[] args) {
int total = 0;
do {
System.out.println("Total: " + total);
total += 10;
} while (total < 100);
}
}

OUTPUT:

Total: 0
Total: 10
Total: 20
Total: 30
Total: 40
Total: 50
Total: 60
Total: 70
Total: 80
Total: 90
INPUT:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
int number1, number2, i, max, min, gcd;

Scanner input = new Scanner(System.in);

System.out.println("Please enter the first number: ");
number1 = input.nextInt();

System.out.println("Please enter the second number: ");
number2 = input.nextInt();

i = 2;
max = 1;
while (number1 >= i) {
if ((number1 % i == 0) && (number2 % i == 0)) {
max = i;
}
i++;
}

min = (number1 * number2) / max;

System.out.println("Greatest Common Divisor: " + max);
System.out.println("Least Common Multiple: " + min);
}
}

OUTPUT:

Please enter the first number:
60
Please enter the second number:
70
Greatest Common Divisor: 10
Least Common Multiple: 420
For Loop

The for loop is used when we want a certain code block to be repeated a desired number of times. The for loop can be written as follows:

public class Main {
public static void main(String[] args) {
for (initialValue; conditionToContinueLoop; incrementOrDecrement) {
// Code block to be executed
}

}
}

When writing a for loop, a variable is defined in the first part of the loop, and its initial value is given. Then, it is specified under what condition the loop should continue. Finally, each time the loop finishes, it is indicated how to progress or regress from the starting point. The for loop runs according to these values and performs the desired operations. Examples of using the for loop are as follows:

INPUT:

public class Main {
public static void main(String[] args) {
boolean check = true;

for(int i = 2; i <= 100; i++) {

for(int k = 2; k < i; k++) {

if(i % k == 0) {
check = false;
}
}
if(check == true) {
System.out.print(" " + i);
}
check = true;
}
}
}

OUTPUT:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
INPUT:

import java.util.Scanner;

class HelloWorld {
public static void main(String[] args) {
int value, power, result;

Scanner input = new Scanner(System.in);

System.out.print("Please enter a value: ");
value = input.nextInt();

System.out.print("Please enter a power value: ");
power = input.nextInt();

result = 1;

for(int i = 0; i < power; i++) {

result *= value;

}

System.out.println("Result: " + result);

}
}

OUTPUT:

Please enter a value: 6
Please enter a power value: 2
Result: 36

The for loop can also be used on arrays. The for loop we write on an array iterates through each element of the array and performs the desired operations on the array elements. The usage of such a for loop is as follows:

class HelloWorld {
public static void main(String[] args) {
for (DataType variableName : arrayName) {
// Code block to be executed
}

}
}
“`html

Below are examples of the for loop type we discussed:

INPUT:

class HelloWorld {
public static void main(String[] args) {
String[] array = {"Ahmet", "Mehmet", "Ali","Ayşe","Cansu","Gizem"};
for(String element : array){
if (element.equals("Ayşe")){
System.out.println("Reached the element Ayşe in the array!");
break;
}
}
}
}

OUTPUT:

Reached the element Ayşe in the array!

Finally, let’s talk about the usage of break and continue statements in while and for loops. We’ve already seen how the break statement is used in a switchcase structure. The logic of using the break statement in loops is similar.

If we want the loop to exit when a certain condition is met or a certain value is reached, we can use the break statement within the loop. When the break statement is executed, the loop will exit even if it should continue.

For example, let’s consider an array with 4 names: {“Ahmet”, “Mehmet”, “Ayşe”, “Fatma”}. Let’s write a loop that exits when it encounters the name Ayşe in the array. We can write this loop as follows:

INPUT:

public class Main {
public static void main(String[] args) {
String[] names = {"Ahmet", "Mehmet", "Ayşe", "Fatma"};
for (String name : names) {
if (name.equals("Ayşe")){
System.out.println("Exited the loop because the current value is Ayşe.");
break;
} else {
System.out.println(name);
}
}
}
}

OUTPUT:

Ahmet
Mehmet
Exited the loop because the current value is Ayşe.

As seen above, the loop exited when it encountered Ayşe, and it never reached Fatma.

In such cases where exiting the loop is necessary, the break statement can be used.

The continue statement is used to skip the current iteration of a loop when a certain condition or value is encountered. When continue is executed, it skips the current loop iteration and moves to the next one without executing the remaining code block for that iteration. If it does not enter the block containing continue in the next loop iteration, it performs the operations in the loop block.

For example, let’s say we want to print numbers from 1 to 10 but skip printing 5. We can achieve this using the continue statement:

INPUT:

public class Main {
public static void main(String[] args) {
for(int i = 0; i <= 10; i++){
if (i == 5){
continue;
}
System.out.println(i);
}
}
}

OUTPUT:

0
1
2
3
4
6
7
8
9
10

Let’s conclude our discussion with a few more examples of for and while loops.

INPUT:

import java.util.Scanner;

class HelloWorld {
public static void main(String[] args) {
int number, sum, digit, temp;

Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
number = input.nextInt();

temp = number;
sum = 0;

while (temp != 0) {
digit = temp % 10;
sum += digit;
temp /= 10;
}

System.out.println("Sum of Digits: " + sum);
}
}

OUTPUT:

Enter a number: 16
Sum of Digits: 7
INPUT:

import java.util.Scanner;

public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int firstNumber = 0, secondNumber = 1, sum, limit;
System.out.print("Enter N value:");
limit = input.nextInt();
System.out.print(firstNumber+" "+secondNumber);

for(int i = 2 ; i <= limit + 1; ++i){
sum = firstNumber + secondNumber;
System.out.print(" "+sum);
firstNumber = secondNumber;
secondNumber = sum;

}
System.out.println();
}

}

OUTPUT:

Enter N value:8
0 1 1 2 3 5 8 13 21
INPUT:

import java.util.Scanner;

public class Main
{
public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("How many numbers will be entered? : ");
int n = input.nextInt();

System.out.print("Please enter a value : ");
int firstValue = input.nextInt();

int smallest = firstValue;
int largest = firstValue;
for(int i = 0; i < n-1; i++){

System.out.print("Please enter a value : ");
int value = input.nextInt();

if(value > largest){
largest = value;
}
if(value < smallest){
smallest = value;
}
}
System.out.println("Largest value : " + largest);
System.out.println("Smallest value : " + smallest);
}
}

OUTPUT:

How many numbers will be entered? : 5
Please enter a value : 15
Please enter a value : 45
Please enter a value : 321
Please enter a value : 54
Please enter a value : 34
Largest value : 321
Smallest value : 15
INPUT:

import java.util.Scanner;

class Patika_Java_101 {
public static void main(String[] args) {
int nEnd;
double sum;

Scanner input = new Scanner(System.in);

System.out.print("Please enter the end value of n : ");
nEnd = input.nextInt();

sum = 0;

for(double i = 1; i <= nEnd; i++){
sum += (1/i);
}

System.out.println("Harmonic Sum : " + sum);

}
}

OUTPUT:

Please enter the end value of n : 6
Harmonic Sum : 2.4499999999999997

You can access our next article about arrays in JAVA from here.

JAVA9US7B9AB2H5L3R

Leave a Reply

Your email address will not be published. Required fields are marked *