0% found this document useful (0 votes)
4 views3 pages

Java Loop Programs

Uploaded by

ehtsalman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Java Loop Programs

Uploaded by

ehtsalman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

1.

Print Numbers from 1 to 10 (for loop)


class Numbers1to10 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
}
}
2. Sum of First N Natural Numbers (while loop)
import java.util.Scanner;

class SumNatural {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N: ");
int n = sc.nextInt();

int i = 1, sum = 0;
while (i <= n) {
sum += i;
i++;

}
System.out.println("Sum = " + sum);
}
}
3. Multiplication Table (do-while loop)
import java.util.Scanner;

class Table {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();

int i = 1;
do {
System.out.println(n + " x " + i + " = " + (n * i));
i++;
} while (i <= 10);
}
}
4. Factorial of a Number (for loop)
import java.util.Scanner;

class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();

long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
System.out.println("Factorial = " + fact);
}
}
5. Reverse Digits of a Number (while loop)
import java.util.Scanner;

class ReverseNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();

int rev = 0;
while (n > 0) {
int digit = n % 10;
rev = rev * 10 + digit;
n = n / 10;
}
System.out.println("Reversed number = " + rev);
}
}
6. Check Prime Number (for loop)
import java.util.Scanner;

class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();

boolean isPrime = true;


if (n <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime)
System.out.println(n + " is Prime");
else
System.out.println(n + " is Not Prime");
}
}

7. Fibonacci Series (while loop)


import java.util.Scanner;

class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = sc.nextInt();

int a = 0, b = 1, count = 0;
System.out.print("Fibonacci Series: ");

while (count < n) {


System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
count++;
}
}
}

You might also like