0% found this document useful (0 votes)
31 views32 pages

Panda

Uploaded by

madhulikapaluri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views32 pages

Panda

Uploaded by

madhulikapaluri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

REVESE AN ARRAY

import java.util.Arrays;

public class ReverseArray {

public static void main(String[] args) {

int[] numbers = {1, 2, 3, 4, 5, 6};

System.out.println("Original Array: " + Arrays.toString(numbers));

reverseArray(numbers);

System.out.println("Reversed Array: " + Arrays.toString(numbers));

public static void reverseArray(int[] array) {

int start = 0; // Start pointer

int end = array.length - 1; // End pointer

while (start < end) {

// Swap elements at start and end

int temp = array[start];

array[start] = array[end];

array[end] = temp;

// Move the pointers

start++;

end--;

}
FINDING SMALLEST AND LARGEST IN AN ARRAY

public class MinMaxInArray {

public static void main(String[] args) {

int[] numbers = {15, 42, 3, 17, 8, 90, 1};

// Initialize variables for smallest and largest

int smallest = numbers[0];

int largest = numbers[0];

// Iterate through the array

for (int number : numbers) {

if (number < smallest) {

smallest = number;

if (number > largest) {

largest = number;

// Print the results

System.out.println("Smallest number: " + smallest);

System.out.println("Largest number: " + largest);

SUM OF ELEMENTS

public class ArraySum {

public static void main(String[] args) {

int[] numbers = {10, 20, 30, 40, 50};

// Calculate sum of array elements

int sum = calculateSum(numbers);


System.out.println("Sum of elements in the array: " + sum);

public static int calculateSum(int[] array) {

int sum = 0; // Initialize sum to 0

// Iterate through the array

for (int num : array) {

sum += num; // Add each element to the sum

return sum;

Factorial

public class Factorial {

public static void main(String[] args) {

int number = 5; // You can change this number to test with other values

// Calculate factorial using an iterative approach

long result = factorial(number);

System.out.println("Factorial of " + number + " is: " + result);

public static long factorial(int n) {

long result = 1; // Initialize result as 1 (since factorial of 0 is 1)

// Iterate from 1 to n and multiply the numbers

for (int i = 1; i <= n; i++) {


result *= i;

return result;

RECUSRIVE IN FACTORIAL

public class Factorial {

public static void main(String[] args) {

int number = 5; // You can change this number to test with other values

// Calculate factorial using recursion

long result = factorial(number);

System.out.println("Factorial of " + number + " is: " + result);

// Recursive method to calculate factorial

public static long factorial(int n) {

if (n == 0) {

return 1; // Base case: 0! = 1

} else {

return n * factorial(n - 1); // Recursive case

// Calculate maximum product of two integers

import java.util.Arrays;

public class MaxProduct {

public static void main(String[] args) {


int[] numbers = {1, 10, -5, 1, -100};

// Calculate maximum product of two integers

int result = maxProduct(numbers);

System.out.println("Maximum product of two integers: " + result);

public static int maxProduct(int[] array) {

// Sort the array

Arrays.sort(array);

// Compare the product of two largest numbers and two smallest numbers

int n = array.length;

int product1 = array[n - 1] * array[n - 2]; // Product of the two largest numbers

int product2 = array[0] * array[1]; // Product of the two smallest numbers (negative)

// Return the maximum product

return Math.max(product1, product2);

ANAGRAM

import java.util.Arrays;

public class AnagramCheck {

public static void main(String[] args) {

String str1 = "listen";

String str2 = "silent";

// Check if the strings are anagrams

boolean result = areAnagrams(str1, str2);


System.out.println("Are the two strings anagrams? " + result);

public static boolean areAnagrams(String str1, String str2) {

// If lengths are different, they cannot be anagrams

if (str1.length() != str2.length()) {

return false;

// Convert strings to char arrays and sort them

char[] arr1 = str1.toCharArray();

char[] arr2 = str2.toCharArray();

Arrays.sort(arr1);

Arrays.sort(arr2);

// Compare sorted arrays

return Arrays.equals(arr1, arr2);

PALINDROME

public class PalindromeCheck {

public static void main(String[] args) {

String str = "madam"; // You can test with other strings as well

// Check if the string is a palindrome

boolean result = isPalindrome(str);

System.out.println("Is the string a palindrome? " + result);

}
public static boolean isPalindrome(String str) {

// Remove spaces and convert to lowercase for uniformity

str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

// Initialize pointers to start and end of the string

int left = 0;

int right = str.length() - 1;

// Compare characters from both ends of the string

while (left < right) {

if (str.charAt(left) != str.charAt(right)) {

return false; // If characters don't match, it's not a palindrome

left++;

right--;

return true; // If loop completes, it's a palindrome

PATTERNS

In Java, patterns can be printed using loops. Common patterns include stars (*), numbers, and
alphabets arranged in different shapes, such as triangles, squares, and pyramids.

Below are some popular star patterns with Java code examples:

1. Right-Angled Triangle (Star Pattern)

**

***

****

*****
Java Code:

public class StarPattern {

public static void main(String[] args) {

int n = 5; // Number of rows

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

System.out.print("*");

System.out.println(); // Move to the next line

2. Inverted Right-Angled Triangle

*****

****

***

**

Java Code:

public class InvertedTriangle {

public static void main(String[] args) {

int n = 5; // Number of rows

for (int i = n; i >= 1; i--) {

for (int j = 1; j <= i; j++) {

System.out.print("*");

System.out.println(); // Move to the next line

3. Pyramid Pattern
*

***

*****

*******

*********

Java Code:

public class PyramidPattern {

public static void main(String[] args) {

int n = 5; // Number of rows

for (int i = 1; i <= n; i++) {

// Print spaces

for (int j = i; j < n; j++) {

System.out.print(" ");

// Print stars

for (int j = 1; j <= (2 * i - 1); j++) {

System.out.print("*");

System.out.println(); // Move to the next line

4. Inverted Pyramid

*********

*******

*****

***

Java Code:

public class InvertedPyramid {

public static void main(String[] args) {


int n = 5; // Number of rows

for (int i = n; i >= 1; i--) {

// Print spaces

for (int j = i; j < n; j++) {

System.out.print(" ");

// Print stars

for (int j = 1; j <= (2 * i - 1); j++) {

System.out.print("*");

System.out.println(); // Move to the next line

5. Diamond Pattern

***

*****

*******

*********

*******

*****

***

Java Code:

public class DiamondPattern {

public static void main(String[] args) {

int n = 5; // Number of rows for the upper part

// Upper half of the diamond

for (int i = 1; i <= n; i++) {

// Print spaces
for (int j = i; j < n; j++) {

System.out.print(" ");

// Print stars

for (int j = 1; j <= (2 * i - 1); j++) {

System.out.print("*");

System.out.println(); // Move to the next line

// Lower half of the diamond

for (int i = n - 1; i >= 1; i--) {

// Print spaces

for (int j = i; j < n; j++) {

System.out.print(" ");

// Print stars

for (int j = 1; j <= (2 * i - 1); j++) {

System.out.print("*");

System.out.println(); // Move to the next line

6. Hollow Square Pattern

*****

* *

* *

* *

*****

Java Code:
public class HollowSquarePattern {

public static void main(String[] args) {

int n = 5; // Size of the square

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();

7. Floyd’s Triangle (Number Pattern)

23

456

7 8 9 10

11 12 13 14 15

Java Code:

public class FloydsTriangle {

public static void main(String[] args) {

int n = 5; // Number of rows

int num = 1; // Starting number

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(num + " ");

num++;

}
System.out.println(); // Move to the next line

1. Reverse a String

public class ReverseString {

public static void main(String[] args) {

String str = "hello";

String reversed = new StringBuilder(str).reverse().toString();

System.out.println("Reversed String: " + reversed);

2. Check for Palindrome

public class Palindrome {

public static void main(String[] args) {

String str = "madam";

String reversed = new StringBuilder(str).reverse().toString();

if (str.equals(reversed)) {

System.out.println("Palindrome");

} else {

System.out.println("Not a Palindrome");

3. Find the Largest and Smallest Number in an Array

public class MinMax {

public static void main(String[] args) {

int[] arr = {4, 1, 9, 3, 6};

int max = arr[0], min = arr[0];

for (int num : arr) {


if (num > max) max = num;

if (num < min) min = num;

System.out.println("Largest: " + max);

System.out.println("Smallest: " + min);

4. Count Occurrences of a Character in a String

public class CountChar {

public static void main(String[] args) {

String str = "hello world";

char ch = 'l';

int count = 0;

for (char c : str.toCharArray()) {

if (c == ch) {

count++;

System.out.println("Occurrences of '" + ch + "': " + count);

5. Factorial of a Number

public class Factorial {

public static void main(String[] args) {

int num = 5;

int fact = 1;

for (int i = 1; i <= num; i++) {


fact *= i;

System.out.println("Factorial of " + num + " is: " + fact);

6. Fibonacci Series

public class Fibonacci {

public static void main(String[] args) {

int n = 5;

int a = 0, b = 1;

System.out.print(a + " " + b + " ");

for (int i = 2; i < n; i++) {

int c = a + b;

System.out.print(c + " ");

a = b;

b = c;

7. Find the Second Largest Element in an Array

public class SecondLargest {

public static void main(String[] args) {

int[] arr = {5, 2, 9, 1, 6};

int max = Integer.MIN_VALUE, secondMax = Integer.MIN_VALUE;

for (int num : arr) {

if (num > max) {

secondMax = max;
max = num;

} else if (num > secondMax && num != max) {

secondMax = num;

System.out.println("Second Largest: " + secondMax);

8. Prime Number Check

public class PrimeNumber {

public static void main(String[] args) {

int num = 7;

boolean isPrime = true;

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) {

isPrime = false;

break;

System.out.println(isPrime ? "Prime" : "Not Prime");

9. Find the Missing Number in an Array

public class MissingNumber {

public static void main(String[] args) {

int[] arr = {1, 2, 4, 5};

int n = 5; // Array should contain numbers from 1 to n

int total = n * (n + 1) / 2;
int sum = 0;

for (int num : arr) {

sum += num;

System.out.println("Missing number: " + (total - sum));

10. Sum of Digits of a Number

public class SumOfDigits {

public static void main(String[] args) {

int num = 1234;

int sum = 0;

while (num > 0) {

sum += num % 10;

num /= 10;

System.out.println("Sum of digits: " + sum);

11. Armstrong Number

public class Armstrong {

public static void main(String[] args) {

int num = 153;

int sum = 0, temp = num, digits = String.valueOf(num).length();

while (temp != 0) {

int remainder = temp % 10;


sum += Math.pow(remainder, digits);

temp /= 10;

System.out.println(sum == num ? "Armstrong" : "Not Armstrong");

12. Count Vowels and Consonants in a String

public class VowelConsonantCount {

public static void main(String[] args) {

String str = "hello";

int vowels = 0, consonants = 0;

for (char ch : str.toLowerCase().toCharArray()) {

if (ch >= 'a' && ch <= 'z') {

if ("aeiou".indexOf(ch) != -1) {

vowels++;

} else {

consonants++;

System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);

13. Find the GCD (Greatest Common Divisor)

public class GCD {

public static void main(String[] args) {

int a = 12, b = 15;


while (b != 0) {

int temp = b;

b = a % b;

a = temp;

System.out.println("GCD: " + a);

14. Sort an Array

import java.util.Arrays;

public class SortArray {

public static void main(String[] args) {

int[] arr = {5, 2, 9, 1, 6};

Arrays.sort(arr);

System.out.println("Sorted Array: " + Arrays.toString(arr));

15. Sum of the Elements in an Array

public class SumArray {

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);


}

16. Reverse an Array

public class ReverseArray {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4};

int start = 0, end = arr.length - 1;

while (start < end) {

int temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

System.out.println("Reversed Array: " + Arrays.toString(arr));

17. Matrix Multiplication

public class MatrixMultiplication {

public static void main(String[] args) {

int[][] matrix1 = {{1, 2}, {3, 4}};

int[][] matrix2 = {{5, 6}, {7, 8}};

int[][] result = new int[2][2];

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++) {

result[i][j] = matrix1[i][0] * matrix2[0][j] + matrix1[i][1] * matrix2[1][j];

}
System.out.println("Matrix Multiplication Result: ");

for (int[] row : result) {

System.out.println(Arrays.toString(row));

18. Find the Longest Substring Without Repeating Characters

import java.util.HashSet;

public class LongestSubstring {

public static void main(String[] args) {

String str = "abcabcbb";

int maxLength = 0;

HashSet<Character> set = new HashSet<>();

int left = 0;

for (int right = 0; right < str.length(); right++) {

while (set.contains(str.charAt(right))) {

set.remove(str.charAt(left));

left++;

set.add(str.charAt(right));

maxLength = Math.max(maxLength, right - left + 1);

System.out.println("Longest Substring Length: " + maxLength);

19. Find if Two Strings are Anagrams

import java.util.Arrays;
public class Anagram {

public static void main(String[] args) {

String str1 = "listen";

String str2 = "silent";

char[] arr1 = str1.toCharArray();

char[] arr2 = str2.toCharArray();

Arrays.sort(arr1);

Arrays.sort(arr2);

if (Arrays.equals(arr1, arr2)) {

System.out.println("Anagrams");

} else {

System.out.println("Not Anagrams");

20. Find Missing Number in the Sequence

public class MissingNumberInSequence {

public static void main(String[] args) {

int[] arr = {1, 2, 4, 5};

int total = 15; // sum of numbers from 1 to 5

int sum = 0;

for (int num : arr) {

sum += num;

System.out.println("Missing number: " + (total - sum));


}

number patterns

1. Right-Angled Triangle (Number Pattern)

public class NumberPattern1 {

public static void main(String[] args) {

int n = 5; // number of rows

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(j + " ");

System.out.println();

Output:

12

123

1234

12345

2. Inverted Right-Angled Triangle (Number Pattern)

public class NumberPattern2 {

public static void main(String[] args) {

int n = 5; // number of rows

for (int i = n; i >= 1; i--) {

for (int j = 1; j <= i; j++) {

System.out.print(j + " ");

}
System.out.println();

Output:

12345

1234

123

12

3. Pyramid (Number Pattern)

public class NumberPattern3 {

public static void main(String[] args) {

int n = 5; // number of rows

for (int i = 1; i <= n; i++) {

for (int j = i; j < n; j++) {

System.out.print(" ");

for (int j = 1; j <= (2 * i - 1); j++) {

System.out.print(j);

System.out.println();

Output:

121

12321

1234321
123454321

4. Inverted Pyramid (Number Pattern)

public class NumberPattern4 {

public static void main(String[] args) {

int n = 5; // number of rows

for (int i = n; 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(j);

System.out.println();

Output:

123454321

1234321

12321

121

5. Diamond Pattern (Number Pattern)

public class NumberPattern5 {

public static void main(String[] args) {

int n = 5; // number of rows

// Upper part of the diamond

for (int i = 1; i <= n; i++) {

for (int j = i; j < n; j++) {


System.out.print(" ");

for (int j = 1; j <= (2 * i - 1); j++) {

System.out.print(j);

System.out.println();

// Lower part of the diamond

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(j);

System.out.println();

Output:

121

12321

1234321

123454321

1234321

12321

121

6. Floyd’s Triangle (Number Pattern)


public class NumberPattern6 {

public static void main(String[] args) {

int n = 5; // number of rows

int num = 1;

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(num + " ");

num++;

System.out.println();

Output:

23

456

7 8 9 10

11 12 13 14 15

7. Pascals Triangle (Number Pattern)

public class NumberPattern7 {

public static void main(String[] args) {

int n = 5; // number of rows

int[][] arr = new int[n][n];

for (int i = 0; i < n; i++) {

for (int j = 0; j <= i; j++) {

if (j == 0 || j == i) {

arr[i][j] = 1;

} else {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];

System.out.print(arr[i][j] + " ");

System.out.println();

Output:

11

121

1331

14641

8. Right-Angled Triangle (Number Pattern with spaces)

public class NumberPattern8 {

public static void main(String[] args) {

int n = 5; // number of rows

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(i + " ");

System.out.println();

Output:

22

333
4444

55555

Mirroing of letters
. // Online Java Compiler

// Use this editor to write, compile and run your Java code online

class Main {

static String compute(String str, int n)

// Creating a string having reversed alphabetical order

String reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba";

int l = str.length();

String answer = "";

for (int i = 0; i < n; i++)

answer = answer + str.charAt(i);

for (int i = n; i < l; i++)

answer = answer + reverseAlphabet.charAt(str.charAt(i) - 'a');

return answer;

// Driver function

public static void main(String args[])

String str = "mazhu";

int n = 2;

System.out.print(compute(str, n - 1));

}
Rearrange positive and negative
// numbers in an array

import java.util.Arrays;

class GfG {

// Function to rearrange the array in-place

static void rearrange(int[] arr) {

// Traverse the array starting from the second element

for (int i = 1; i < arr.length; i++) {

// If the current element is positive, do nothing

if (arr[i] > 0)

continue;

// If the current element is negative, we need to rearrange

int temp = arr[i]; // Store the negative element temporarily

int j = i - 1; // Start shifting from the previous index

// Shift all positive elements to the right until the correct

// position for the negative number is found

while (j >= 0 && arr[j] > 0) {

arr[j + 1] = arr[j]; // Shift the positive element one position to the right

j--; // Move to the previous element

// Place the negative element in its correct position

arr[j + 1] = temp;

// Main function to test the rearrangement


public static void main(String[] args) {

// Input array containing positive and negative integers

int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};

// Call the rearrange function

rearrange(arr);

// Print the rearranged array

for (int ele : arr)

System.out.print(ele + " ");

String Manipulation

import java.util.HashMap;

import java.util.Map;

class Solution {

public static int getSumOfSequence(String str) {

// Create a map to store the values of each letter

Map<Character, Integer> valueMap = new HashMap<>();

valueMap.put('A', 1);

valueMap.put('B', 10);

valueMap.put('C', 100);

valueMap.put('D', 1000);

valueMap.put('E', 10000);

valueMap.put('F', 100000);

valueMap.put('G', 1000000);

int sum = 0;

// Loop through each character in the string and sum their corresponding values
for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);

// If the character is a valid key in the map, add its value to the sum

if (valueMap.containsKey(ch)) {

sum += valueMap.get(ch);

return sum;

public static void main(String[] args) {

// Example usage

String input = "BC";

int result = getSumOfSequence(input);

System.out.println("Sum of sequence: " + result);

You might also like