Skip to main content

Control Flow: Practice

Basic Loops 1

Loops may seem tricky, but practicing them makes them your helpful buddies in programming.

So, let's get started!


Problem1: Write a java program to print all even numbers between 1 to 100 using for loop.

Input

10

Output

Even numbers between 1 to 10:
2, 4, 6, 8, 10

Approach

Hint

You already know how to print odd numbers till n using a for loop. It is just that odd numbers start from 1 and even from 2. Check that out and try again.

Solution
import java.util.*;

public class main {
    public static void main(String[] args) {
        // Taking input of the number
        System.out.println("Enter a number: ");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        System.out.println("Even numbers between 1 to " + num + " :");
        // Starting the iteration with 2 since we need to print even numbers
        for(int i = 2; i <= num; i = i + 2) {
            System.out.println(i);
        }
        
    }
}

Problem2: Write a java program to find sum of all odd numbers from 1 to n using for loop.

Input

10

Output

Sum of odd numbers from 1 to given input is:
25

Approach

Hint

Again, we have already covered how to print the sum of all even numbers from 1 to n using a for loop. It is just that odd numbers start from 1 and even from 2. Check that out and try again.

Solution
import java.util.*;
public class main {
    public static void main(String[] args) {
      // Taking input of the number
      System.out.println("Enter a number: ");
      Scanner sc = new Scanner(System.in);
      int num = sc.nextInt();	
        
      int sum = 0;
      // Starting the iteration with 1 since we need to print sum of odd numbers
      for(int i = 1; i <= num; i += 2){  
         sum += i;  
      }   
       
       System.out.println("Sum of odd numbers from 1 to given input is:");
       System.out.println(sum);
    }
}

Problem3: Write a java program to print multiplication table of any number.

Input

5

Output

5 * 1  = 5
5 * 2  = 10
5 * 3  = 15
5 * 4  = 20
5 * 5  = 25
5 * 6  = 30
5 * 7  = 35
5 * 8  = 40
5 * 9  = 45
5 * 10 = 50

Approach

Hint

Just iterate till 10, as we were iterating till n earlier and print the product correctly.

Solution
import java.util.*;

public class main {
    public static void main(String[] args) {
        // Taking input of the number
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number to print table: ");
        int num = scanner.nextInt();

        // Iterating and printing the product
        for (int i = 1; i <= 10; i++) {
            System.out.println(num + " * " + i + " = " + (num * i));
        }
    }
}

Problem4: Write a java program to input a number from user and count number of digits in the given integer.

Input

35419

Output

Total digits: 5

Approach

Hint

Whatever the number is, we know it will always have atleast 1 digit. Can you think of the loop we can use?

Yes, it is do while loop.

Explanation

Let's say we have the number is 9. If we divide it by 10, we get 0 as quotient.
And if the number is 89, and we divide it by 10, we get 8 as the quotient. Dividing 8 further by 10, gives 0 as the quotient.
Okay, what about 789? We can divide it 3 times until we have quotient as 0.


I feel we are able to observe some pattern from these examples. The number of times we can divide a number by 10 until the quotient equals zero tells us how many digits that number has.

Solution
import java.util.*;

public class main {
    public static void main(String[] args) {
        int count = 0;

        // Input number from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any number: ");
        long num = scanner.nextLong();

        // Run loop till num is greater than 0
        do {
            // Increment digit count
            count++;

            // Remove the last digit of 'num'
            num /= 10;
        } while (num != 0);

        System.out.println("Total digits: " + count);
    }
}

Tip:
You can even calculate number of digits without using loops. That is:

Number of digits(num) = (log10(num) + 1)

Problem5: Write a java program to input a number and calculate sum of digits.

Input

1234

Output

10

Approach

Hint

For finding the sum of value of digits, we need to think of the way of getting hold of a particular digit. Okay, so with the help of previous question, can you think of how we can do that?

On diving a number by 10, the remainder gives us the digit at the unit's place. That means if we keep on dividing a number by 10 until the number is 0, we can get the digits and eventually the sum.

Isn't that amazing? Let's code the solution now 🥳

Solution
import java.util.*;

public class main {
    public static void main(String[] args) {
        // Input a number from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any number to find sum of its digit: ");
        int num = scanner.nextInt();

        int sum = 0;
        // Repeat till num becomes 0
        while (num != 0) {
            // Find the last digit of num and add to sum
            sum += num % 10;

            // Remove the last digit from num
            num = num / 10;
        }

        System.out.println("Sum of digits = " + sum);
    }
}

Tip:

Coding advice is here, ready to be enjoyed like a delicious cherry!
Try not to change the provided number in any way. After storing the value in another variable, perform the computation on that variable. This is because the input might be used by the program later on.

Hooray! Let's gear up for the next adventure: Getting Hold of Loops! 🚀