Showing posts with label Programming Assignment 1. Show all posts
Showing posts with label Programming Assignment 1. Show all posts

Tuesday, July 21, 2015

Prog21.java

Write a method which takes 3 integers as parameters and adds the 2 highest numbers out of 3 then and returns the result. e.g. m1(5,7,2) will return you 12 (5+7).


class Utility{
static int addMax2(int i, int j, int k){
int max1, max2;
if(i<=j && i<=k){
return k+j;
}
else if(j<=k && j<=i){
return k+i;
}
else if(k<=j && k<=i){
return i+j;
}
else if(i==j && i==k){
return i+j;
}
return 0;
}
}

class Demo{
public static void main(String[] args){
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int k = Integer.parseInt(args[2]);
int ans = Utility.addMax2(i,j,k);
System.out.println(ans);
}
}

Prog7.java

Write a program to find no. of digits in a String.

class Demo{
public static void main(String[] args){
String a="2sdf46sf4";
int count = 0;
for(int i =0; i<a.length(); i++){
char c = a.charAt(i);
if(Character.isDigit(c)){
count++;
}
}
System.out.println("No. of Digits = "+count);
}

}


Output:
No. of Digits = 4


[Hint: You can also go for command line argument instead of fixed string in program]

Prog10.java

Find whether an array is sorted or not.

class Prog10{
static boolean isSorted(int[] arr){
int flag = 0;
for(int i = 0 ; i<arr.length-1; i++){
if(arr[i] > arr[i+1]){
return false;
                               // Even if 1 item is greater then next item, ans is false.
}
}
          return true;
// if all items are perfect only then code reaches till here, so return true.
}

public static void main(String[] args){
// args[0] -> no . of  elements
int no = Integer.parseInt(args[0]);
int[] arr = new int[no];

for(int i = 0 ; i<no ; i++){
arr[i] = Integer.parseInt(args[i+1]);
}

if(Prog10.isSorted(arr)){
System.out.println("Yes sorted");
}
else{
System.out.println("Not sorted");
}
}
}