Sitemap
Kshitij Kumar

Kshitij Kumar

Loops in Java

7 min readFeb 4, 2023

Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.

By using loops, you can simplify your code and make it more efficient at repetitive actions.

In Java, there are three types of loops:

  1. For loop: A for loop is used when the number of iterations is known in advance. The basic syntax of a for loop is:
for (initialization; condition; increment/decrement) {
// code to be executed
}

2. While loop: A while loop is used when the number of iterations is not known in advance. The basic syntax of a while loop:

while (condition) {
// code to be executed
}

3. Do-while loop: A do-while loop is similar to a while loop, but the condition is checked at the end of each iteration. The basic syntax of a do-while loop is:

do {
// code to be executed
} while (condition);

Problem

  1. Reverse a Number
import java.util.Scanner;

public class ReverseNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int reversed = 0;
while (num != 0) {
int lastDigit = num % 10;
reversed = reversed * 10 + lastDigit;
num /= 10;
}
System.out.println("Reversed number: " + reversed);
}
}

2. Sum of Digit (Sum of Even Places and Odd Places) and Print Both of Them

import java.util.Scanner;

public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int evenSum = 0, oddSum = 0;
int digit, place = 1;
while (num != 0) {
digit = num % 10;
if (place % 2 == 0) {
evenSum += digit;
} else {
oddSum += digit;
}
place++;
num /= 10;
}
System.out.println("Sum of digits in even places: " + evenSum);
System.out.println("Sum of digits in odd places: " + oddSum);
}
}

3.LCM of a Number

import java.util.Scanner;

public class LCM {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
int gcd = 1;
int min = Math.min(num1, num2);
for (int i = 1; i <= min; i++) {
if (num1 % i == 0 && num2 % i == 0) {
gcd = i;
}
}
int lcm = (num1 * num2) / gcd;
System.out.println("The LCM of " + num1 + " and " + num2 + " is: " + lcm);
}
}

4. Print Armstrong number b/w 1 to N

import java.util.Scanner;

public class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
System.out.println("Armstrong numbers between 1 and " + n + " are:");
for (int i = 1; i <= n; i++) {
if (isArmstrong(i)) {
System.out.print(i + " ");
}
}
}
static boolean isArmstrong(int x) {
int n = 0, a, temp;
temp = x;
while (temp != 0) {
a = temp % 10;
n = n + a * a * a;
temp = temp / 10;
}
return (n == x);
}
}

5.Sum of Series.

import java.util.Scanner;

public class SumOfSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of terms in the series: ");
int n = sc.nextInt();
System.out.print("Enter the formula for each term: ");
String formula = sc.next();
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += Double.parseDouble(formula.replace("x", Integer.toString(i)));
}
System.out.println("The sum of the series is: " + sum);
}
}

6.Implement a program to find out whether a number is a seed of another number.A number X is said to be a seed of number Y if multiplying X by its every digit equates to Y.

import java.util.Scanner;

public class SeedNumber {
public static int multiplyDigits(int n) {
int result = 1;
while (n > 0) {
int digit = n % 10;
if (digit == 0) {
return 0;
}
result *= digit;
n /= 10;
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter X: ");
int x = sc.nextInt();
System.out.print("Enter Y: ");
int y = sc.nextInt();
sc.close();
int z = x;
while (z < y) {
z = multiplyDigits(z) * x;
}
if (z == y) {
System.out.println(x + " is a seed of " + y);
} else {
System.out.println(x + " is not a seed of " + y);
}
}
}

7. WAP to find the Prime Number b/w 1 to N

import java.util.Scanner;

public class PrimeNumbers {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n: ");
int n = sc.nextInt();
sc.close();
System.out.println("Prime numbers between 1 and " + n + " are:");
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
}

9. Implement a program to find out whether a number is divisible by the sum of its digits. Display appropriate messages.

import java.util.Scanner;

public class DivisibleBySum {
public static int sumOfDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
sc.close();
int sum = sumOfDigits(num);
if (num % sum == 0) {
System.out.println(num + " is divisible by the sum of its digits (" + sum + ")");
} else {
System.out.println(num + " is not divisible by the sum of its digits (" + sum + ")");
}
}
}

10. Find out Prime Number

public class PrimeNumber {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for(int i = 2; i <= num/2; ++i) {
if(num % i == 0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

11. Java has 8 primitive data types; char, boolean, byte, short, int, long, float, and double. For this exercise, we’ll work with the primitives used to hold integer values (byte, short, int, and long):

  • A byte is an 8-bit signed integer.
  • A short is a 16-bit signed integer.
  • An int is a 32-bit signed integer.
  • A long is a 64-bit signed integer.

Given an input integer, you must determine which primitive data types are capable of properly storing that input.

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
try {
long x = sc.nextLong();
System.out.println(x + " can be fitted in:");
if (x >= Byte.MIN_VALUE && x <= Byte.MAX_VALUE) {
System.out.println("* byte");
}
if (x >= Short.MIN_VALUE && x <= Short.MAX_VALUE) {
System.out.println("* short");
}
if (x >= Integer.MIN_VALUE && x <= Integer.MAX_VALUE) {
System.out.println("* int");
}
if (x >= Long.MIN_VALUE && x <= Long.MAX_VALUE) {
System.out.println("* long");
}
} catch (Exception e) {
System.out.println(sc.next() + " can't be fitted anywhere.");
}
}
sc.close();
}
}

Some GFG Problems

  1. For Loop- primeCheck

Example 1:

Input:
n = 1
Output:
No

Example 2:

Input:
n = 2
Output:
Yes

User Task:
Your task is to complete the provided function isPrime() which should return a string “Yes” if n is prime and “No” if not.

Get Kshitij Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Constraints:
1 ≤ n ≤ 1000

Solution:

class GFG {
public static String isPrime(int n) {
if (n < 2) return "No";
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return "No";
}
return "Yes";
}

}

2. GCD of two numbers

Example 1:

Input: A = 3, B = 6
Output: 3
Explanation: GCD of 3 and 6 is 3

Example 2:

Input: A = 1, B = 1
Output: 1
Explanation: GCD of 1 and 1 is 1

Your Task:
You don’t need to read input or print anything. Complete the function gcd() which takes two positive integers as input parameters and returns an integer.

Expected Time Complexity: O(log(min(A, B)))
Expected Auxiliary Space: O(1)

Solution:

class GFG {
int gcd(int A, int B) {
if (B == 0)
return A;
return gcd(B, A % B);
}
}

3. LCM And GCD

Given two numbers A and B. The task is to find out their LCM and GCD.

Example 1:

Input:
A = 5 , B = 10
Output:
10 5
Explanation:
LCM of 5 and 10 is 10, while
thier GCD is 5.

Example 2:

Input:
A = 14 , B = 8
Output:
56 2
Explanation:
LCM of 14 and 8 is 56, while
thier GCD is 2.

Your Task:
You don’t need to read input or print anything. Your task is to complete the function lcmAndGcd() which takes an Integer N as input and returns a List of two Integers, the required LCM and GCD.

Expected Time Complexity: O(log(min(A, B))
Expected Auxiliary Space: O(1)

Constraints:
1 <= A,B <= 1018

Solution:

class GFG {
Long[] lcmAndGcd(long A, long B) {
long gcd = gcd(A, B);
long lcm = (A * B) / gcd;
Long result[] = {lcm, gcd};
return result;
}

long gcd(long A, long B) {
if (B == 0)
return A;
return gcd(B, A % B);
}
};

--

--