# Common Loop Examples

## For Loop

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

```java
for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}
```

2. Print even numbers from 1 to 20 using a for loop.

```java
for (int i = 2; i <= 20; i += 2) {
    System.out.println(i);
}
```

3. Print odd numbers from 1 to 20 using a for loop.

```java
for (int i = 1; i <= 20; i += 2) {
    System.out.println(i);
}
```

4. Calculate the sum of numbers from 1 to 100 using a for loop.

```java
int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
System.out.println("Sum: " + sum);
```

5. Print the multiplication table of a given number using a for loop.

```java
int number = 5;
for (int i = 1; i <= 10; i++) {
    System.out.println(number + " x " + i + " = " + (number * i));
}
```

6. Print the Fibonacci series up to a given number using a for loop.

```java
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;
}
```

7. Find the factorial of a given number using a for loop.

```java
int number = 5;
int factorial = 1;
for (int i = 1; i <= number; i++) {
    factorial *= i;
}
System.out.println("Factorial: " + factorial);
```

8. Print the reverse of a given string using a for loop.

```java
String str = "Hello World";
for (int i = str.length() - 1; i >= 0; i--) {
    System.out.print(str.charAt(i));
}
```

9. Check if a given number is prime using a for loop.

```java
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);
```

10. Count the number of vowels in a given string using a for loop.

```java
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.

```java
int i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}
```

2. Print even numbers from 1 to 20 using a while loop.

```java
int i = 2;
while (i <= 20) {
    System.out.println(i);
    i += 2;
}
```

3. Print odd numbers from 1 to 20 using a while loop.

```java
int i = 1;
while (i <= 20) {
    System.out.println(i);
    i += 2;
}
```

4. Calculate the sum of numbers from 1 to 100 using a while loop.

```java
int i = 1;
int sum = 0;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("Sum: " + sum);
```

5. Print the multiplication table of a given number using a while loop.

```java
int number = 5;
int i = 1;
while (i <= 10) {
    System.out.println(number + " x " + i + " = " + (number * i));
    i++;
}
```

6. Print the Fibonacci series up to a given number using a while loop.

```java
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++;
}
```

7. Find the factorial of a given number using a while loop.

```java
int number = 5;
int factorial = 1;
int i = 1;
while (i <= number) {
    factorial *= i;
    i++;
}
System.out.println("Factorial: " + factorial);
```

8. Print the reverse of a given string using a while loop.

```java
String str = "Hello World";
int i = str.length() - 1;
while (i >= 0) {
    System.out.print(str.charAt(i));
    i--;
}
```

9. Check if a given number is prime using a while loop.

```java
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);
```

10. Count the number of vowels in a given string using a while loop.

```java
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:

```java
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.

```java
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}
```

2. Print elements of a list using a foreach loop.

```java
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
    System.out.println(name);
}
```

3. Calculate the sum of elements in an array using a foreach loop.

```java
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
    sum += num;
}
System.out.println("Sum: " + sum);
```

4. Print the multiplication table of a given number using a foreach loop.

```java
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);
}
```

5. Print the Fibonacci series up to a given number using a foreach loop.

```java
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:

```java
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.

```java
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);
```

2. Calculate the number of days in a given month using a switch statement.

```java
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);
```

3. Perform different operations based on the operator using a switch statement.

```java
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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://qatesting.gitbook.io/qa/java/loops/common-loop-examples.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
