Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

1.

Half Pyramid of Stars

public class HalfPyramid {


public static void main(String[] args) {
int rows = 5;

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


for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}

2. Str Concat without In Built Functions


public class StringConcatenation {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = " ";
String str3 = "World";

// Calculate the length of the concatenated string


int totalLength = str1.length() + str2.length() + str3.length();

// Create a character array with the total length


char[] resultArray = new char[totalLength];

// Copy each character from the original strings to the result array
int index = 0;

// Copy characters from str1


for (int i = 0; i < str1.length(); i++) {
resultArray[index++] = str1.charAt(i);
}

// Copy characters from str2


for (int i = 0; i < str2.length(); i++) {
resultArray[index++] = str2.charAt(i);
}

// Copy characters from str3


for (int i = 0; i < str3.length(); i++) {
resultArray[index++] = str3.charAt(i);
}

// Convert the character array to a String


String concatenatedString = new String(resultArray);

// Print the result


System.out.println(concatenatedString);
}
}

3. Reverse words in a string without in built functions

public class ReverseWords {


public static void main(String[] args) {
String inputString = "Hello World";
String reversedString = reverseWords(inputString);
System.out.println(reversedString);
}

private static String reverseWords(String input) {


char[] inputArray = input.toCharArray();
int start = 0;

for (int end = 0; end <= inputArray.length; end++) {


if (end == inputArray.length || inputArray[end] == ' ') {
reverseWord(inputArray, start, end - 1);
start = end + 1;
}
}

return new String(inputArray);


}

private static void reverseWord(char[] array, int start, int end) {


while (start < end) {
char temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
}

4. Find Smallest, Middle and Largest Element in an array

5. Binary Search

public class BinarySearch {

public static int binarySearch(int[] array, int target) {


int left = 0;
int right = array.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (array[mid] == target) {
return mid; // Target found
} else if (array[mid] < target) {
left = mid + 1; // Search in the right half
} else {
right = mid - 1; // Search in the left half
}
}

return -1; // Target not found


}

public static void main(String[] args) {


int[] sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 7;

int result = binarySearch(sortedArray, target);

if (result != -1) {
System.out.println("Element found at index " + result);
} else {
System.out.println("Element not found");
}
}
}

You might also like