0% found this document useful (0 votes)
29 views54 pages

50 Most Important Programs

Uploaded by

roopa.bailamma3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views54 pages

50 Most Important Programs

Uploaded by

roopa.bailamma3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Clarify

Knowledge

50 Most
Important
programs
ICSE 9 & 10
Code is Easy
Clarify
Knowledge

Conditional
Constructs

Write a program to input three numbers (positive or


negative). If they are unequal then display the greatest
number otherwise, display they are equal. The program
also displays whether the numbers entered by the user
are 'All positive', 'All negative' or 'Mixed numbers'.

import java.util.Scanner;
public class NumberAnalysis
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = in.nextInt();
System.out.print("Enter second number: ");
int b = in.nextInt();
System.out.print("Enter third number: ");
int c = in.nextInt();
int greatestNumber = a;
if ((a == b) && (b == c)) {
System.out.println("Entered numbers are equal.");
}
else {
if (b > greatestNumber) {
greatestNumber = b;
}
if (c > greatestNumber) {
greatestNumber = c;
}
System.out.println("The greatest number is " + greatestNumber);
if ((a >= 0) && (b >= 0) && (c >= 0)) {
System.out.println("Entered numbers are all positive numbers.");
}
else if((a < 0) && (b < 0) && (c < 0)) {
System.out.println("Entered numbers are all negative numbers.");
}
else {
System.out.println("Entered numbers are mixed numbers.");
}
}
}
}
Clarify
Knowledge

Conditional
Constructs

A triangle is said to be an 'Equable Triangle', if the area of


the triangle is equal to its perimeter. Write a program to
enter three sides of a triangle. Check and print whether
the triangle is equable or not.
For example, a right angled triangle with sides 5, 12 and 13
has its area and perimeter both equal to 30.
iimport java.util.Scanner;
public class EquableTriangle
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the 3 sides of the triangle.");
System.out.print("Enter the first side: ");
double a = in.nextDouble();
System.out.print("Enter the second side: ");
double b = in.nextDouble();
System.out.print("Enter the third side: ");
double c = in.nextDouble();
double p = a + b + c;
double s = p / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
if (area == p)
System.out.println("Entered triangle is equable.");
elseSystem.out.println("Entered triangle is not equable.");
}
}
}
Clarify
Knowledge

Conditional
Constructs

A special two-digit number is such that when the sum of


its digits is added to the product of its digits, the result is
equal to the original two-digit number.
Example: Consider the number 59.
Sum of digits = 5 + 9 = 14
Product of digits = 5 * 9 = 45
Total of the sum of digits and product of digits = 14 + 45 =
59
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 number input, display the message "Special 2
- digit number" otherwise, display the message "Not a
special two-digit number".
import java.util.Scanner;
public class SpecialNumber
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a 2 digit number: ");
int orgNum = in.nextInt();
if (orgNum < 10 || orgNum > 99) {
System.out.println("Invalid input. Entered number is not a 2 digit
number");
System.exit(0);
}
int num = orgNum;
int digit1 = num % 10;
int digit2 = num / 10;
num /= 10;
int digitSum = digit1 + digit2;
int digitProduct = digit1 * digit2;
int grandSum = digitSum + digitProduct;
if (grandSum == orgNum)
System.out.println("Special 2-digit number");
elseSystem.out.println("Not a special 2-digit number");
}
}
Clarify
Knowledge

Conditional
Constructs

Write a program that accepts three numbers from the user


and displays them either in "Increasing Order" or in
"Decreasing Order" as per the user's choice.
Choice 1: Ascending order
Choice 2: Descending order
Sample Inputs: 394, 475, 296
Choice 2
Sample Output
First number : 475
Second number: 394
Third number : 296
The numbers are in decreasing order.
import java.util.Scanner;
public class BusFare
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter distance travelled: ");
int dist = in.nextInt();
int fare = 0;
if (dist <= 0)
fare = 0;
else if (dist <= 10)
fare = 80;
else if (dist <= 20)
fare = 80 + (dist - 10) * 6;
else if (dist <= 30)
fare = 80 + 60 + (dist - 20) * 5;
else if (dist > 30)
fare = 80 + 60 + 50 + (dist - 30) * 4;
System.out.println("Fare = " + fare);
}
}
Clarify
Knowledge

Conditional
Constructs

A courier company charges differently for 'Ordinary'


