Java Programs - Pattern and ASCII
1(a) Triangle Pattern with Repeating Numbers
public class TrianglePattern {
public static void main(String[] args) {
int n = 5; // you can change n to any value
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
1(b) Inverted Triangle Pattern with Repeating Numbers
public class InvertedTrianglePattern {
public static void main(String[] args) {
int n = 5; // you can change n to any value
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
2(a) Incremental Number Triangle
public class NumberTriangle {
public static void main(String[] args) {
int n = 5; // you can change n to any value
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
2(b) Inverted Hash Triangle
public class HashTriangle {
public static void main(String[] args) {
int n = 5; // you can change n to any value
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("# ");
}
System.out.println();
}
}
}
3) Sum of ASCII values of 10 characters
import java.util.Scanner;
public class ASCIISum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] chars = new char[10];
int sum = 0;
System.out.println("Enter 10 characters:");
for (int i = 0; i < 10; i++) {
chars[i] = sc.next().charAt(0);
sum += (int) chars[i];
}
System.out.println("Sum of ASCII values: " + sum);
}
}
4) Reverse ASCII Code and Display Character
import java.util.Scanner;
public class ReverseASCII {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = sc.next().charAt(0);
int ascii = (int) ch;
int reversedAscii = 0;
while (ascii > 0) {
int digit = ascii % 10;
reversedAscii = reversedAscii * 10 + digit;
ascii = ascii / 10;
}
if (reversedAscii >= 0 && reversedAscii <= 127) {
char result = (char) reversedAscii;
System.out.println("Reversed ASCII value: " + reversedAscii);
System.out.println("Equivalent character: " + result);
} else {
System.out.println("Reversed value not a valid ASCII character.");
}
}
}