21.
Sum of First N Natural Numbers
public class SumNatural {
public static void main(String[] args) {
int n = 10, sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
System.out.println("Sum of first " + n + " natural numbers: " + sum);
// Output: Sum of first 10 natural numbers: 55
22. Count Digits in a Number
public class CountDigits {
public static void main(String[] args) {
int num = 12345, count = 0;
while (num != 0) {
num /= 10;
count++;
System.out.println("Number of digits: " + count);
// Output: Number of digits: 5
23. Table of a Number
public class MultiplicationTable {
public static void main(String[] args) {
int num = 5;
for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
}
// Output:
// 5 x 1 = 5
// 5 x 2 = 10
// ...
// 5 x 10 = 50
24. Print Alphabets A to Z
public class PrintAlphabets {
public static void main(String[] args) {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
// Output: A B C D ... Z
25. Convert Lowercase to Uppercase
public class ToUpperCase {
public static void main(String[] args) {
char ch = 'b';
char upper = Character.toUpperCase(ch);
System.out.println("Uppercase: " + upper);
// Output: Uppercase: B
26. Reverse a String
public class ReverseString {
public static void main(String[] args) {
String str = "hello", rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev += str.charAt(i);
}
System.out.println("Reversed: " + rev);
// Output: Reversed: olleh
27. Check Palindrome String
public class PalindromeString {
public static void main(String[] args) {
String str = "madam", rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev += str.charAt(i);
if (str.equals(rev))
System.out.println(str + " is a palindrome");
else
System.out.println(str + " is not a palindrome");
// Output: madam is a palindrome
28. Count Vowels in a String
public class CountVowels {
public static void main(String[] args) {
String str = "Hello World";
int count = 0;
str = str.toLowerCase();
for (char ch : str.toCharArray()) {
if ("aeiou".indexOf(ch) != -1) count++;
System.out.println("Number of vowels: " + count);
}
// Output: Number of vowels: 3
29. Sum of Array Elements
public class ArraySum {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : arr) {
sum += num;
System.out.println("Sum of array elements: " + sum);
// Output: Sum of array elements: 15
30. Find Largest Element in Array
public class LargestInArray {
public static void main(String[] args) {
int[] arr = {5, 10, 25, 15, 20};
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
System.out.println("Largest element: " + max);
// Output: Largest element: 25