Assignment 1
Assignment 1
SIVAKUMAR.M CT20100218667
Question 1 Search for a name Write a program to accept an array of names and a name and check whether the name is present in the array. Return the count of occurrence. Use the following array as input {Dave, Ann, George, Sam, Ted, Gag, Saj, Agati, Mary, Sam, Ayan, Dev, Kity, Meery, Smith, Johnson, Bill, Williams, Jones, Brown, Davis, Miller, Wilson, Moore, Taylor, Anderson, Thomas, Jackson} Program :
import java.io.*; import java.util.*; public class Counter { static String Arr_names = " Dave Ann George Sam Ted Gag Saj Agati Mary Sam Ayan Dev Kity Meery Smith Johnson Bill Williams Jones Brown Davis Miller Wilson Moore Taylor Anderson Thomas Jackson "; public static void main(String args[])throws Exception { StringTokenizer s1=new StringTokenizer(Arr_names); Scanner br= new Scanner(System.in);
System.out.println("Enter a name to be searched"); String name=br.nextLine(); int count=0; while(s1.hasMoreTokens()) { if(name.equalsIgnoreCase(s1.nextToken())) { count++; } } System.out.println("THE NAME "+name+" HAS APPEARED "+count+" TIMES"); } }
Question 2 Greatest common divisor Calculate the greatest common divisor of two positive numbers a and b. gcd(a,b) is recursively defined as gcd(a,b) = a if a =b gcd(a,b) = gcd(a-b, b) if a >b gcd(a,b) = gcd(a, b-a) if b > a Program:
import java.io.*; import java.util.Scanner; class gcdfinder { public static void main(String args[]) { Scanner sr= new Scanner(System.in); System.out.println("Enter The number a"); int a=sr.nextInt(); System.out.println("Enter The number b"); int b=sr.nextInt(); int gcd;
if(a==b) gcd=a; else if(a>b) gcd=findgcd(a-b,b); else gcd=findgcd(b,b-a); System.out.println("The greatest common divisor of numbers " + a + " and " + b + " is " + gcd); } public static int findgcd(int c,int d) { if (d == 0) return c; return findgcd(d, c % d); } }