๐Ÿ’ŽCommon Loop Examples

For Loop

  1. Print numbers from 1 to 10 using a for loop.

for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}
  1. Print even numbers from 1 to 20 using a for loop.

for (int i = 2; i <= 20; i += 2) {
    System.out.println(i);
}
  1. Print odd numbers from 1 to 20 using a for loop.

for (int i = 1; i <= 20; i += 2) {
    System.out.println(i);
}
  1. Calculate the sum of numbers from 1 to 100 using a for loop.

int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
System.out.println("Sum: " + sum);
  1. Print the multiplication table of a given number using a for loop.

int number = 5;
for (int i = 1; i <= 10; i++) {
    System.out.println(number + " x " + i + " = " + (number * i));
}
  1. Print the Fibonacci series up to a given number using a for loop.

int n = 10;
int first = 0;
int second = 1;
System.out.print(first + " " + second + " ");
for (int i = 2; i < n; i++) {
    int next = first + second;
    System.out.print(next + " ");
    first = second;
    second = next;
}
  1. Find the factorial of a given number using a for loop.

int number = 5;
int factorial = 1;
for (int i = 1; i <= number; i++) {
    factorial *= i;
}
System.out.println("Factorial: " + factorial);
  1. Print the reverse of a given string using a for loop.

String str = "Hello World";
for (int i = str.length() - 1; i >= 0; i--) {
    System.out.print(str.charAt(i));
}
  1. Check if a given number is prime using a for loop.

int number = 17;
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(number); i++) {
    if (number % i == 0) {
        isPrime = false;
        break;
    }
}
System.out.println("Is Prime: " + isPrime);
  1. Count the number of vowels in a given string using a for loop.

String str = "Hello World";
int vowelCount = 0;
for (int i = 0; i < str.length(); i++) {
    char ch = Character.toLowerCase(str.charAt(i));
    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
        vowelCount++;
    }
}
System.out.println("Vowel Count: " + vowelCount);

While Loop

  1. Print numbers from 1 to 10 using a while loop.

int i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}
  1. Print even numbers from 1 to 20 using a while loop.

int i = 2;
while (i <= 20) {
    System.out.println(i);
    i += 2;
}
  1. Print odd numbers from 1 to 20 using a while loop.

int i = 1;
while (i <= 20) {
    System.out.println(i);
    i += 2;
}
  1. Calculate the sum of numbers from 1 to 100 using a while loop.

int i = 1;
int sum = 0;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("Sum: " + sum);
  1. Print the multiplication table of a given number using a while loop.

int number = 5;
int i = 1;
while (i <= 10) {
    System.out.println(number + " x " + i + " = " + (number * i));
    i++;
}
  1. Print the Fibonacci series up to a given number using a while loop.

int n = 10;
int first = 0;
int second = 1;
System.out.print(first + " " + second + " ");
int i = 2;
while (i < n) {
    int next = first + second;
    System.out.print(next + " ");
    first = second;
    second = next;
    i++;
}
  1. Find the factorial of a given number using a while loop.

int number = 5;
int factorial = 1;
int i = 1;
while (i <= number) {
    factorial *= i;
    i++;
}
System.out.println("Factorial: " + factorial);
  1. Print the reverse of a given string using a while loop.

String str = "Hello World";
int i = str.length() - 1;
while (i >= 0) {
    System.out.print(str.charAt(i));
    i--;
}
  1. Check if a given number is prime using a while loop.

int number = 17;
boolean isPrime = true;
int i = 2;
while (i <= Math.sqrt(number)) {
    if (number % i == 0) {
        isPrime = false;
        break;
    }
    i++;
}
System.out.println("Is Prime: " + isPrime);
  1. Count the number of vowels in a given string using a while loop.

String str = "Hello World";
int vowelCount = 0;
int i = 0;
while (i < str.length()) {
    char ch = Character.toLowerCase(str.charAt(i));
    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
        vowelCount++;
    }
    i++;
}
System.out.println("Vowel Count: " + vowelCount);

For-Each Loop

The foreach loop is used to iterate over elements of an array or a collection without using an index variable. The syntax for a foreach loop is as follows:

for (type var : array/collection) {
    // statements to be executed
}

Here are some examples of using foreach loops in Java:

  1. Print elements of an array using a foreach loop.

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}
  1. Print elements of a list using a foreach loop.

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
    System.out.println(name);
}
  1. Calculate the sum of elements in an array using a foreach loop.

int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
    sum += num;
}
System.out.println("Sum: " + sum);
  1. Print the multiplication table of a given number using a foreach loop.

int number = 5;
int[] multiples = new int[10];
for (int i = 0; i < multiples.length; i++) {
    multiples[i] = number * (i + 1);
}
for (int multiple : multiples) {
    System.out.println(multiple);
}
  1. Print the Fibonacci series up to a given number using a foreach loop.

int n = 10;
List<Integer> fib = new ArrayList<>();
fib.add(0);
fib.add(1);
for (int i = 2; i < n; i++) {
    int next = fib.get(i - 1) + fib.get(i - 2);
    fib.add(next);
}
for (int num : fib) {
    System.out.print(num + " ");
}

The time and space complexity of foreach loops in Java are the same as for loops, which depend on the number of iterations and the size of the array or collection. The time complexity of a foreach loop is O(n), where n is the number of iterations. The space complexity of a foreach loop is O(1), as it only uses a fixed number of variables.

Switch Statement

The next important loop commonly used in interviews is the switch statement. The switch statement is used to perform different actions based on different conditions. It provides an alternative to using multiple if-else statements. The syntax for a switch statement is as follows:

switch (expression) {
    case value1:
        // statements to be executed if expression matches value1
        break;
    case value2:
        // statements to be executed if expression matches value2
        break;
    ...
    default:
        // statements to be executed if expression doesn't match any case
}

Here are some examples of using switch statements in Java:

  1. Print the name of the day based on the day number using a switch statement.

int day = 3;
String dayName;
switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
        dayName = "Saturday";
        break;
    case 7:
        dayName = "Sunday";
        break;
    default:
        dayName = "Invalid day";
}
System.out.println("Day: " + dayName);
  1. Calculate the number of days in a given month using a switch statement.

int month = 2;
int year = 2023;
int days;
switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
        days = 31;
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        days = 30;
        break;
    case 2:
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            days = 29;
        } else {
            days = 28;
        }
        break;
    default:
        days = -1;
}
System.out.println("Number of days: " + days);
  1. Perform different operations based on the operator using a switch statement.

int num1 = 10;
int num2 = 5;
char operator = '+';
int result;
switch (operator) {
    case '+':
        result = num1 + num2;
        break;
    case '-':
        result = num1 - num2;
        break;
    case '*':
        result = num1 * num2;
        break;
    case '/':
        result = num1 / num2;
        break;
    default:
        result = 0;
}
System.out.println("Result: " + result);

The time and space complexity of switch statements in Java are constant, O(1), as the execution time and memory usage do not depend on the number of cases. However, the efficiency of a switch statement can be impacted by the number of cases and the complexity of the statements within each case.

Last updated