1.Write a program to find sum of digits of a given number.
(using recursion)
import java.util.*;
public class Main
{
public static long sod(long N)
{
if(N==0){
return 0;
}
else{
return N%10+sod(N/10);
}
}
public static void main(String[] args)
{
Scanner inp = new Scanner(System.in);
long N = inp.nextLong();
System.out.print(sod(N));
}
}
2.check if a string is palinedrome
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get input from the user
System.out.print("Enter a string: ");
String str = scanner.nextLine();
// Check if the string is a palindrome
int left = 0;
int right = str.length() - 1;
boolean isPalindrome = true;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
if (isPalindrome) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
// Convert string to array and swap elements
char[] charArray = str.toCharArray();
left = 0;
right = charArray.length - 1;
while (left < right) {
// Swap elements
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
left++;
right--;
}
// Print the array after swapping
System.out.println("Array after swapping elements: ");
System.out.println(charArray);
scanner.close();
}
}
3.find maximum subarray sum of an array
import java.util.Scanner;
public class GfG {
static int maxSubarraySum(int[] arr) {
int maxSum = arr[0];
int currentSum = arr[0];
for (int i = 1; i < arr.length; i++) {
currentSum = Math.max(arr[i], currentSum + arr[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the size of the array
int n = scanner.nextInt();
// Initialize the array
int[] arr = new int[n];
// Get input from the user for the array elements
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
// Find and print the maximum subarray sum
System.out.println("Maximum Subarray Sum: " + maxSubarraySum(arr));
scanner.close();
}
}