Showing posts with the label Coding practice

How to find largest number in an array in Java

 All we have to do in this problem is to consider 0 as the largest number then loop all the elements of the array and if any number is greater than the currently set largest number then we will replace the largest number with the new number that is greater and we keep doing this till the end of the array.  class findlargest{ public int largest( int arr[], int n) { int largestNum = 0 ; for ( int i= 0 ; i<arr. length ; i++){ if (arr[i]>largestNum){ largestNum=arr[i]; } } return largestNum; } }

How to reverse a string in Java

 In this problem we are given a string e.g Hello and we need to write a function that will reverse the string and return olleH. In the below function reverseWords we take a string and read each character from the opposite direction then concatenate each charaters to make the string and finally return the string.  class ReverseString { // str: input string public static String reverseWords(String str) { String s= "" ; // Reverse the string str for ( int i=str. length ()- 1 ; i>= 0 ; i--){ char ch=str. charAt (i); s+=ch; } return s; } }