1. Write a program to print numbers from 1 to 10?
Algorithm :
- Start
- Initialize loop counter i to 1
- Check if i is less than or equal to 10
- If yes, continue to step 4
- If no, go to step 6
- Print the value of i
- Increment i by 1 and go back to step 3
- End
Program :
public class PrintNumbers { public static void main(String[] args) { for(int i=1; i<=10; i++) { System.out.println(i); } } } |
Output :
1 2 3 4 5 6 7 8 9 10 |
Explanation :
This Java program prints numbers from 1 to 10 using a for loop. The loop starts with the variable i initialized to 1. It checks whether i is less than or equal to 10. If true, it prints the value of i and then increases i by 1. This process repeats until i becomes greater than 10, at which point the loop stops. The program then ends after printing all numbers from 1 to 10, each on a new line. |
2. Write a program to calculate the sum of first 10 natural number?
Algorithm :
- Start
- Initialize a variable sum to 0
- Initialize loop counter i to 1
- Check if i is less than or equal to 10
- If yes, go to step 5
- If no, go to step 7
- Add the value of i to sum
- Increment i by 1 and go back to step 4
- Print the value of sum
- End
Program :
public class SumNumbers { public static void main(String[] args) { int sum = 0; for(int i=1; i<=10; i++) { sum += i; } System.out.println(“Sum: ” + sum); } } |
Output :
Sum: 55 |
Explanation :
This Java program defines a class named SumNumbers with a main method, which serves as the starting point of execution. Inside the main method, an integer variable sum is initialized to 0. A for loop is used to iterate from 1 to 10, incrementing the variable i in each iteration. During each loop cycle, the current value of i is added to the sum variable. After the loop completes, sum contains the total of all integers from 1 to 10, which is 55. Finally, the program prints the result to the console with the message Sum: 55. |
3. Write a program that prompts the user to input a positive integer. It should then print the multiplication table of that number?
Algorithm :
- Start
- Create a Scanner object to read input
- Prompt the user to enter a positive integer
- Read the input number and store it in variable num
- Display a message indicating the multiplication table of num
- Initialize a loop counter i to 1
- Check if i is less than or equal to 10
- If yes, go to step 8
- If no, go to step 10
- Calculate and print num * i in the format “num x i = result”
- Increment i by 1 and go back to step 7
- End
Program :
import java.util.Scanner; public class Table { public static void main(String[] args) { Scanner console = new Scanner(System.in); int num; System.out.print(“Enter any positive integer: “); num = console.nextInt(); System.out.println(“Multiplication Table of ” + num); for(int i=1; i<=10; i++) { System.out.println(num +” x ” + i + ” = ” + (num*i) ); } } } |
Output (if the user enters 5):
Enter any positive integer: 5 Multiplication Table of 5 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 |
Explanation :
This Java program prints the multiplication table of any positive integer entered by the user. It first uses the Scanner class to take input from the user and stores it in the variable num. Then, using a for loop from 1 to 10, it multiplies num by the loop counter i in each iteration and prints the result in a formatted way. This continues until the multiplication table from num × 1 to num × 10 is printed. It’s a simple and interactive way to generate and display a multiplication table. |
4. Write a program to find the factorial value of any number entered through the keyboard?
Algorithm :
- Start
- Create a Scanner object to read input
- Prompt the user to enter a positive integer
- Read the input and store it in variable num
- Initialize variable fact to 1
- Initialize loop counter i to 1
- Check if i is less than or equal to num
- If yes, go to step 8
- If no, go to step 10
- Multiply fact by i and store the result back in fact
- Increment i by 1 and go back to step 7
- Print the value of fact
- End
Program :
import java.util.Scanner; public class FactorialDemo1 { public static void main(String[] args) { Scanner console = new Scanner(System.in); int num; int fact = 1; System.out.print(“Enter any positive integer: “); num = console.nextInt(); for(int i=1; i<=num; i++) { fact *= i; } System.out.println(“Factorial: “+ fact); } } |
Output :
Enter any positive integer: 5 Factorial: 120 |
Explanation :
This Java program calculates the factorial of a user-provided positive integer. It uses a Scanner to read the input and stores it in the variable num. It initializes the variable fact to 1 and then uses a for loop from 1 to num. In each loop iteration, the value of fact is multiplied by the loop counter i. After the loop ends, fact contains the factorial of the input number, which is then printed. For example, if the user enters 5, the output will be Factorial: 120 because 5! = 5×4×3×2×1 = 120. |
5. Write a program that takes two numbers as input from the user and calculates the result of raising the first number to the power of the second number?
Algorithm :
- Start
- Create a Scanner object to read input
- Prompt the user to enter the base number
- Read the base and store it in variable base
- Prompt the user to enter the power (exponent)
- Read the power and store it in variable power
- Initialize variable result to 1
- Initialize loop counter i to 1
- Check if i is less than or equal to power
- If yes, go to step 10
- If no, go to step 12
- Multiply result by base and store back in result
- Increment i by 1 and go back to step 9
- Print the value of result
- End
Program :
import java.util.Scanner; public class PowerDemo { public static void main(String[] args) { Scanner console = new Scanner(System.in); int base; int power; int result = 1; System.out.print(“Enter the base number “); base = console.nextInt(); System.out.print(“Enter the power “); power = console.nextInt(); for(int i = 1; i <= power; i++) { result *= base; } System.out.println(“Result: “+ result); } } |
Output :
If the user enters: Enter the base number 2 Enter the power 4 Result: 16 |
Explanation :
This Java program calculates the power of a number, i.e., base^power, using a loop. It first takes two inputs from the user: the base and the exponent (power). The result is initially set to 1. Then, a for loop runs from 1 to the value of power, multiplying result by base during each iteration. This repeated multiplication simulates exponentiation. After the loop completes, the final result (which equals base raised to the power) is printed. For example, if the user inputs base = 2 and power = 4, the output will be Result: 16. |
6. Write a program that prompts the user to input an integer and then outputs the number with the digits reversed?
Algorithm :
- Start
- Create a Scanner object to read input
- Prompt the user to enter a number
- Read the number and store it in variable number
- Initialize variable reverse to 0
- Assign number to a temporary variable temp
- Repeat while temp > 0
- Get the last digit: remainder = temp % 10
- Append the digit to reverse: reverse = reverse * 10 + remainder
- Remove the last digit from temp: temp = temp / 10
- Display the original number and its reverse
- End
Program :
import java.util.Scanner; public class ReverseNumber { public static void main(String[] args) { Scanner console = new Scanner(System.in); int number; int reverse = 0; System.out.print(“Enter the number “); number = console.nextInt(); int temp = number; int remainder = 0; while(temp>0) { remainder = temp % 10; reverse = reverse * 10 + remainder; temp /= 10; } System.out.println(“Reverse of ” + number + ” is ” + reverse); } } |
Output :
If the user enters: Enter the number 1234 Reverse of 1234 is 4321 |
Explanation :
This Java program reverses the digits of a given integer. It first takes input from the user and stores it in the variable number. The variable temp is used to preserve the original number while reversing it. The program extracts digits one by one from the end of temp using the modulus operator (% 10), appends them to reverse by shifting existing digits left (multiplying by 10), and then removes the last digit of temp using integer division (/ 10). This continues until all digits are processed. Finally, the reversed number is printed. For example, if the user inputs 1234, the output will be Reverse of 1234 is 4321. |
7. Write a program that reads a set of integers, and then prints the sum of the even and odd integers?
Algorithm :
- Start
- Create a Scanner object to read input
- Initialize evenSum and oddSum to 0
- Repeat the following steps in a do-while loop:
- Prompt the user to enter a number
- Read the number and store it in number
- Check if the number is even (number % 2 == 0)
- If yes, add it to evenSum
- If no, add it to oddSum
- Ask the user if they want to continue (enter ‘y’ or ‘n’)
- Read the user’s choice into choice
- Continue the loop while choice is ‘y’ or ‘Y’
- Print the sum of even numbers
- Print the sum of odd numbers
- End
Program :
import java.util.Scanner; public class ReadSetIntegers { public static void main(String[] args) { Scanner console = new Scanner(System.in); int number; char choice; int evenSum = 0; int oddSum = 0; do { System.out.print(“Enter the number “); number = console.nextInt(); if( number % 2 == 0) { evenSum += number; } else { oddSum += number; } System.out.print(“Do you want to continue y/n? “); choice = console.next().charAt(0); }while(choice==’y’ || choice == ‘Y’); System.out.println(“Sum of even numbers: ” + evenSum); System.out.println(“Sum of odd numbers: ” + oddSum); } } |
Output :
Enter the number 10 Do you want to continue y/n? y Enter the number 7 Do you want to continue y/n? y Enter the number 2 Do you want to continue y/n? y Enter the number 5 Do you want to continue y/n? n Sum of even numbers: 12 Sum of odd numbers: 12 |
Explanation :
This Java program reads a set of integers from the user and calculates two totals: the sum of all even numbers and the sum of all odd numbers. It uses a do-while loop to allow repeated input. After each number is entered, the program checks if it’s even or odd using the modulus operator (%). Based on the result, it adds the number to the appropriate sum (evenSum or oddSum). The loop continues as long as the user responds with ‘y’ or ‘Y’ when prompted. Once the user chooses to stop, the program displays the final sums of even and odd numbers. |
8. Write a program to check whether a given number is a palindrome or not using a loop?
Algorithm :
- Start
- Create a Scanner object to read input
- Prompt the user to enter a number
- Read the number and store it in variable N
- Store the original number in variable original
- Initialize reverse to 0
- Repeat while N is not equal to 0
- Extract the last digit: digit = N % 10
- Append the digit to reverse: reverse = reverse * 10 + digit
- Remove the last digit from N: N = N / 10
- Compare original with reverse
- If they are equal, print that it’s a palindrome
- Otherwise, print that it’s not a palindrome
- End
Program :
import java.util.Scanner; public class PalindromeNumber { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter a number: “); int N = sc.nextInt(); int original = N; int reverse = 0; while (N != 0) { int digit = N % 10; reverse = reverse * 10 + digit; N /= 10; } if (original == reverse) { System.out.println(original + ” is a Palindrome number.”); } else { System.out.println(original + ” is not a Palindrome number.”); } } } |
Output :
Enter a number: 121 121 is a Palindrome number. |
Explanation :
This Java program checks whether a given integer is a palindrome—a number that reads the same backward as forward (e.g., 121, 1331). The program first takes an integer input and stores a copy of it in original. It then reverses the number using a while loop by repeatedly extracting the last digit and building the reverse number. After the loop, it compares the reversed number with the original. If both are equal, the number is a palindrome; otherwise, it’s not. For example, if the input is 12321, the output will state that it is a palindrome. |
9. Write a program to count the number of digits in a given number using a loop?
Algorithm :
- Start
- Create a Scanner object to read input
- Prompt the user to enter a number
- Read the number and store it in variable N
- Initialize count to 0
- Repeat while N is not equal to 0
- Divide N by 10 (remove the last digit)
- Increment count by 1
- Print the value of count
- End
Program :
import java.util.Scanner; public class CountDigits { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter a number: “); int N = sc.nextInt(); int count = 0; while (N != 0) { N /= 10; count++; } System.out.println(“Number of digits: ” + count); } } |
Output :
Enter a number: 12345 Number of digits: 5 |
Explanation :
This Java program counts how many digits are in a given integer. It reads an integer input from the user and uses a while loop to divide the number by 10 repeatedly, effectively removing the last digit in each iteration. Each time a digit is removed, a counter is incremented. When the number becomes 0, the loop ends, and the program prints the total count of digits. For example, if the input is 4567, the output will be Number of digits: 4. |
10. Write a program to print all the prime numbers between 1 and N using a loop?
Algorithm :
- Start
- Create a Scanner object to read input
- Prompt the user to enter a number
- Read the number and store it in variable N
- Loop from num = 2 to N
- Set isPrime = true
- Loop from i = 2 to num / 2
- If num % i == 0, set isPrime = false and break the loop
- After inner loop, if isPrime is true, print num
- End
Program :
import java.util.Scanner; public class PrimeNumbersBetween1toN { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter a number: “); int N = sc.nextInt(); for (int num = 2; num <= N; num++) { boolean isPrime = true; for (int i = 2; i <= num / 2; i++) { if (num % i == 0) { isPrime = false; break; } } if (isPrime) { System.out.print(num + ” “); } } } } |
Output :
Enter a number: 20 2 3 5 7 11 13 17 19 |
Explanation :
This Java program prints all prime numbers between 1 and a user-specified number N. A prime number is a number greater than 1 that is divisible only by 1 and itself. The program uses two nested loops: the outer loop iterates through all numbers from 2 to N, and the inner loop checks if the current number is divisible by any number from 2 to half of itself. If it finds a divisor, it sets isPrime to false. If no divisors are found, the number is printed as prime. For example, if the input is 10, the output will be: 2 3 5 7. |
11. Write a program to find the greatest common divisor (GCD) of two numbers using a loop?
Algorithm :
- Start
- Create a Scanner object to read input
- Prompt the user to enter two numbers
- Read the two numbers and store them in variables a and b
- Repeat the following steps while a is not equal to b:
- If a > b, set a = a – b
- Else, set b = b – a
- When the loop ends, print a (or b) as the GCD
- End
Program :
import java.util.Scanner; public class Demo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter two numbers: “); int a = sc.nextInt(); int b = sc.nextInt(); while (a != b) { if (a > b) { a -= b; } else { b -= a; } } System.out.println(“GCD is: ” + a); } } |
Output :
Enter two numbers: 36 60 GCD is: 12 |
Explanation :
This Java program calculates the Greatest Common Divisor (GCD) of two numbers using the subtraction-based version of the Euclidean algorithm. It continuously subtracts the smaller number from the larger one until both numbers become equal. That final equal value is the GCD. For example, if the user inputs 48 and 18, the program keeps subtracting until both values reach 6, which is the GCD. This method is simple and doesn’t require division or modulus, making it easy to understand, though it’s less efficient than the modulo version for larger numbers. |
12. Write a program to print a pyramid pattern using loops?
Algorithm :
- Start
- Create a Scanner object to read input
- Prompt the user to enter a number
- Read the number and store it in variable N
- Loop from i = 1 to N (for each row of the pyramid):
- Loop from j = N down to i + 1, print a space ” ” to center the stars
- Loop from j = 1 to 2 * i – 1, print an asterisk “*”
- Move to the next line using System.out.println()
- End
Program :
import java.util.Scanner; public class PyramidPattern { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter a number: “); int N = sc.nextInt(); for (int i = 1; i <= N; i++) { for (int j = N; j > i; j–) { System.out.print(” “); } for (int j = 1; j <= (2 * i – 1); j++) { System.out.print(“*”); } System.out.println(); } } } |
Output :
Enter a number: 5 * *** ***** ******* ********* |
Explanation :
This Java program prints a centered pyramid pattern of asterisks based on the number of rows N entered by the user. It uses nested loops: the first inner loop prints spaces to align the stars centrally, and the second inner loop prints an increasing number of stars based on the row number (2 * i – 1 gives the correct number of stars for a symmetric pyramid). After printing each row, the program moves to the next line. For example, if the user enters 5, the program will output a 5-row pyramid with * aligned in the center. |
13. Write a program to print a diamond pattern using loops?
Algorithm :
- Start
- Declare necessary variables: N, i, j
- Create a Scanner object to take input from the user
- Prompt the user to enter a number N
- Read the value of N
- Top Half of the Diamond (including the middle row):
- Repeat for i = 1 to N:
- Repeat for j = N down to i + 1:
- Print a space ” ” (for alignment)
- Repeat for j = 1 to (2 * i – 1):
- Print a star “*”
- Print a newline (move to the next row)
- Repeat for j = N down to i + 1:
- Repeat for i = 1 to N:
- Bottom Half of the Diamond:
- Repeat for i = N – 1 down to 1:
- Repeat for j = N down to i + 1:
- Print a space ” ” (for alignment)
- Repeat for j = 1 to (2 * i – 1):
- Print a star “*”
- Print a newline (move to the next row)
- Repeat for j = N down to i + 1:
- Repeat for i = N – 1 down to 1:
- End
Program :
import java.util.Scanner; public class DiamondPattern { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter a number: “); int N = sc.nextInt(); for (int i = 1; i <= N; i++) { for (int j = N; j > i; j–) { System.out.print(” “); } for (int j = 1; j <= (2 * i – 1); j++) { System.out.print(“*”); } System.out.println(); } for (int i = N – 1; i >= 1; i–) { for (int j = N; j > i; j–) { System.out.print(” “); } for (int j = 1; j <= (2 * i – 1); j++) { System.out.print(“*”); } System.out.println(); } } } |
Output :
Enter a number: 5 * *** ***** ******* ********* ******* ***** *** * |
Explanation :
The program prints a symmetrical diamond pattern using asterisks (*). It takes a number N as input, representing the number of rows in the top half (including the middle). The first loop builds the upper part of the diamond by printing decreasing spaces followed by increasing stars. The second loop constructs the bottom half by reversing the process—spaces increase and stars decrease. This results in a centered diamond shape on the console. |
14. Write a program to print the Fibonacci series up to N terms using a loop?
Algorithm :
- Start
- Declare variables: N, first = 0, second = 1, next
- Create a Scanner object to read input
- Prompt the user: “Enter the number of terms”
- Read the input value N
- Print the initial two terms: 0 and 1
- Loop from i = 3 to N:
- Calculate next = first + second
- Print nextUpdate first = second
- Update second = next
- End
Program :
import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter the number of terms: “); int N = sc.nextInt(); int first = 0, second = 1; System.out.print(“Fibonacci series: ” + first + ” ” + second + ” “); for (int i = 3; i <= N; i++) { int next = first + second; System.out.print(next + ” “); first = second; second = next; } } } |
Output :
Enter the number of terms: 7 Fibonacci series: 0 1 1 2 3 5 8 |
Explanation :
This program generates the Fibonacci series up to N terms, where each term is the sum of the two preceding ones. It starts with the first two fixed values 0 and 1. Then, using a for loop, it calculates the next term by adding the previous two and updates the values accordingly. This process continues until the desired number of terms is printed in the sequence. |
15. Write a program to count the number of vowels and consonants in a given string?
Algorithm :
- Start
- Declare variables: vowels = 0, consonants = 0
- Create a Scanner object to read input
- Prompt the user: “Enter a string”
- Read the input string and convert it to lowercase
- Loop through each character of the string:
- Extract character at position i using charAt(i)
- Check if the character is a letter (‘a’ to ‘z’):
- If it is a vowel (a, e, i, o, u), increment vowels
- Else, increment consonants
- Display the values of vowels and consonants
- End
Program :
import java.util.Scanner; public class VowelConsonantCount { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter a string: “); String str = sc.nextLine().toLowerCase(); int vowels = 0, consonants = 0; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch >= ‘a’ && ch <= ‘z’) { if (ch == ‘a’ || ch == ‘e’ || ch == ‘i’ || ch == ‘o’ || ch == ‘u’) { vowels++; } else { consonants++; } } } System.out.println(“Vowels: ” + vowels); System.out.println(“Consonants: ” + consonants); } } |
Output :
If the user enters: Enter a string: Hello World Vowels: 3 Consonants: 7 |
Explanation :
This program reads a string input from the user, converts it to lowercase, and counts how many vowels and consonants it contains. It ignores non-alphabetic characters (like digits or symbols) by checking if the character lies between ‘a’ and ‘z’. If it’s a vowel (a, e, i, o, u), it increments the vowel counter; otherwise, it increments the consonant counter. Finally, it prints the counts of both vowels and consonants. |
16. Write a program to print a square star pattern of given size?
Algorithm :
- Start
- Declare variable N for the size of the square
- Create a Scanner object to read input
- Prompt the user: “Enter the size of the square”
- Read the value of N
- Loop from i = 1 to N (for each row):
- Loop from j = 1 to N (for each column in the row):
- Print “* ” (star followed by a space)
- Print a newline to move to the next row
- Loop from j = 1 to N (for each column in the row):
- End
Program :
import java.util.Scanner; public class SquareStarPattern { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter the size of the square: “); int N = sc.nextInt(); for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { System.out.print(“* “); } System.out.println(); } } } |
Output :
If the user enters: Enter the size of the square: 4 * * * * * * * * * * * * * * * * |
Explanation :
The program begins by importing the Scanner class to enable user input. Inside the main method, it prompts the user to enter the size of the square and stores the input in the variable N . It then uses a nested for loop to print a square pattern made of asterisks. The outer loop runs from 1 to N , controlling the number of rows. The inner loop also runs from 1 to N , printing * on each iteration to form columns. After each row, System.out.println() is used to move to the next line, resulting in a square of asterisks of size N x N . |
17. Write a program to print a right-angled triangle pattern of numbers?
Algorithm :
- Start
- Declare variable N to store the number of rows
- Create a Scanner object to read input from the user
- Prompt the user: “Enter a number”
- Read the value of N
- Loop from i = 1 to N (each row of the triangle):
- Loop from j = 1 to i:
- Print j followed by a space
- Print a newline to move to the next row
- Loop from j = 1 to i:
- End
Program :
import java.util.Scanner; public class RightAngledTrianglePattern { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter a number: “); int N = sc.nextInt(); for (int i = 1; i <= N; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + ” “); } System.out.println(); } } } |
Output :
Enter a number: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 |
Explanation :
This program prints a right-angled triangle made of numbers. The user inputs a number N, which determines the number of rows. Each row contains an increasing sequence of numbers starting from 1 up to the current row number i. This is achieved using a nested loop where the outer loop controls the rows and the inner loop prints the numbers from 1 to i. The output is a number triangle aligned to the left. |
18. Write a program to print a pyramid pattern of numbers?
Algorithm :
- Start
- Declare variable N for the number of rows
- Create a Scanner object to take input
- Prompt the user: “Enter the number of rows”
- Read the value of N
- Loop from i = 1 to N (to print each row):
- Loop from j = N down to i + 1:
- Print a space ” ” for alignment
- Loop from j = 1 to (2 * i – 1):
- Print the number i
- Print a newline to move to the next row
- Loop from j = N down to i + 1:
- End
Program :
import java.util.Scanner; public class NumberPyramid { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter the number of rows: “); int N = sc.nextInt(); for (int i = 1; i <= N; i++) { for (int j = N; j > i; j–) { System.out.print(” “); } for (int j = 1; j <= (2 * i – 1); j++) { System.out.print(i); } System.out.println(); } } } |
Output :
Enter the number of rows: 5 1 222 33333 4444444 555555555 |
Explanation :
This program prints a centered number pyramid, where each row contains repeated digits equal to the row number. The user provides the number of rows N, and for each row i, the program first prints spaces to center-align the numbers, then prints 2 * i – 1 instances of the number i. This forms a symmetric pyramid shape that grows row by row with increasing numbers. |
19. Write a program to print a hollow square pattern of stars?
Algorithm :
- Start
- Declare variable N to store the size of the square
- Create a Scanner object to read input
- Prompt the user: “Enter the size of the square”
- Read the value of N
- Loop from i = 1 to N (each row of the square):
- Loop from j = 1 to N (each column in the row):
- If i == 1, i == N, j == 1, or j == N:
- Print “* ” (border of the square)
- Else:
- Print ” ” (space inside the square)
- If i == 1, i == N, j == 1, or j == N:
- Print a newline to move to the next row
- Loop from j = 1 to N (each column in the row):
- 7. End
Program :
import java.util.Scanner; public class HollowSquarePattern { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter the size of the square: “); int N = sc.nextInt(); for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if (i == 1 || i == N || j == 1 || j == N) { System.out.print(“* “); } else { System.out.print(” “); } } System.out.println(); } } } |
Output :
Enter the size of the square: 5 * * * * * * * * * * * * * * * * |
Explanation :
This program prints a hollow square pattern using stars (*). The user inputs the size N, which determines both the number of rows and columns. The outer edges (first and last rows/columns) are filled with stars to form the border, while the inner part remains empty, filled with spaces. This is achieved using condition checks inside nested loops, creating a visually clean hollow square. |
20. Write a program to print a right-aligned number pyramid pattern?
Algorithm :
- Start
- Declare variable N to store the height of the pyramid
- Create a Scanner object to read input
- Prompt the user: “Enter the height of the pyramid”
- Read the value of N
- Loop from i = 1 to N (for each row):
- Loop from j = 1 to N – i:
- Print a space ” ” (to right-align the numbers)
- Loop from j = 1 to i:
- Print the value of j (numbers increasing from 1 to i)
- Print a newline to move to the next row
- Loop from j = 1 to N – i:
- End
Program :
import java.util.Scanner; public class RightAlignedNumberPyramid { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter the height of the pyramid: “); int N = sc.nextInt(); for (int i = 1; i <= N; i++) { for (int j = 1; j <= N – i; j++) { System.out.print(” “); } for (int j = 1; j <= i; j++) { System.out.print(j); } System.out.println(); } } } |
Output :
Enter the height of the pyramid: 5 1 12 123 1234 12345 |
Explanation :
This program prints a right-aligned number pyramid. The user inputs the height N, and the pyramid is built row by row. For each row i, it first prints N – i spaces to push the numbers to the right, then prints numbers from 1 to i. This forms a triangular shape aligned to the right side of the console, with each row showing an increasing sequence of numbers. |
21. Write a program to inverted Right-Angled Triangle?
Algorithm :
- Start
- Declare variable n to store the number of rows
- Create a Scanner object to read input
- Prompt the user: “Enter rows”
- Read the value of n
- Loop from i = n down to 1 (for each row from top to bottom):
- Loop from j = 1 to i:
- Print “* ” (a star followed by a space)
- Print a newline to move to the next row
- Loop from j = 1 to i:
- End
Program :
import java.util.Scanner; public class InvertedRightTriangle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter rows: “); int n = sc.nextInt(); for (int i = n; i >= 1; i–) { for (int j = 1; j <= i; j++) { System.out.print(“* “); } System.out.println(); } } } |
Output :
Enter rows: 4 * * * * * * * * * * |
Explanation :
This program prints an inverted right-angled triangle made of stars (*). The user inputs the number of rows n. The outer loop starts from n and decreases down to 1, which determines how many stars are printed on each line. The inner loop prints stars from 1 to i for each row. As a result, the triangle starts with the maximum number of stars at the top and reduces one by one on each new line. |
22. Write a program to create a Floyd’s Triangle?
Algorithm :
- Start
- Declare variables:
- n to store number of rows
- num = 1 to track the current number to print
- Create a Scanner object to read input
- Prompt the user: “Enter rows”
- Read the value of n
- Loop from i = 1 to n (each row):
- Loop from j = 1 to i:
- Print the value of num
- Increment num by 1
- Print a newline to move to the next row
- Loop from j = 1 to i:
- End
Program :
import java.util.Scanner; public class FloydTriangle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter rows: “); int n = sc.nextInt(); int num = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print(num++ + ” “); } System.out.println(); } } } |
Output :
Enter rows : 4 1 2 3 4 5 6 7 8 9 10 |
Explanation :
The program starts by importing the Scanner class to take input from the user. It prompts the user to enter the number of rows for the Floyd’s Triangle and stores the input in variable n. The variable num is initialized to 1 and will be used to print consecutive numbers. A nested for loop is used, where the outer loop runs from 1 to n, representing each row. The inner loop runs from 1 to i, printing the current value of num and incrementing it. After each row, the program prints a newline to format the triangle structure. |
23. Write a program to create a binary triangle?
Algorithm :
- Start
- Declare variable n to store the number of rows
- Create a Scanner object to read input
- Prompt the user: “Enter rows”
- Read the value of n
- Loop from i = 1 to n (for each row):
- Set val = i % 2 → this determines whether to start the row with 0 or 1 (alternating)
- Loop from j = 1 to i:
- Print val
- Flip val using val = 1 – val (switches between 0 and 1)
- Print a newline to move to the next row
- End
Program :
import java.util.Scanner; public class BinaryTriangle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(“Enter rows: “); int n = sc.nextInt(); for (int i = 1; i <= n; i++) { int val = i % 2; for (int j = 1; j <= i; j++) { System.out.print(val + ” “); val = 1 – val; } System.out.println(); } } } |
Output :
Enter rows: 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 |
Explanation :
This program prints a binary triangle pattern where each row consists of alternating 1s and 0s. The number of elements in each row increases with the row number. The starting value alternates based on the row number: odd rows start with 1, and even rows start with 0. The flipping of val in each iteration ensures alternating binary digits in each row. This creates a visually interesting and mathematically structured triangle. |