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
Churn Modeling Application #1
Loading Libraries and Dataset

In this article, we will start implementing a Churn modeling application using various machine learning algorithms. The scope of this Churn modeling application will not be limited to just using machine learning algorithms.

In addition, we will perform operations such as gaining insights from the dataset, data preprocessing, data visualization, and comparing different algorithms with different success criteria on the dataset. With this comparison process, we will see the success of each algorithm on the data with these different success criteria and then make a general evaluation.

Let’s start by explaining what Churn means, as we used in the title of our article.

What is Churn?

Terminologically, it means loss. This can be interpreted as the loss of a target data in any field. Churn in this study commonly refers to how much a business loses customers within a certain period. With Churn modeling, we can analyze the customer loss of any business. Through this analysis, businesses can predict customers who will no longer work with them.

As we perform this application, you can access the dataset we will use from here. Like our other articles, we will examine the dataset using Python on Google Colab. To do this, you first need to download the dataset from the relevant site and upload it to Google Drive. After logging into Google Colab with your Google Drive email address, you will be able to use the dataset.

After completing the steps above, we can now work with the dataset. First, we need to load the libraries we will use on the dataset. We can use the following code block for this:

!pip install researchpy
!pip install keras-tuner

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
import researchpy as rp
import lightgbm as lgb
warnings.filterwarnings("ignore")
from sklearn.metrics import roc_auc_score, accuracy_score, confusion_matrix,classification_report,roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB,MultinomialNB,ComplementNB,BernoulliNB
from sklearn.metrics import roc_curve, auc

roc_auc_score, accuracy_score, confusion_matrix, classification_report, and roc_auc_score will be used to measure the performance of the algorithms. We can compare the results obtained from these to see which algorithm is successful with which metric.

Since our dataset is in Excel format, we will use the read_csv method of the pandas library to load it in the Python environment. After loading our data, we will use the head method to display a specified number of data from our dataset.

data = pd.read_csv("/content/drive/MyDrive/Churn_Modelling.csv")
data.head(10)

The descriptions of the parameters contained in our dataset are as follows:

< td class="has-text-align-center" data-align="center">Geography
ParameterDescription
CreditScoreIndicates the customer’s credit score.
Indicates the country of the customer.
GenderIndicates the gender of the customer.
AgeColumn indicating the age of the customer.
TenureColumn indicating the working period of the customer with the bank.
BalanceColumn indicating the balance of the customer.
NumOfProductsColumn indicating the number of products the customer owns.
HasCrCardColumn indicating whether the customer has a credit card or not.
IsActiveMemberColumn indicating whether the customer is an active user.
EstimatedSalaryColumn indicating the estimated annual salary of the customer.
ExitedColumn indicating whether the customer left the bank.
RowNumberIndicates the column number of the customer.
CustomerIdIndicates the user number of the customer.
SurnameIndicates the surname of the customer.

When examining our dataset and parameters, RowNumber, CustomerId, and Surname parameters are insignificant and need to be removed from our dataset. At the same time, since the region where the person lives and their gender do not determine whether they will leave the bank, we will convert these values to numeric using One Hot transformation.

After these operations, we will group the age groups into certain intervals, convert them into categorical, and then convert them into numeric using One Hot transformation.

Before performing the operations mentioned above, let’s try to gain insights from the data.

Gaining Insights from the Dataset

We see that we have an “Exited” column in our dataset. This value indicates whether the customer left the bank or not, so by taking the sum of this column, we can obtain the total number of customers who left the bank.

INPUT:

data["Exited"].sum()

OUTPUT:


2037

We see that there are 2037 customers who left the bank in the dataset.

INPUT:

data.isna().sum()

OUTPUT:

RowNumber          0
CustomerId         0
Surname            0
CreditScore        0
Geography          0
Gender             0
Age                0
Tenure             0
Balance            0
NumOfProducts      0
HasCrCard          0
IsActiveMember     0
EstimatedSalary    0
Exited             0
dtype: int64

There are no missing values in the dataset.

INPUT:

data.info()

OUTPUT:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10000 entries, 0 to 9999
Data columns (total 14 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   RowNumber        10000 non-null  int64  
 1   CustomerId       10000 non-null  int64  
 2   Surname          10000 non-null  object 
 3   CreditScore      10000 non-null  int64  
 4   Geography        10000 non-null  object 
 5   Gender           10000 non-null  object 
 6   Age              10000 non-null  int64  
 7   Tenure           10000 non-null  int64  
 8   Balance          10000 non-null  float64
 9   NumOfProducts    10000 non-null  int64  
 10  HasCrCard        10000 non-null  int64  
 11  IsActiveMember   10000 non-null  int64  
 12  EstimatedSalary  10000 non-null  float64
 13  Exited           10000 non-null  int64  
dtypes: float64(2), int64(9), object(3)
memory usage: 1.1+ MB

When we examine the returned values, we confirm that there are no missing values in the dataset. We can also see the data types of the columns in the dataset.

INPUT

data["Geography"].unique()

OUTPUT:

array(['France', 'Spain', 'Germany'], dtype=object)

Our dataset contains individuals from 3 different countries: Spain, France, and Germany.

To examine the distribution percentages of classes within the categorical columns in the dataset, we can use the following code block:

INPUT:

fig, axarr = plt.subplots(2, 3, figsize=(30, 10))
data["Gender"].value_counts().plot.pie(explode = [0.05,0.05], autopct = '%1.1f%%',ax=axarr[0][0]);
data["Geography"].value_counts().plot.pie(explode = [0.05,0.05,0.05], autopct = '%1.1f%%',ax=axarr[0][1]);
data["IsActiveMember"].value_counts().plot.pie(labels = ["Active","Inactive"],explode = [0.05,0.05], autopct = '%1.1f%%',ax=axarr[0][2]);
data["NumOfProducts"].value_counts().plot.pie(explode = [0.05,0.05,0.05,0.06], autopct = '%1.1f%%',ax=axarr[1][0]);
data["HasCrCard"].value_counts().plot.pie(labels = ["Yes","No"],explode = [0.05,0.05], autopct = '%1.1f%%',ax=axarr[1][1]);
data["Exited"].value_counts().plot.pie(labels = ["Not Exited","Exited"],explode = [0.05,0.05], autopct = '%1.1f%%',ax=axarr[1]

When examining the pie charts above:

  • We observe that the majority of individuals in the dataset are male,
  • Most of our customers are from France; additionally, the presence of French customers is almost twice that of German and Spanish customers,
  • While the majority of our customers are active users, the percentage of inactive users is quite high,
  • 96.7% of our customers have at most 2 products,
  • The majority of our customers have a credit card,
  • We can see that 79.6% of the customers in our dataset have not exited the bank.

If we want to find out how many columns and data samples are in our dataset, we can use the following code block:

INPUT:

data.shape

OUTPUT:

(10000, 14)

When the code block is executed, we get the result (10000, 14). This indicates that there are 10000 data samples and 14 columns.

In our next article, we will continue to gain insights from our dataset by visualizing the data.

You can access our next article by clicking here.

MCHNLRNRU95A10517