Programs based on
Conditional Constructs
and Iterative Constructs
in Java
1. Write a program in Java to accept three integers and find the largest
among them using an if Statement.
/*FindLargestOf3.java*/
import java. util. Scanner;
public class FindLargestOf3
{
public static void main (String args[])
{
int maxNum;
Scanner scan = new Scanner (System. in);
System.out.print (“Enter the first number :”);
int num1= scan.nextInt ();
System.out.print (“Enter the second number :”);
int num2= scan.nextInt ();
System.out.print (“Enter the third number :”);
int num3= scan.nextInt ();
maxNum= num1;
if (num2 > maxNum)
maxNum= num2;
if (num3> maxNum)
maxNum= num3;
System.out.println (“Largest of’’+ num1+”,” + num2+”and” + num3+”is:’ ’+
maxNum);
scan. close ();
}
}
2. Write a program in Java to determine the nature of roots of the quadric
equation ax2+ bx+c= 0 where discriminant= b2- 4ac determines the
nature of the roots as follows:
discriminant > 0 Roots are real
discriminant< 0 Roots are imaginary
The roots are computed by the following formula:
root1 = -b+ b2-4ac
2a
root2 = -b- b2- 4ac
2a
/*Quadratic. java*/
import java. util.Scanner;
public class Quadratic
{
public static void main (String args [])
{
double discriminant, root1=0, root2=0;
Scanner input= new Scanner (System. in);
System. out. print (“Enter the value of a :”);
int a = input.nextInt ();
System. out. print (“Enter the value of b :”);
int b = input.nextInt ();
System. out. print (“Enter the value of c :”);
int c= input.nextInt ();
discriminant = Math.sqrt (b*b – 4*a*c);
if (discriminant>=0)
{
System. out. print (“The roots are equal. :”);
root1 = (-b + discriminant)/ (2.0*a);
root2 = (-b – discriminant)/ (2.0*a);
System. out. print (“The roots are” + root1 + “and” + root2);
}
else
{
System. out. print (“The roots are imaginary.”);
}
input. close ();
}
}
3. Write a program in Java to read the gender code (M or F) and the age
and print the price of the hair cut
A hair salon charges customers as per the following criteria:
Male Customers:
Boys (age< =13):Rs. 200
Men (age>= 13): Rs. 300
Female Customers:
Girls (age<= 13): Rs. 250
Women (age>13): Rs.350
/*HairCutSalon.java */
import java.util.Scanner;
public class HaircutSalon
public static void main (String args [])
int price = 0;
Scanner input = new Scanner (System. in);
System.out.print (“Enter the Gender code (M or F) :”);
char gendercode = input. next ().charAt (0);
System.out.print (“Enter the Gender code (M or F) :”);
int age = input. nextInt ();
if (genderCode == ‘M’)
if (age<=13)
price = 200;
else
price = 300;
System.out.println (“Price is:” + price);
else if (genderCode == ‘F’)
if (age<= 13)
price = 250;
else
price = 350;
System.out.println (“Price is:” + price);
else
System.out.println (“Invalid Gender code Entered”);
input. close ();
}
4. Write a program to accept a two digit number. Add the sum of its digits
to the product of its digits. If the value is equal to the input number,
display the message” Special 2 digit number”; otherwise, display the
message” Not a special 2 digit number”.
/*SpecialNumber.java*/
import java.util.Scanner;
public class SpecialNumber
{
public static void main (String args [])
{
Scanner sc = new Scanner (System. in);
System.out.println (“Enter a two digit number :”);
int number = sc.nextInt ();
if (number < 10|| number > 99)
{
System.out.println (“Entered number is not a two digit number :”);
System.out.println (“Exiting :”);
System. exit (0);
}
int firstDigit = number % 10; // Get remainder
int secondDigit = number / 10; // Get quotient
int sumOfDigits = firstDigit + secondDigit;
int productOfDigits = firstDigit * secondDigit;
int newNumber = sumOfDigits + productOfDigits;
if (newNumber == number)
System.out.println (“Special 2 digit number”);
else
System.out.println (“Not a Special 2 digit number”);
}
}
5. Write a Java program that reads two positive integer numbers ( a and
b) and calculations ab using only addition and multiplication
operations.
/*ComputePower.java*/
import java. util.Scanner;
public static void main (String args [])
{
int power = 1;
int counter = 1;
Scanner keyboard = new Scanner (System. in);
System.out.print (“Enter the first number :”);
int a = keyboard. nextInt ();
System.out.print (“Enter the first number :”);
int b = keyboard. nextInt ();
while (counter <= b)
{
power = power * a;
counter++;
}
System.out.println ( a + “^” + b + “=” + power);
keyboard. close();
}
}
Programs based
on Methods
6. Design a class to overload a method volume() as follows:
(i). double volume (double r) -- with radius ‘r’ as an argument, returns
the volume of sphere using the formula:
v = 4 /3* 22/7*r3
(ii). double volume (double h, double r) – with height ‘h’ and radius ‘r’
as the arguments, returns the volume of a cylinder using the formula:
v = 22/7* r2*h
(iii). double volume (double l, double b, double h)—with length ‘l’,
breadth ’b’ and the arguments, returns the volume of a cuboid using
the formula:
v = l*b*h
public class VolumeOverload
{
double volume (double r)
{
double vol = 4.0 / 3*22 / 7* Math.pow(r, 3);
return vol;
}
double volume (double h, double r)
{
double v = 22.0/ 7* Math.pow(r, 2) * h;
return v;
}
double volume (double l, double b, double h)
{
double v = l*b*h;
return v;
}
}
7. Design a class to overload a function SumSeries() as follows:
(i). void SumSeries (int n, double x) – with one integer argument and
one double argument and one double argument to find and display the
sum of the series given below:
s = x/1 - x/2 + x/3 - x/4 + x/5 ………… to n terms
(ii). void SumSeries ()—To find and display the sum of the following
series:
s = 1+ (1*2) + (1*2*3) + ……… + (1*2*3*4 ………………*20)
public class SeriesOverload
public void SumSeries (int n, double x)
double sum = 0;
for (int i = 1; i<=n; i++)
if (i% 2 == 1)
sum = sum + (x/i);
else
sum = sum – (x/i);
System.out.println (“Sum of series =” + sum);
}
public void SumSeries ()
long sum = 0;
for (int I = 1; 1<= 20; i++)
long product = 1;
for (int j = 1; j<= I; j++)
product = product * j;
sum = sum + product;
System.out.println (“Sum of series=” + sum);
}
8. Design a class to overload a function area() as follows:
(i). double area (double a, double b, double c) with three double
arguments, returns the area of a scalene triangle using the formula:
area = s(s-a) (s-b) (s-c)
s=a+b+c
2
(ii). double area (int a, int b, int height) with three integer arguments,
returns the area of a trapezium using the formula:
area = 1/2height (a + b)
(iii). double area (double diagonal1, double diagonal2) with double
arguments, returns the area of a rhombus using the formula:
area = ½(diagonal * diagonal)
public class AreaOverload
{
public double area (double a, double b, double c)
{
double s = (a + b + c)/2;
double area = Math.sqrt( s * (s-a) * (s-b) * (s-c));
return area;
}
public double area (int a, int b, int height)
{
double area = 0.5* height*(a + b);
return area;
}
public double area (double diagonal1, double diagonal2)
{
double area = 0.5 *(diagonal1 * diagonal2);
}
}
9. Write a Java program to check whether the given number is a prime
number or not. While doing so, demonstrate the use of the break
statement in Java.
/*PrimeNumberWithBreak.java*/
import java. util.Scanner;
public class PrimeNumberWithBreak
{
static Boolean IsPrime( int num)
{
boolean prime = true;
for ( int i = 2; i<=num/2; i++)
{
if (num % i = = 0)
{
prime = false;
break;
}
}
return prime;
}
public static void main (String args[])
{
Scanner keyboard = new Scanner (System. in);
System.out.println (“Enter an integer(0 to exist)”);
int number = keyboard. nextInt ();
while (number! = 0)
{
if (IsPrime (number))
System.out.println (number + “is a prime number”);
else
System.out.println (number + “is not a prime number”);
System.out.println (“Enter an integer ( 0 to exit)”);
number = keyboard.nextInt ();
}
System.out.println (“Exiting………”);
keyboard. close ();
}
}
10. Write a program to check whether the given number is a composite
number or not.
Hint: A composite number is a positive integer that has factors other
than 1 and itself
/*CompositeNumber.java*/
import java.util.Scanner;
public class CompositeNumber
{
static boolean IsComposite (int num)
{
boolean composite = false;
for (int i = 2; i<=2 num/2; i++)
{
if (num % I ==0)
composite = true;
}
return composite;
}
public static void main (String args [])
{
Scanner keyboard = new Scanner (System. in);
System.out.println (“Enter an integer (0 to exit)’’);
int number = keyboard.nextInt ();
while (number!= 0)
{
if (IsComposite (number))
System.out.println (number + “is a Composite number”);
else
System.out.println (number + “is not a Composite number”);
System.out.println (“Enter an integer (0 to exit)”);
number = keyboard.nextInt ();
}
System.out.println (“Exiting……”);
keyboard. close ();
}
}
Programs Based
on String
Handling
11. Write a program to input a word and display each character of the
word on a separate line.
Sample input: ICSE
Sample Output:
I
C
S
E
/*Pattern1.java*/
import java.util.*;
public class Pattern1
{
public static void main (String args [])
{
Scanner scan = new Scanner (System. in);
int length;
System.out.println (“Enter a word :”);
String word = scan. next ();
length = word. length ();
for (int i = 0; i<=length; i++)
System.out.println (word. CharAt (i));
scan. close ();
}
}
12. Write a program to accept a word and check if it is a Palindrome or
not
(Hint: A palindrome is a word which reads the same backward as
forward)
Sample Input:
Radar
Sample Output:
Radar is palindrome
/*PalindromeString.java*/
import java.util.*;
public class PalindromeString
{
public static void main (String args[])
{
Scanner scan = new Scanner (System. in);
int length;
String reverseString = “‘’;
System.out.println (“Enter a word :”);
String inputString = scan.nextLine ();
length = inputString. Length ();
for (int I = length – 1; I >= 0; i--)
{
reverseString = reverseString + inputString. charAt (i);
}
if (reverseString.equalsIgnoreCase (inputString))
System.out.println (inputString + “is Palindrome”);
else
System.out.println (inputString + “is not Palindrome”);
scan. close();
}
}
13. Write a program to accept a string and display the numbers of
vowels in it
/*Vowels java.util.*;
import java.util.*;
public class Vowels
{
public static void main (String args [])
{
Scanner scan = new Scanner (System. in);
int length;
int vowels = 0;
char tmpChar;
System.out.println (“Enter a word :”);
String sentence = scan.nextLine ();
length = sentence. length ();
for (int i = 0; i<length; i++)
{
tmpChar = sentence. charAt (i);
if (tmpChar == ‘a’ || tmpChar == ‘e’ || tmpChar == ‘i’ ||
tmpChar == ‘o’ || tmpChar == ‘u’ || tmpChar == ‘A’ ||
tmpChar == ‘E’ || tmpChar == ‘I’ || tmpChar == ‘O’ ||
tmpChar == ‘U’)
vowels++;
}
System.out.println (“Number of vowels are:” + vowels);
scan. close ();
}
}
14. Write in java to accept a string in lowercase and change the first
letter of every word to uppercase. Display the new String.
Sample INPUT: we are in cyber world
Sample OUTPUT: We Are In Cyber World
/*import java.util.Scanner;
public class Capitalise
{
public static void main (String args [])
{
Scanner sc = new Scanner (System. in);
System.out.println (“Enter the string :”);
String input = sc.nextInt ();
String output = “”;
for (int i = 0; i< input. length (); i++)
{
char currentChar = input. CharAt (i);
if (i == 0|| input. charAt (i-1) == ‘‘)
output+= Character.touppercase (currentChar);
else
output+= currentChar;
}
System.out.println (“New string is:” + output);
scanner. close ();
}
}
15. Write a program that reads a string and a word separately. The
program then finds the frequency of the word in the string.
Sample Input:
The quick brown fox jumps over the lazy dog.
Sample Output:
Frequency is: 2
/*WordCount.java*/
import java.util.*;
public class WordCount
{
public static void main (String args [])
{
Scanner sc = new Scanner (System. in);
int length, count = 0;
char tmpChar;
String tmpWord = “”
System.out.println (“Enter a string ;”);
String searchString = scan.nextLine ();
searchString = searchString.trim () + “”;
length = searchString. length ();
System.out.println (“Enter the word to search for :”);
String searchWord = scan.next ();
for (int i = 0; i< length; i++)
{
tmpChar = searchString. charAt (i);
if (tmpChar == ‘‘)
{
if (tmpWord.compareToIgnoreCase (searchWord) = = 0)
{
count++;
}
tmpWord = “”;
}
else
tmpWord = tmpWord + tmpChar;
}
System.out.println (“Frequency of” + searchWord + “is:” +
count);
scan. close ();
}
}
Programs Based
on Arrays
16. Write a program in java to input 10 integers and save them in a
single dimensional array. Perform the following tasks.
(i) Print the elements in the array on a single line followed by a
space.
(ii) Compute and print the sum of elements at even indices.
(iii) Compute and print the product of elements at odd indices.
import. java.util.*;
public class SumProduct
{
public static void main (String args[])
{
Scanner keyboard = new Scanner (System. in);
int numbers[] = new int[10];
int sumEven = 0;
long productOdd = 1
System.out.println (“Enter 10 integer :”)
for(int i = 0; i < 10; i++)
numbers[i] = keyboard.nextInt();
for (int i = 0; i < 10; i++)
{
System.out.print(numbers[i] + “”);
if (i % 2 == 1)
productOdd = productOdd * numbers[i];
else
sumEven = sumEven + numbers[i];
}
System.out.println (“\nSum of integers at even indices:” + sumEven);
System.out.println (“Product of integers at odd indices:” +
productOdd);
keyboard. close ();
}
17. Write a program to accept 10 different numbers in a single
dimensional array. Display the greatest and smallest numbers of the
array elements.
import java.util.*;
public class MinMax
public static void main(String args[])
Scanner keyboard = new Scanner (System. in);
int number[] = new int[10];
int min, max;
System.out.println(“Enter 10 integers:”);
for (int i =0; i<10; i++)
numbers[i] = keyboard.nextInt();
min = numbers[0];
max = numbers[0];
for(int i = 1; i< 10; i++)
{
if(numbers[i]> max)
max = numbers[i];
if(numbers[i] < min)
min = numbers[i];
System.out.println (“The greatest of the array elements is:” + max);
System.out.println (“The smallest of the array elements is;” + min);
}
18. Write a program in Java to store the characters in word COMPUTER
in a single dimensional array. Arrange and display all the characters in
descending order.
public class Descending
{
public static void main(String args[])
{
char list[] = {‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’};
int len = list. length;
for ( int i = 0; i < len-1; i++)
{
for( int j = 0; j < len-i-1; j++)
{
if (list[j]< list[j+1])
{
char tmp = list[j];
list[j] = list[j + 1];
list[j+1] = tmp;
}
}
}
19. Write a program in input a string in uppercase and print the
frequency of each character.
INPUT : COMPUTER HARDWARE
OUTPUT :
CHARACTERS FREQUENCY
A 2
C 1
D 1
E 2
H 1
M 1
O 1
P 1
R 3
T 1
U 1
W 1
import java.util.Scanner;
public class charFrequency
public static void main (String args[])
{
Scanner keyboard = new Scanner (System. in);
int charFrequency[] = new int[26];
System.out.print(“Enter a string:”);
String input = keyboard.nextLine ();
input = input.toUpperCase();
for ( int = 0; i< input. length(); i++)
char ch = input. CharAt(i);
if (Character. isLetter(ch))
charFrequency[ch – ‘A’]++;
System.out.println(“Characters Frequency”);
for(int i = 0; i<26; i++)
if (charFrequency[i]! =0)
System.out.println((char) (i + ‘A’) + “\t\t” + charFrequency[i]);
keyboard. close();
}
20. Write a program to input 15 integer elements in array and sort
them in ascending order.
import java.util.Scanner;
public class Ascending
{
public static void main (String args[])
{
int list[] = new int[15];
Scanner keyboard = new Scanner (System. in);
for (Int i= 0; i< 15; i++)
{
System.out.print (“Enter element” + (i+1) + “:”);
list[i] = keyboard.nextInt();
}
int len = list. length;
for (int i = 0; i< len – 1; i++)
{
for (int j = 0; j< len –i-1; j++)
{
if( list[j] > list[j + 1])
{
int tmp = list[j];
list[j] = list[j+1];
list[j + 1] = tmp;
}
}
}
System.out.println (“Sorted array is:”);
for( int i = 0; i<len; i++)
{
System.out.print(list[i] + “”);
}
}
}