Java Loops Programs
1. Write a Program to print the following Pattern--
****
***
**
*
Program:
// Akash Suryawanshi
// 25-Nov-2022
public class loops {
public static void main(String[] args) {
int n = 4;
for(int i=n;i>0;i--){
for(int j=0;j<i;j++){
System.out.print("*");
}
System.out.print("\n");
}
}
}
Output:
****
***
**
*
2. Write a program to sum first n even numbers using a while loop.
Program:
// Akash Suryawanshi
// 25-Nov-2022
public class loops {
public static void main(String[] args) {
int sum = 0;
int n = 5;
for (int i = 0; i < n; i++) {
sum = sum+(2*i);
}
System.out.println("Sum of even number: " +sum);
}
}
Output:
Sum of even number: 20
3. Write a program to print the multiplication table of a given number n.
Program:
// Akash Suryawanshi
// 25-Nov-2022
public class loops {
public static void main(String[] args) {
int n = 5;
for(int i=1;i<=10;i++){
System.out.printf("%d X %d = %d\n" ,n,i ,n*i );
}
}
}
Output:
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
4. Write a program to find the factorial of a given number using for loop
Program:
// Akash Suryawanshi
// 25-Nov-2022
public class loops {
public static void main(String[] args) {
int n = 5;
int factorial=1;
for(int i = 1;i<=n;i++){
factorial *=i;
}
System.out.println("Factorial of a given number is: " +factorial);
}
}
Output:
Factorial of a given number is: 120
5. Write a program Display sum of n Natural Numbers.
Program:
// Akash Suryawanshi
// 25-Nov-2022
public class loops {
public static void main(String[] args) {
int sum= 0;
int n = 10;
int i;
for(i = 1; i<=n;i++){
sum += i;
}
System.out.println("Sum of natural numbers is: "+sum);
}
}
Output:
Sum of natural numbers is: 55
Comments
Post a Comment