booking and 'Express' booking based on the weight of the
parcel as per the tariff given below:
Weight of parcel Ordinary booking. Express booking
Up to 100 gm ₹80 ₹100
101 to 500 gm ₹150 ₹200
501 gm to 1000 gm ₹210 ₹250
More than 1000 gm ₹250 ₹300
Write a program to input weight of a parcel and type of
booking (`O' for ordinary and 'E' for express). Calculate and
print the charges accordingly.

import java.util.Scanner;
public class CourierCompany
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter weight of parcel: ");
double wt = in.nextDouble();
System.out.print("Enter type of booking: ");
char type = in.next().charAt(0);
double charge = 0;
if (wt <= 0)
charge = 0;
else if (wt <= 100 && type == 'O')
charge = 80;
else if (wt <= 100 && type == 'E')
charge = 100;
else if (wt <= 500 && type == 'O')
charge = 150;
else if (wt <= 500 && type == 'E')
charge = 200;
else if (wt <= 1000 && type == 'O')
charge = 210;
else if (wt <= 1000 && type == 'E')
charge = 250;
else if (wt > 1000 && type == 'O')
charge = 250;
else if (wt > 1000 && type == 'E')
charge = 300;
System.out.println("Parcel charges = " + charge);
}
}
Clarify
Knowledge

Iterative
constructs

Write the programs in Java to find the sum of the following


series:
(a) S = 1 + 1 + 2 + 3 + 5 + ....... to n terms
import java.util.Scanner;
public class Series
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int a = 1, b = 1;
int sum = a + b;
for (int i = 3; i <= n; i++) {
int term = a + b;
sum += term;
a = b;
b = term;
}
System.out.println("Sum=" + sum);
}

}
Clarify
Knowledge

Iterative
constructs

Write the programs in Java to find the sum of the following


series:
(b) S = 2 - 4 + 6 - 8 + ....... to n
import java.util.Scanner;
public class Series
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0;
for (int i = 1, j = 2; i <= n; i++, j = j + 2) {
if (i % 2 == 0) {
sum -= j;
}
else {
sum += j;
}
}
System.out.println("Sum=" + sum);
}
}
Clarify
Knowledge

Iterative
constructs

Write the programs in Java to find the sum of the following


series:
(c) S = 1 + (1+2) + (1+2+3) + ....... + (1+2+3+ ....... + n)

import java.util.Scanner;
public class Series
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int a = 1, b = 1;
int sum = a + b;
for (int i = 3; i <= n; i++) {
int term = a + b;
sum += term;
a = b;
b = term;
}
System.out.println("Sum=" + sum);
}

}
Clarify
Knowledge

Iterative
constructs

Write the programs in Java to find the sum of the following


series:
(d) S = 1 + (1*2) + (1*2*3) + ....... + (1*2*3* ....... * n)

import java.util.Scanner;
public class Series
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
long sum = 0, term = 1;
for (int i = 1; i <= n; i++) {
term *= i;
sum += term;
}
System.out.println("Sum=" + sum);
}
}
Clarify
Knowledge

Iterative
constructs

Write the program to find the sum of the following series:


S = (a/2) + (a/5) + (a/8) + (a/11) + ....... + (a/20)
import java.util.Scanner;
public class Series
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
double sum = 0;
for (int i = 2; i <= 20; i = i + 3) {
sum += a / (double)i;
}
System.out.println("Sum=" + sum);
}
}
Clarify
Knowledge

Iterative
constructs

Write a program to enter two numbers and check whether


they are co-prime or not.
[Two numbers are said to be co-prime, if their HCF is 1
(one).]
Sample Input: 14, 15
Sample Output: They are co-prime.
import java.util.Scanner;
public class Coprime
{
public void checkCoprime() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter b: ");
int b = in.nextInt();
int hcf = 1;
for (int i = 1; i <= a && i <= b; i++) {
if (a % i == 0 && b % i == 0)
hcf = i;
}
if (hcf == 1)
System.out.println(a + " and " + b + " are
co-prime");
elseSystem.out.println(a + " and " + b + " are
not co-prime");
}
}
Clarify
Knowledge

Iterative
constructs

Write a program to input a number and check and print


whether it is a Pronic number or not. [Pronic number is the
number which is the product of two consecutive integers.]
Examples:
12 = 3 * 4
20 = 4 * 5
42 = 6 * 7
import java.util.Scanner;
public class PronicNumber
{
public void pronicCheck() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number to
check: ");
int num = in.nextInt();
boolean isPronic = false;
for (int i = 1; i <= num - 1; i++) {
if (i * (i + 1) == num) {
isPronic = true;
break;
}
}
if (isPronic)
System.out.println(num + " is a pronic
number");
elseSystem.out.println(num + " is not a
pronic number");
}
}
Clarify
Knowledge

Iterative
constructs

Write a program to input a number and check whether it is


a prime number or not. If it is not a prime number then
display the next number that is prime.
Sample Input: 14
Sample Output: 17
import java.util.Scanner;
public class PrimeCheck
{
public void primeCheck() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + " is a prime number");
}
else {
for (int newNum = num + 1; newNum <=
Integer.MAX_VALUE; newNum++) {
isPrime = true;
for (int i = 2; i <= newNum / 2; i++) {
if (newNum % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("Next prime number = " +
newNum);
break;
}
}
}
}
}
Clarify
Knowledge

Iterative
constructs

Write a program to input a number and check whether it is


a Harshad Number or not. [A number is said to be Harshad
number, if it is divisible by the sum of its digits. The
program displays the message accordingly.]
For example;
Sample Input: 132
Sum of digits = 6 and 132 is divisible by 6.
Output: It is a Harshad Number.
Sample Input: 353
Output: It is not a Harshad Number.
import java.util.*;
public class HarshadNumber
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = in.nextInt();
int x = num, rem = 0, sum = 0;
while(x > 0) {
rem = x % 10;
sum = sum + rem;
x = x / 10;
}
int r = num % sum;
if(r == 0)
System.out.println(num + " is a Harshad Number.");
elseSystem.out.println(num + " is not a Harshad Number.");
}
}
Clarify
Knowledge

Iterative
constructs

Using a switch statement, write a menu driven program


to:
(a) generate and display the first 10 terms of the
Fibonacci series
0, 1, 1, 2, 3, 5
The first two Fibonacci numbers are 0 and 1, and each
subsequent number is the sum of the previous two.
(b) find the sum of the digits of an integer that is input
by the user.
Sample Input: 15390
Sample Output: Sum of the digits = 18
For an incorrect choice, an appropriate error message
should be displayed.
import java.util.Scanner;
public class FibonacciNDigitSum
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Fibonacci Series");
System.out.println("2. Sum of digits");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
int a = 0, b = 1;
System.out.print(a + " " + b);
/*
* i is starting from 3 below
* instead of 1 because we have
* already printed 2 terms of
* the series. The for loop will
* print the series from third
* term onwards.
*/
for (int i = 3; i <= 10; i++) {
int term = a + b;
System.out.print(" " + term);
a = b;
b = term;
}
break;
Clarify
Knowledge

case 2:
System.out.print("Enter number: ");
int num = in.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits " + " = " + sum);
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
Clarify
Knowledge

iterative
constructs

Create a menu-driven program using a switch


statement for the tasks below:
(a) Calculate and show the sum of the series:
S = x^1 - x^2 + x^3 - x^4 + x^5 - ... - x^20
(b) Calculate and display the sum of the series:
S = 1/a^2 + 1/a^4 + 1/a^6 + 1/a^8 + ... up to n terms
If an incorrect option is selected, display an
appropriate error message.

import java.util.Scanner;
public class SeriesSum
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Sum of x^1 - x^2 + .... - x^20");
System.out.println("2. Sum of 1/a^2 + 1/a^4 + .... to n terms");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
System.out.print("Enter the value of x: ");
int x = in.nextInt();
long sum1 = 0;
for (int i = 1; i <= 20; i++) {
int term = (int)Math.pow(x, i);
if (i % 2 == 0)
sum1 -= term;
else
sum1 += term;
}
System.out.println("Sum = " + sum1);
break;
Clarify
Knowledge

case 2:
System.out.print("Enter the number of terms: ");
int n = in.nextInt();
System.out.print("Enter the value of a: ");
int a = in.nextInt();
int c = 2;
double sum2 = 0;
for(int i = 1; i <= n; i++) {
sum2 += (1/Math.pow(a, c));
c += 2;
}
System.out.println("Sum = " + sum2);
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
Clarify
Knowledge

Nested
loops

Write a program in Java to enter a number


containing three digits or more. Arrange the digits
of the entered number in ascending order and
display the result.
Sample Input: Enter a number 4972
Sample Output: 2, 4, 7, 9
import java.util.Scanner;
public class DigitSort
{
public void sortDigits() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number having 3 or
more digits: ");
int OrgNum = in.nextInt();
for (int i = 0; i <= 9; i++) {
int num = OrgNum;
int c = 0;
while (num != 0) {
if (num % 10 == i)
c++;
num /= 10;
}
for (int j = 1; j <= c; j++) {
System.out.print(i + ", ");
}
}
System.out.println();
}
}
Clarify
Knowledge

Nested
loops

A number is said to be Multiple Harshad number, when divided


by the sum of its digits, produces another 'Harshad Number'.
Write a program to input a number and check whether it is a
Multiple Harshad Number or not.
(When a number is divisible by the sum of its digit, it is called
'Harshad Number').
Sample Input: 6804
Hint: 6804 ⇒ 6+8+0+4 = 18 ⇒ 6804/18 = 378
378 ⇒ 3+7+8= 18 ⇒ 378/18 = 21
21 ⇒ 2+1 = 3 ⇒ 21/3 = 7
Sample Output: Multiple Harshad Number
import java.util.Scanner;
public class MultipleHarshad
{
public void checkMultipleHarshad() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number to check: ");
int num = in.nextInt();
int dividend = num;
int divisor;
int count = 0;
while (dividend > 1) {
divisor=0;
int t = dividend;
while (t > 0) {
int d = t % 10;
divisor += d;
t /= 10;
}
if (dividend % divisor == 0 && divisor != 1) {
dividend = dividend / divisor;
count++;
}
else {
break;
}
}
if (dividend == 1 && count > 1)
System.out.println(num + " is Multiple Harshad Number");
else
System.out.println(num + " is not Multiple Harshad Number");
}
}
Clarify
Knowledge

Nested
loops

A number is said to be Multiple Harshad number, when divided


by the sum of its digits, produces another 'Harshad Number'.
Write a program to input a number and check whether it is a
Multiple Harshad Number or not.
(When a number is divisible by the sum of its digit, it is called
'Harshad Number').
Sample Input: 6804
Hint: 6804 ⇒ 6+8+0+4 = 18 ⇒ 6804/18 = 378
378 ⇒ 3+7+8= 18 ⇒ 378/18 = 21
21 ⇒ 2+1 = 3 ⇒ 21/3 = 7
Sample Output: Multiple Harshad Number
import java.util.Scanner;
public class MultipleHarshad
{
public void checkMultipleHarshad() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number to check: ");
int num = in.nextInt();
int dividend = num;
int divisor;
int count = 0;
while (dividend > 1) {
divisor=0;
int t = dividend;
while (t > 0) {
int d = t % 10;
divisor += d;
t /= 10;
}
if (dividend % divisor == 0 && divisor != 1) {
dividend = dividend / divisor;
count++;
}
else {
break;
}
}
if (dividend == 1 && count > 1)
System.out.println(num + " is Multiple Harshad Number");
else
System.out.println(num + " is not Multiple Harshad Number");
}
}
Clarify
Knowledge

Nested
loops

Write the programs to display the following patterns:


(a)
1
31
531
7531
97531

public class Pattern


{
public void displayPattern() {
for (int i = 1; i < 10; i = i + 2) {
for (int j = i; j > 0; j = j - 2) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Clarify
Knowledge

Nested
loops

Write the programs to display the following patterns:


(b)
1 2 3 4 5
6 7 8 9
10 11 12
13 14
15

public class Pattern


{
public void displayPattern() {
int a = 1;
for (int i = 5; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
}
}
Clarify
Knowledge

Nested
loops

Write the programs to display the following patterns:


(c)
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1
public class Pattern
{
public void displayPattern() {
int a = 15;
for (int i = 5; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(a-- + "\t");
}
System.out.println();
}
}
}
Clarify
Knowledge

Nested
loops

Write the programs to display the following patterns:


(d)
1
10
101
1010
10101
public class Pattern
{
public void displayPattern() {
int a = 1, b = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
System.out.print(b + " ");
elseSystem.out.print(a + " ");
}
System.out.println();
}
}
}
Clarify
Knowledge

Nested
loops

Write the programs to display the following patterns:


(g)
*
*#
*#*
*#*#
*#*#*
public class Pattern
{
public void displayPattern() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
System.out.print("# ");
else
System.out.print("* ");
}
System.out.println();
}
}
}
Clarify
Knowledge

Nested
loops

Using the switch statement, write a menu driven program for


the following:
(a) To print the Floyd's triangle:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
(b) To display the following pattern:
I
IC
ICS
ICSE
For an incorrect option, an appropriate error message should be
displayed.
import java.util.Scanner;
public class Pattern
{
public void choosePattern() {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Floyd's triangle");
System.out.println("Type 2 for an ICSE pattern");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
break;
Clarify
Knowledge

case 2:
String s = "ICSE";
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j <= i; j++) {
System.out.print(s.charAt(j) + " ");
}
System.out.println();
}
break;
default:
System.out.println("Incorrect Choice");
}
}
}
Clarify
Knowledge

Character
Manipulation
Write a program in Java to accept an integer number N
such that 0<N<27. Display the corresponding letter of
the alphabet (i.e. the letter at position N).
[Hint: If N =1 then display A]

import java.util.Scanner;
public class Integer2Letter
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter integer: ");
int n = in.nextInt();
if (n > 0 && n < 27) {
char ch = (char)(n + 64);
System.out.println("Corresponding letter = " + ch);
}
else {
System.out.println("Please enter a number in 1 to 26
range");
}
}
}
Clarify
Knowledge

Character
Manipulation

Write a program to input a letter. Find its ASCII code.


Reverse the ASCII code and display the equivalent
character.
Sample Input: Y
Sample Output: ASCII Code = 89
Reverse the code = 98
Equivalent character: b
import java.util.Scanner;
public class ASCIIReverse
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a letter: ");
char l = in.next().charAt(0);
int a = (int)l;
System.out.println("ASCII Code = " + a);
int r = 0;
while (a > 0) {
int digit = a % 10;
r = r * 10 + digit;
a /= 10;
}
System.out.println("Reversed Code = " + r);
System.out.println("Equivalent character = " + (char)r);
}
}
Clarify
Knowledge

Character
Manipulation

Write a menu driven program to display


(i) first five upper case letters
(ii) last five lower case letters as per the user's choice.
Enter '1' to display upper case letters and enter '2' to
display lower case letters.
import java.util.Scanner;
public class MenuUpLowCase
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter '1' to display upper case
letters");
System.out.println("Enter '2' to display lower case
letters");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
for (int i = 65; i <= 69; i++)
System.out.println((char)i);
break;
case 2:
for (int i = 118; i <= 122; i++)
System.out.println((char)i);
break;
default:
break;
}
}
}
Clarify
Knowledge

Character
Manipulation

Write a program in Java to display the following


patterns:
(i)
A
ab
ABC
abcd
ABCDE
public class Pattern
{
public static void main(String args[]) {
for (int i = 65; i < 70; i++) {
for (int j = 65; j <= i; j++) {
if (i % 2 == 0)
System.out.print((char)(j+32));
elseSystem.out.print((char)j);
}
System.out.println();
}
}
}
Clarify
Knowledge

Character
Manipulation

Write a program in Java to display the following


patterns:
(ii)
ZYXWU
ZYXW
ZYX
ZY
Z
public class Pattern
{
public static void main(String args[]) {
for (int i = 86; i <= 90; i++) {
for (int j = 90; j >= i; j--) {
System.out.print((char)j);
}
System.out.println();
}
}
}
Clarify
Knowledge

Arrays

Write a program in Java to store 20 numbers (even and


odd numbers) in a Single Dimensional Array (SDA).
Calculate and display the sum of all even numbers and
all odd numbers separately.
import java.util.Scanner;
public class SDAOddEvenSum
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[ ] = new int[20];
System.out.println("Enter 20 numbers");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
int oddSum = 0, evenSum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
evenSum += arr[i];
elseoddSum += arr[i];
}
System.out.println("Sum of Odd numbers = " +
oddSum);
System.out.println("Sum of Even numbers = " +
evenSum);
}
}
Clarify
Knowledge

Arrays

Write a program in Java to store 20 temperatures in °F


in a Single Dimensional Array (SDA) and display all the
temperatures after converting them into °C.
Hint: (c/5) = (f - 32) / 9
import java.util.Scanner;
public class SDAF2C
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
double arr[] = new double[20];
System.out.println("Enter 20 temperatures in degree
Fahrenheit");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextDouble();
}
System.out.println("Temperatures in degree
Celsius");
for (int i = 0; i < arr.length; i++) {
double tc = 5 * ((arr[i] - 32) / 9);
System.out.println(tc);
}
}
}
Clarify
Knowledge

Arrays

Write a program in Java to store 20 numbers in a Single


Dimensional Array (SDA). Display the numbers which
are prime.
import java.util.Scanner;
public class PrimeNumbers
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[] = new int[20];
System.out.println("Enter 20 numbers");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
System.out.println("Prime Numbers:");
for (int i = 0; i < arr.length; i++) {
int c = 0;
for (int j = 1; j <= arr[i]; j++) {
if (arr[i] % j == 0) {
c++;
}
}
if (c == 2)
System.out.print(arr[i] + ", ");
}
}
}
Clarify
Knowledge

Arrays

Write a program in Java using arrays:


(a) To store the Roll No., Name and marks in six
subjects for 100 students.
(b) Calculate the percentage of marks obtained by
each candidate. The maximum marks in each subject
are 100.
(c) Calculate the Grade as per the given criteria:
Percentage MarksGrade
From 80 to 100 A
From 60 to 79. B
From 40 to 59 C
Less than 40. D
import java.util.Scanner;
public class SDAGrades
{
public static void main(String args[]) {
final int TOTAL_STUDENTS = 100;
Scanner in = new Scanner(System.in);
int rollNo[ ]= new int[TOTAL_STUDENTS];
String name[ ]= new String[TOTAL_STUDENTS];
int s1[ ]= new int[TOTAL_STUDENTS];
int s2[ ]= new int[TOTAL_STUDENTS];
int s3[ ]= new int[TOTAL_STUDENTS];
int s4[ ]= new int[TOTAL_STUDENTS];
int s5[ ]= new int[TOTAL_STUDENTS];
int s6[ ]= new int[TOTAL_STUDENTS];
double p[ ] = new double[TOTAL_STUDENTS];
char g[ ] = new char[TOTAL_STUDENTS];
for (int i = 0; i < TOTAL_STUDENTS; i++) {
Clarify
Knowledge

System.out.println("Enter student " + (i+1) + " details:");


System.out.print("Roll No: ");
rollNo[i] = in.nextInt();
in.nextLine();
System.out.print("Name: ");
name[i] = in.nextLine();
System.out.print("Subject 1 Marks: ");
s1[i] = in.nextInt();
System.out.print("Subject 2 Marks: ");
s2[i] = in.nextInt();
System.out.print("Subject 3 Marks: ");
s3[i] = in.nextInt();
System.out.print("Subject 4 Marks: ");
s4[i] = in.nextInt();
System.out.print("Subject 5 Marks: ");
s5[i] = in.nextInt();
System.out.print("Subject 6 Marks: ");
s6[i] = in.nextInt();
p[i] = (((s1[i] + s2[i] + s3[i] + s4[i]
+ s5[i] + s6[i]) / 600.0) * 100);
if (p[i] < 40)
g[i] = 'D';
else if (p[i] < 60)
g[i] = 'C';
else if (p[i] < 80)
g[i] = 'B';
elseg[i] = 'A';
}
System.out.println();
for (int i = 0; i < TOTAL_STUDENTS; i++) {
System.out.println(rollNo[i] + "\t"
+ name[i] + "\t"
+ p[i] + "\t"
+ g[i]);
}
}
}
Clarify
Knowledge

Arrays

Write a program to accept a list of 20 integers. Sort the


first 10 numbers in ascending order and next the 10
numbers in descending order by using 'Bubble Sort'
technique. Finally, print the complete list of integers.
import java.util.Scanner;
public class SDABubbleSort
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[] = new int[20];
System.out.println("Enter 20 numbers:");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
//Sort first half in ascending orderfor (int i = 0; i < arr.length /
2 - 1; i++) {
for (int j = 0; j < arr.length / 2 - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = t;
}
}
}
//Sort second half in descending orderfor (int i = 0; i <
arr.length / 2 - 1; i++) {
for (int j = arr.length / 2; j < arr.length - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int t = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = t;
}
}
}
//Print the final sorted arraySystem.out.println("\nSorted
Array:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Clarify
Knowledge

Arrays

Write a program in Java to accept 20 numbers in a


single dimensional array arr[20]. Transfer and store all
the even numbers in an array even[ ] and all the odd
numbers in another array odd[ ]. Finally, print the
elements of both the arrays.
import java.util.Scanner;
public class SDAEvenOdd
{
public static void main(String args[]) {
final int NUM_COUNT = 20;
Scanner in = new Scanner(System.in);
int i = 0;
int arr[] = new int[NUM_COUNT];
int even[] = new int[NUM_COUNT];
int odd[] = new int[NUM_COUNT];
System.out.println("Enter 20 numbers:");
for (i = 0; i < NUM_COUNT; i++) {
arr[i] = in.nextInt();
}
int eIdx = 0, oIdx = 0;
for (i = 0; i < NUM_COUNT; i++) {
if (arr[i] % 2 == 0)
even[eIdx++] = arr[i];
elseodd[oIdx++] = arr[i];
}
System.out.println("Even Numbers:");
for (i = 0; i < eIdx; i++) {
System.out.print(even[i] + " ");
}
System.out.println("\nOdd Numbers:");
for (i = 0; i < oIdx; i++) {
System.out.print(odd[i] + " ");
}
}
}
Clarify
Knowledge

Arrays

A double dimensional array is defined as N[4][4] to


store numbers. Write a program to find the sum of all
even numbers and product of all odd numbers of the
elements stored in Double Dimensional Array (DDA).
import java.util.Scanner;
public class DDAEvenOdd
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N[][] = new int[4][4];
long evenSum = 0, oddProd = 1;
System.out.println("Enter the elements of 4x4 DDA: ");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
N[i][j] = in.nextInt();
if (N[i][j] % 2 == 0)
evenSum += N[i][j];
else
OddProd *= N[i][j];
}
}
System.out.println("Sum of all even numbers = " + evenSum);
System.out.println("Product of all odd numbers = " +
oddProd);
}
}
Clarify
Knowledge

Strings

Write a program to input a sentence. Find and display


the following:
(i) Number of words present in the sentence
(ii) Number of letters present in the sentence
Assume that the sentence has neither include any digit
nor a special character.

import java.util.Scanner;
public class WordsNLetters
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
int wCount = 0, lCount = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ')
wCount++;
elselCount++;
}
System.out.println("No. of words = " + wCount);
System.out.println("No. of letters = " + lCount);
}
}
Clarify
Knowledge

Strings

Write a program in Java to accept a word/a String and


display the new string after removing all the vowels
present in it.
Sample Input: COMPUTER APPLICATIONS
Sample Output: CMPTR PPLCTNS

import java.util.Scanner;
public class VowelRemoval
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or sentence:");
String str = in.nextLine();
int len = str.length();
String newStr = "";
for (int i = 0; i < len; i++) {
char ch = Character.toUpperCase(str.charAt(i));
if (ch == 'A' ||
ch == 'E' ||
ch == 'I' ||
ch == 'O' ||
ch == 'U') {
continue;
}
newStr = newStr + ch;
}
System.out.println("String with vowels removed");
System.out.println(newStr);
}
}
Clarify
Knowledge

Strings

Write a program in Java to accept a name(Containing


three words) and display only the initials (i.e., first letter
of each word).
Sample Input: LAL KRISHNA ADVANI
Sample Output: L K A

import java.util.Scanner;
public class NameInitials
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a name of 3 or more
words:");
String str = in.nextLine();
int len = str.length();
System.out.print(str.charAt(0) + " ");
for (int i = 1; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ') {
char ch2 = str.charAt(i + 1);
System.out.print(ch2 + " ");
}
}
}
}
Clarify
Knowledge

Strings

Write a program in Java to accept a name containing


three words and display the surname first, followed by
the first and middle names.
Sample Input: MOHANDAS KARAMCHAND GANDHI
Sample Output: GANDHI MOHANDAS KARAMCHAND
import java.util.Scanner;
public class SurnameFirst
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a name of 3 words:");
String name = in.nextLine();
Int lastSpaceIdx = name.lastIndexOf(' ');
String surname = name.substring(lastSpaceIdx + 1);
String initialName = name.substring(0, lastSpaceIdx);
System.out.println(surname + " " + initialName);
}
}
Clarify
Knowledge

Strings

Write a program in Java to enter a String/Sentence and


display the longest word and the length of the longest
word present in the String.
Sample Input: “TATA FOOTBALL ACADEMY WILL PLAY
AGAINST MOHAN BAGAN”
Sample Output: The longest word: FOOTBALL: The length
of the word: 8
import java.util.Scanner;
public class LongestWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or sentence:");
String str = in.nextLine();
str += " "; //Add space at end of stringString word = "",
lWord = "";
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ') {
if (word.length() > lWord.length())
lWord = word;
word = "";
}
else {
word += ch;
}
}
System.out.println("The longest word: " + lWord +
": The length of the word: " + lWord.length());
}
}
Clarify
Knowledge

Strings

Write a program in Java to accept a word and display


the ASCII code of each character of the word.
Sample Input: BLUEJ
Sample Output:
ASCII of B = 66
ASCII of L = 76
ASCII of U = 85
ASCII of E = 69
ASCII of J = 74
import java.util.Scanner;
public class ASCIICode
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
int len = word.length();
for (int i = 0; i < len; i++) {
char ch = word.charAt(i);
System.out.println("ASCII of " + ch
+ " = " + (int)ch);
}
}
}
Clarify
Knowledge

Strings

Write a program in Java to accept a String in upper


case and replace all the vowels present in the String
with Asterisk (*) sign.
Sample Input: "TATA STEEL IS IN JAMSHEDPUR"
Sample output: T*T* ST**L *S *N J*MSH*DP*R
import java.util.Scanner;
public class VowelReplace
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string in
uppercase:");
String str = in.nextLine();
String newStr = "";
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == 'A' ||
ch == 'E' ||
ch == 'I' ||
ch == 'O' ||
ch == 'U') {
newStr = newStr + '*';
}
else {
newStr = newStr + ch;
}
}
System.out.println(newStr);
}
}
Clarify
Knowledge

Strings

Write a program in Java to enter a sentence. Frame a


word by joining all the first characters of each word of
the sentence. Display the word.
Sample Input: Vital Information Resource Under Seize
Sample Output: VIRUS
import java.util.Scanner;
public class FrameWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
String word = "" + str.charAt(0);
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ')
word += str.charAt(i + 1);
}
System.out.println(word);
}
}
Clarify
Knowledge

Strings

Write a program in Java to enter a sentence. Display


the words which are only palindrome.
Sample Input: MOM AND DAD ARE NOT AT HOME
Sample Output: MOM
DAD
import java.util.Scanner;
public class PalinWords
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
str = str + " ";
String word = "";
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ') {
int wordLen = word.length();
boolean isPalin = true;
for (int j = 0; j < wordLen / 2; j++) {
if (word.charAt(j) !=word.charAt(wordLen - 1 - j)) {
isPalin = false;
break;
}
}
if (isPalin)
System.out.println(word);
word = "";
}
else {
word += ch;
}
}
}
}
Clarify
Knowledge

Strings

Write a program to accept a word and convert it into


lower case, if it is in upper case. Display the new word
by replacing only the vowels with the letter following it.
Sample Input: computer
Sample Output: cpmpvtfr
import java.util.Scanner;
public class VowelReplace
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = in.nextLine();
str = str.toLowerCase();
String newStr = "";
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (str.charAt(i) == 'a' ||
str.charAt(i) == 'e' ||
str.charAt(i) == 'i' ||
str.charAt(i) == 'o' ||
str.charAt(i) == 'u') {
char nextChar = (char)(ch + 1);
newStr = newStr + nextChar;
}
else {
newStr = newStr + ch;
}
}
System.out.println(newStr);
}
}
Clarify
Knowledge

Strings

Write a program to input a sentence. Create a new sentence by


replacing each consonant with the previous letter. If the previous
letter is a vowel then replace it with the next letter (i.e., if the letter is B
then replace it with C as the previous letter of B is A). Other characters
must remain the same. Display the new sentence.
Sample Input : ICC WORLD CUP
Sample Output : IBB VOQKC BUQ
import java.util.Scanner;
public class ReplaceLetters
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String str = in.nextLine();
int len = str.length();
String newStr = "";
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
char chUp = Character.toUpperCase(ch);
if (chUp == 'A'
|| chUp == 'E'
|| chUp == 'I'
|| chUp == 'O'
|| chUp == 'U') {
newStr = newStr + ch;
}
else {
char prevChar = (char)(ch - 1);
char prevCharUp = Character.toUpperCase(prevChar);
if (prevCharUp == 'A'
|| prevCharUp == 'E'
|| prevCharUp == 'I'
|| prevCharUp == 'O'
|| prevCharUp == 'U') {
newStr = newStr + (char)(ch + 1);
}
else {
newStr = newStr + prevChar;
}
}
}
System.out.println(newStr);
}
}
Clarify
Knowledge

Strings

Write a program to generate a triangle or an inverted triangle based


upon User’s choice.
Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter a word : BLUEJ
Sample Output:
B
LL
UUU
EEEE
JJJJJ
import java.util.Scanner;
public class TriangleMenu
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for a triangle and");
System.out.println("Type 2 for an inverted triangle");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
in.nextLine();
System.out.print("Enter a word: ");
String word = in.nextLine();
int len = word.length();
switch (choice) {
case 1:
for(int i = 0; i < len; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(word.charAt(i));
}
System.out.println();
}
break;
case 2:
for(int i = len - 1; i >= 0; i--) {
for(int j = 0; j <= i; j++) {
System.out.print(word.charAt(j));
}
System.out.println();
}
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}

You might also like