0% found this document useful (0 votes)
19 views31 pages

PROGRAM NO - Docxvk

Uploaded by

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

PROGRAM NO - Docxvk

Uploaded by

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

PROGRAM NO:1

PROBLEM DEFINATION:Write a program to accept the marks in Physics, Chemistry


and Maths secured by 5 students
of a class in three different single-Dimensional Arrays. Find and display the following:
i. Number of students securing 80% and above in aggregate.
ii. Number of students securing 30% and below in aggregate

ALGORITHM:
START
· Initialize Arrays: Create three single-dimensional arrays to store Physics,
Chemistry, and Maths marks for 5 students.
· Input Marks: For each student, input the marks for Physics, Chemistry, and Maths
and store them in the respective arrays.
· Initialize Counters: Set counters for students securing 80% and above, and 30%
and below.
· Calculate Aggregate:For each student, calculate the aggregate of marks from the
three subjects.Compute the percentage from the aggregate.
· Categorize Students:

 If the percentage is 80% or above, increment the count80AndAbove.


 If the percentage is 30% or below, increment the count30AndBelow.

· Display Results: Print the counts of students in each category.


· Close Scanner: Close the Scanner object to prevent resource leaks.
STOP

PROGRAM CODE:
import java.util.Scanner;

public class StudentMarks {

// Method to calculate aggregate percentage


public static double calculateAggregate(int[] marks) {
int total = 0;
for (int mark : marks) {
total += mark;
}
return (double) total / marks.length;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Number of students
final int NUM_STUDENTS = 5;
int[] physicsMarks = new int[NUM_STUDENTS];
int[] chemistryMarks = new int[NUM_STUDENTS];
int[] mathsMarks = new int[NUM_STUDENTS];

// Input marks for each student


for (int i = 0; i < NUM_STUDENTS; i++) {
System.out.println("Enter marks for Student " + (i + 1) + ":");
System.out.print("Physics: ");
physicsMarks[i] = scanner.nextInt();
System.out.print("Chemistry: ");
chemistryMarks[i] = scanner.nextInt();
System.out.print("Maths: ");
mathsMarks[i] = scanner.nextInt();
}

// Initialize counters
int count80AndAbove = 0;
int count30AndBelow = 0;

// Calculate aggregate and categorize students


for (int i = 0; i < NUM_STUDENTS; i++) {
int[] marks = {physicsMarks[i], chemistryMarks[i], mathsMarks[i]};
double aggregate = calculateAggregate(marks);
double percentage = (aggregate / 300) * 100;

if (percentage >= 80) {


count80AndAbove++;
}
if (percentage <= 30) {
count30AndBelow++;
}
}

// Display results
System.out.println("Number of students securing 80% and above in aggregate: "
+ count80AndAbove);
System.out.println("Number of students securing 30% and below in aggregate: "
+ count30AndBelow);

scanner.close();
}
}
INPUT AND OUTPUT:

Variable Description Table

Variable Name Description Type


NUM_STUDENTS Constant indicating the number of students final int
physicsMarks Array storing marks obtained in Physics int[]
chemistryMarks Array storing marks obtained in Chemistry int[]
mathsMarks Array storing marks obtained in Maths int[]
count80AndAbove Counter for students securing 80% and above int
count30AndBelow Counter for students securing 30% and below int
marks Temporary array to store marks for a student int[]
aggregate Aggregate of marks for a student double
percentage Percentage calculated from aggregate double

Method Description Table

Return
Method Name Description Parameters
Type
Calculates the aggregate int[] marks (array of
calculateAggregate double
percentage of marks marks)
PROGRAM NO:2
PROBLEM DEFINATION:Write a program to accept 20 integer numbers in single
Dimensional
Array. Using menu driven approach display the following, as per user's choice:
i. All the perfect numbers store in the array.
ii. All the Buzz numbers store in the array.
A number whose sum of factors (including 1 and excluding the number itself) is the
same is said to be a perfect number.
A number that is divisible by 7 or has last digit as 7, is said to be a buzz number.

ALGORITHM:
· Start
· Declare an array numbers of size 20.
· Prompt the user to enter 20 integer numbers and store them in the array numbers.
· Display a menu with options:
a. "Display all perfect numbers in the array"
b. "Display all buzz numbers in the array"
c. "Exit"
· Accept the user's choice.
· If choice is 1:
a. Call displayPerfectNumbers() to display all perfect numbers in the array.
· If choice is 2:
a. Call displayBuzzNumbers() to display all buzz numbers in the array.
· If choice is 3:
a. Exit the program.
· If choice is invalid, display an error message and repeat steps 4 to 5.
· End
PROGRAM CODE:
import java.util.Scanner;

public class Number {


// Method to check if a number is perfect
public static boolean isPerfect(int num) {
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum == num;
}

// Method to check if a number is buzz


public static boolean isBuzz(int num) {
return (num % 7 == 0) || (num % 10 == 7);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int[] numbers = new int[20];

// Accepting 20 numbers into the array


System.out.println("Enter 20 integer numbers:");
for (int i = 0; i < 20; i++) {
numbers[i] = sc.nextInt();
}

while (true) {
// Displaying menu to the user
System.out.println("\nMenu:");
System.out.println("1. Display all Perfect numbers");
System.out.println("2. Display all Buzz numbers");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();

switch (choice) {
case 1:
// Displaying perfect numbers
System.out.println("Perfect numbers in the array:");
boolean foundPerfect = false;
for (int num : numbers) {
if (isPerfect(num)) {
System.out.print(num + " ");
foundPerfect = true;
}
}
if (!foundPerfect) {
System.out.println("None");
}
break;

case 2:
// Displaying buzz numbers
System.out.println("Buzz numbers in the array:");
boolean foundBuzz = false;
for (int num : numbers) {
if (isBuzz(num)) {
System.out.print(num + " ");
foundBuzz = true;
}
}
if (!foundBuzz) {
System.out.println("None");
}
break;

case 3:
// Exit the program
System.out.println("Exiting...");
sc.close();
return;

default:
System.out.println("Invalid choice! Please try again.");
}
}
}
}

INPUT AND OUTPUT:

Variable Description Table

Variable Data
Purpose
Name Type
numbers int[] Array to store 20 integer numbers entered by the user.
choice int Stores the user's menu choice.
num int Represents the number to check if it is perfect or buzz.
Used to calculate the sum of factors for perfect number
sum int
checking.
i int Loop control variable used for iteration.

Method Description Table

Method Name Purpose


displayPerfectNumbers(int[] array) Displays all perfect numbers stored in the array.
isPerfectNumber(int num) Checks if a given number is a perfect number.
displayBuzzNumbers(int[] array) Displays all buzz numbers stored in the array.
isBuzzNumber(int num) Checks if a given number is a buzz number.
PROGRAM NO:3

PROBLEM DEFINATION:Write a program to accept 10 integer numbers in single


Dimensional Array. Using menu
driven approach display the following, as per user's choice:
Case 1: ascending order sorting using bubble sort
Case 2: descending order sorting using selection sort.

ALGORITHM:
· Start
· Declare an array numbers of size 10.
· Prompt the user to enter 10 integer numbers and store them in the array numbers.
· Display a menu with options:
a. "Sort in ascending order using Bubble Sort"
b. "Sort in descending order using Selection Sort"
c. "Exit"
· Accept the user's choice.
· If choice is 1:
a. Call bubbleSortAscending() to sort the array in ascending order.
b. Display the sorted array.
· If choice is 2:
a. Call selectionSortDescending() to sort the array in descending order.
b. Display the sorted array.
· If choice is 3:
a. Exit the program.
· If choice is invalid, display an error message and repeat steps 4 to 5.
· End

PROGRAM CODE:
import java.util.Scanner;

public class ArraySorter {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] numbers = new int[10];

// Accepting 10 numbers into the array


System.out.println("Enter 10 integer numbers:");
for (int i = 0; i < 10; i++) {
numbers[i] = sc.nextInt();
}

while (true) {
// Displaying menu to the user
System.out.println("\nMenu:");
System.out.println("1. Ascending order sorting using Bubble Sort");
System.out.println("2. Descending order sorting using Selection Sort");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();

switch (choice) {
case 1:
// Ascending order sorting using Bubble Sort
bubbleSortAscending(numbers);
System.out.println("Array sorted in ascending order:");
displayArray(numbers);
break;

case 2:
// Descending order sorting using Selection Sort
selectionSortDescending(numbers);
System.out.println("Array sorted in descending order:");
displayArray(numbers);
break;

case 3:
// Exit the program
System.out.println("Exiting...");
sc.close();
return;

default:
System.out.println("Invalid choice! Please try again.");
}
}
}

// Method to sort the array in ascending order using Bubble Sort


public static void bubbleSortAscending(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// Method to sort the array in descending order using Selection Sort


public static void selectionSortDescending(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int maxIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] > arr[maxIdx]) {
maxIdx = j;
}
}
// Swap arr[i] and arr[maxIdx]
int temp = arr[maxIdx];
arr[maxIdx] = arr[i];
arr[i] = temp;
}
}
// Method to display the array
public static void displayArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}
INPUT AND OUTPUT:

Variable Description Table

Variable Data
Purpose
Name Type
numbers int[] Array to store 10 integer numbers entered by the user.
choice int Stores the user's menu choice.
n int Length of the array in sorting methods.
temp int Temporary variable used for swapping elements.
Index of the largest element in the unsorted portion of the
maxIndex int
array for selection sort.
i, j int Loop control variables.

Method Description Table

Method Name Purpose


Sorts the array in ascending order using the
bubbleSortAscending(int[] array)
Bubble Sort algorithm.
selectionSortDescending(int[] Sorts the array in descending order using the
array) Selection Sort algorithm.
displayArray(int[] array) Displays the elements of the array.

PROGRAM:4
PROBLEM DEFINATION:Write a program to accept 20 double type numbers in
single Dimensional Array. Using menu
driven approach display the following, as per user's choice:
Case 1: searching an element using linear search algorithm
Case 2: searching an element using binary search algorithm on a sorted array (apply
any sorting on the array)

ALGORITHM:
· Start
· Declare an array numbers of size 20 to store double-type numbers.
· Prompt the user to enter 20 double-type numbers and store them in the array
numbers.
· Display a menu with options:
a. "Search an element using Linear Search"
b. "Search an element using Binary Search on a sorted array"
c. "Exit"
· Accept the user's choice.
· If choice is 1:
a. Prompt the user to enter the element to search using linear search.
b. Call linear Search() to search for the element in the array.
c. If the element is found, display its index; otherwise, display "Element not found."
· If choice is 2:
a. Sort the array using any sorting method (e.g., Arrays.sort()).
b. Prompt the user to enter the element to search using binary search.
c. Call binary Search() to search for the element in the sorted array.
d. If the element is found, display its index; otherwise, display "Element not found."
· If choice is 3:
a. Exit the program.
· If choice is invalid, display an error message and repeat steps 4 to 5.
· End

PROGRAM CODE:

import java.util.Scanner;
import java.util.Arrays;

public class ArraySearcher {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double[] numbers = new double[20];

// Accepting 20 numbers into the array


System.out.println("Enter 20 double-type numbers:");
for (int i = 0; i < 20; i++) {
numbers[i] = sc.nextDouble();
}

while (true) {
// Displaying menu to the user
System.out.println("\nMenu:");
System.out.println("1. Search an element using Linear Search");
System.out.println("2. Search an element using Binary Search (on a sorted
array)");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();

switch (choice) {
case 1:
// Linear search
System.out.print("Enter the element to search (Linear Search): ");
double elementToSearch = sc.nextDouble();
int linearSearchResult = linearSearch(numbers, elementToSearch);
if (linearSearchResult == -1) {
System.out.println("Element not found in the array.");
} else {
System.out.println("Element found at index: " + linearSearchResult);
}
break;

case 2:
// Binary search after sorting the array
System.out.println("Sorting the array for Binary Search...");
bubbleSort(numbers);
System.out.print("Enter the element to search (Binary Search): ");
double elementToSearchBinary = sc.nextDouble();
int binarySearchResult = binarySearch(numbers,
elementToSearchBinary);
if (binarySearchResult == -1) {
System.out.println("Element not found in the array.");
} else {
System.out.println("Element found at index: " + binarySearchResult);
}
break;

case 3:
// Exit the program
System.out.println("Exiting...");
sc.close();
return;

default:
System.out.println("Invalid choice! Please try again.");
}
}
}

// Method for Linear Search


public static int linearSearch(double[] arr, double key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
return i; // Return the index where the element is found
}
}
return -1; // Element not found
}

// Method for Binary Search (array must be sorted)


public static int binarySearch(double[] arr, double key) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;

// Check if key is present at mid


if (arr[mid] == key) {
return mid;
}

// If key is greater, ignore the left half


if (arr[mid] < key) {
left = mid + 1;
} else { // If key is smaller, ignore the right half
right = mid - 1;
}
}
return -1; // Element not found
}

// Method to sort the array in ascending order using Bubble Sort


public static void bubbleSort(double[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
double temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("Array sorted: " + Arrays.toString(arr));
}
}

INPUT AND OUTPUT:


Variable Description Table
Variable Data
Purpose
Name Type
numbers double[] Array to store 20 double-type numbers entered by the user.
choice int Stores the user's menu choice.
element1 double The element to be searched using linear search.
element2 double The element to be searched using binary search.
Index where the element is found using linear search, or -1
index1 int
if not found.
Index where the element is found using binary search, or -1
index2 int
if not found.
left int Left boundary for binary search.
right int Right boundary for binary search.
middle int Middle index for binary search calculation.
i int Loop control variable for iteration.

Method Description Table

Method Name Purpose


linearSearch(double[] array, Searches for the specified element in the array
double element) using the linear search algorithm.
binarySearch(double[] array, Searches for the specified element in the sorted
double element) array using the binary search algorithm.

PROGRAM NO:5

PROBLEM DEFINATION:Write a program to accept 10 states and 10 capitals of our


country in 2 different single
dimensional arrays. Now, enter a state of the country to display its capital.
If it is present then display its capital otherwise, display a relevant message.
Sample input: enter the state and the capital
Bihar
Patna
.
..
West Bengal
Kolkata
and so on------------
Sample Output: enter the state whose capital is to be searched:
West Bengal
The capital is Kolkata

ALGORITHM:
· Start
· Declare two arrays: states and capitals, both of size 10 to store state names and
their corresponding capitals.
· Prompt the user to enter 10 states and their capitals and store them in the arrays.
· Prompt the user to enter the state whose capital is to be searched.
· Call the searchStateIndex() method to find the index of the entered state in the
states array.
· If the index is not -1:
a. Display the corresponding capital from the capitals array.
· Else:
a. Display a message indicating that the state is not present in the list.
· End

PROGRAM CODE:
import java.util.Scanner;

public class StateCapitalProgram {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] states = new String[10];
String[] capitals = new String[10];

// Accept 10 states and their corresponding capitals


System.out.println("Enter 10 states and their capitals:");
for (int i = 0; i < 10; i++) {
System.out.print("Enter state " + (i + 1) + ": ");
states[i] = sc.nextLine();
System.out.print("Enter capital of " + states[i] + ": ");
capitals[i] = sc.nextLine();
}

// Prompt user to enter a state to search for its capital


System.out.print("\nEnter the state whose capital is to be searched: ");
String searchState = sc.nextLine();

// Search and display the capital of the entered state


int index = searchStateIndex(states, searchState);
if (index != -1) {
System.out.println("The capital is " + capitals[index] + ".");
} else {
System.out.println("The state is not present in the list.");
}
sc.close();
}

// Method to search for the state index in the array


public static int searchStateIndex(String[] states, String searchState) {
for (int i = 0; i < states.length; i++) {
if (states[i].equalsIgnoreCase(searchState)) {
return i; // Return the index if state is found
}
}
return -1; // Return -1 if state is not found
}
}

INPUT AND OUTPUT:


Variable Description Table

Data
Variable Name Purpose
Type
states String[] Array to store the names of 10 states entered by the user.
capitals String[] Array to store the corresponding capitals of the 10 states.
The state whose capital is to be searched, entered by the
searchState String
user.
Index of the searched state in the states array, or -1 if not
index int
found.
i int Loop control variable for iteration.

Method Description Table

Method Name Purpose


searchStateIndex(String[] states, String Searches for the index of the specified
searchState) state in the states array.
PROGRAM NO:6

PROBLEM DEFINATION: Write a program in Java to store 10 city names in single


Dimensional Array. Display only those words/names, which begin with a consonant
but end with a vowel.
ALGORITHM:
· Start
· Declare an array cities of size 10 to store city names.
· Prompt the user to enter 10 city names and store them in the cities array.
· Iterate through each city name in the cities array.
a. For each city name, check if it starts with a consonant using
startsWithConsonant().
b. Check if the city name ends with a vowel using endsWithVowel().
c. If both conditions are satisfied, display the city name.
· Close the scanner.
· End
PROGRAM CODE:
import java.util.Scanner;

public class CityNamesProgram {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] cities = new String[10];

// Accept 10 city names from the user


System.out.println("Enter 10 city names:");
for (int i = 0; i < 10; i++) {
cities[i] = sc.nextLine();
}

System.out.println("\nCities that start with a consonant and end with a vowel:");


for (String city : cities) {
if (startsWithConsonant(city) && endsWithVowel(city)) {
System.out.println(city);
}
}
sc.close();
}

// Method to check if a string starts with a consonant


public static boolean startsWithConsonant(String word) {
char firstChar = Character.toLowerCase(word.charAt(0));
return firstChar >= 'a' && firstChar <= 'z' &&
!(firstChar == 'a' || firstChar == 'e' || firstChar == 'i' || firstChar == 'o' ||
firstChar == 'u');
}

// Method to check if a string ends with a vowel


public static boolean endsWithVowel(String word) {
char lastChar = Character.toLowerCase(word.charAt(word.length() - 1));
return lastChar == 'a' || lastChar == 'e' || lastChar == 'i' || lastChar == 'o' ||
lastChar == 'u';
}
}

INPUT AND OUTPUT:


Variable Description Table

Variable Data
Purpose
Name Type
cities String[] Array to store 10 city names entered by the user.
city String Holds each city name during iteration over the array.
Stores the first character of a city name in lowercase for
firstChar char
checking.
Stores the last character of a city name in lowercase for
lastChar char
checking.
i int Loop control variable for iteration.

Method Description Table

Method Name Purpose


startsWithConsonant(String word) Checks if the given string starts with a consonant.
endsWithVowel(String word) Checks if the given string ends with a vowel.

PROGRAM NO:7

PROBLEM DEFINATION: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

ALGORITHM:
· Start
· Accept a word from the user and store it in the variable word.
· Convert the word to lowercase and store it in lowerCaseWord.
· Call the method replaceVowels(lowerCaseWord) to replace each vowel in the word
with the letter following it in the alphabet.
a. Initialize a StringBuilder named result.
b. Iterate through each character of the word:

 If the character is a vowel ('a', 'e', 'i', 'o', 'u'), append the next letter in the
alphabet to result.
 Else, append the character itself to result.
c. Return the modified string from result.

· Display the new word.


· End

PROGRAM CODE:
import java.util.Scanner;

public class VowelReplacementProgram {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Accept a word from the user


System.out.print("Enter a word: ");
String word = sc.nextLine();

// Convert the word to lowercase


String lowerCaseWord = word.toLowerCase();

// Replace vowels with the following letter


String newWord = replaceVowels(lowerCaseWord);

// Display the new word


System.out.println("Output: " + newWord);
sc.close();
}

// Method to replace vowels in the word with the letter following them
public static String replaceVowels(String word) {
StringBuilder result = new StringBuilder();

for (int i = 0; i < word.length(); i++) {


char ch = word.charAt(i);
switch (ch) {
case 'a': result.append('b'); break;
case 'e': result.append('f'); break;
case 'i': result.append('j'); break;
case 'o': result.append('p'); break;
case 'u': result.append('v'); break;
default: result.append(ch); // Append non-vowel characters as they are
}
}
return result.toString();
}
}

INPUT AND OUTPUT:

Variable Description Table


Variable Name Data Type Purpose
word String The word entered by the user.
lowerCaseWord String The word converted to lowercase.
The modified word after replacing vowels with their
newWord String
following letters.
Used to build the modified string after vowel
result StringBuilder
replacement.
Loop control variable for iterating over the characters of
i int
the word.
ch char Holds the current character in the word during iteration.

Method Description Table

Method Name Purpose


replaceVowels(String Replaces each vowel in the word with the letter following it
word) in the alphabet.

PROGRAM CODE: 8

PROBLEM DEFINATION: Write a program to accept a sentence. Display the


sentence in reversing order of its word.
Sample Input: Computer is Fun
Sample Output: Fun is Computer
ALGORITHM:
· Start
· Accept a sentence from the user and store it in the variable sentence.
· Call the method reverseWords(sentence) to reverse the order of words in the
sentence:
a. Split the sentence into words using spaces as a delimiter and store them in the
array words.
b. Initialize a StringBuilder named reversed.
c. Iterate through the words array in reverse order:

 Append each word to reversed.


 If the current word is not the last one, append a space after it.
d. Return the reversed sentence as a string.

· Display the reversed sentence.


· End

PROGRAM CODE:
import java.util.Scanner;

public class ReverseWordsProgram {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Accept a sentence from the user


System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();

// Reverse the order of words in the sentence


String reversedSentence = reverseWords(sentence);

// Display the reversed sentence


System.out.println("Output: " + reversedSentence);
sc.close();
}

// Method to reverse the order of words in a sentence


public static String reverseWords(String sentence) {
// Split the sentence into words based on spaces
String[] words = sentence.split(" ");
StringBuilder reversed = new StringBuilder();

// Append the words in reverse order to the StringBuilder


for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]);
if (i != 0) {
reversed.append(" "); // Add space between words
}
}
return reversed.toString();
}
}
INPUT AND OUTPUT:

Variable Description Table


Variable Name Data Type Purpose
sentence String The sentence entered by the user.
reversedSentence String The sentence with the order of its words reversed.
words String[] Array that stores individual words from the sentence.
reversed StringBuilder Used to build the reversed sentence.
Loop control variable for iterating through the words
i int
in reverse order.

Method Description Table

Method Name Purpose


reverseWords(String sentence) Reverses the order of words in the given sentence.

PROGRAM NO:9

PROBLEM DEFINATION:Write a program to enter a String/Sentence and display


the longest word.
Sample Input: TATA FOOTBALL ACADEMY WILL PLAY
Sample Output: FOOTBALL
ALGORITHM:

· Start
· Accept a sentence from the user and store it in the variable sentence.
· Call the method findLongestWord(sentence) to find the longest word in the
sentence:
a. Split the sentence into words using spaces as a delimiter and store them in the
array words.
b. Initialize an empty string longest to store the longest word found.
c. Iterate through each word in the words array:

 If the length of the current word is greater than the length of longest, update
longest with the current word.
d. Return the longest word.

· Display the longest word.


· End

PROGRAM CODE:

import java.util.Scanner;

public class LongestWordProgram {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Accept a sentence from the user


System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();

// Find the longest word in the sentence


String longestWord = findLongestWord(sentence);

// Display the longest word


System.out.println("Longest word: " + longestWord);
sc.close();
}

// Method to find the longest word in the sentence


public static String findLongestWord(String sentence) {
// Split the sentence into words based on spaces
String[] words = sentence.split(" ");
String longest = "";

// Iterate through each word and find the longest one


for (String word : words) {
if (word.length() > longest.length()) {
longest = word; // Update the longest word
}
}
return longest;
}
}
INPUT AND OUTPUT:

Variable Description Table


Variable Name Data Type Purpose
sentence String The sentence entered by the user.
longestWord String The longest word found in the sentence.
words String[] Array that stores individual words from the sentence.
longest String Holds the longest word found during the iteration process.
word String The current word being checked in the iteration.

Method Description Table

Method Name Purpose


findLongestWord(String Finds and returns the longest word in the given
sentence) sentence.

PROGRAM NO: 10

PROBLEM DEFINATION: Write a program in java to accept a string/sentence and


find the frequency of given
alphabets.
Sample
Input: WE ARE LIVING IN COMPUTER WORLD
Enter an alphabet whose frequency is to be checked: E
Sample
Output: The frequency of 'E' is 3

ALGORITHM:
· Start
· Accept a sentence from the user and store it in the variable sentence.
· Accept an alphabet from the user whose frequency is to be checked and store it in
the variable alphabet.
· Call the method findFrequency(sentence, alphabet) to find the frequency of the
given alphabet in the sentence:
a. Convert the alphabet to lowercase for case-insensitive comparison.
b. Convert the sentence to lowercase for case-insensitive comparison.
c. Initialize a counter count to 0.
d. Iterate through each character in the sentence:

 If the character matches the given alphabet, increment the count.


e. Return the count as the frequency of the alphabet.

· Display the frequency of the given alphabet.


· End

PROGRAM CODE:
import java.util.Scanner;

public class AlphabetFrequencyProgram {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Accept a sentence from the user


System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();

// Accept an alphabet whose frequency is to be checked


System.out.print("Enter an alphabet whose frequency is to be checked: ");
char alphabet = sc.next().charAt(0);

// Find the frequency of the given alphabet in the sentence


int frequency = findFrequency(sentence, alphabet);

// Display the frequency


System.out.println("The frequency of '" + alphabet + "' is " + frequency + ".");
sc.close();
}

// Method to find the frequency of the given alphabet in the sentence


public static int findFrequency(String sentence, char alphabet) {
int count = 0;
alphabet = Character.toLowerCase(alphabet); // Convert alphabet to lowercase
for case-insensitive comparison

// Convert sentence to lowercase for case-insensitive comparison


sentence = sentence.toLowerCase();

// Iterate through each character in the sentence


for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == alphabet) {
count++; // Increment the count if the character matches the given alphabet
}
}
return count;
}
}

INPUT AND OUTPUT:

Variable Description Table


Variable Data
Purpose
Name Type
sentence String The sentence entered by the user.
The alphabet whose frequency is to be checked, entered by
alphabet char
the user.
frequency int The frequency of the given alphabet in the sentence.
Counter to keep track of the frequency of the alphabet in the
count int
sentence.
Loop control variable for iterating through the characters of
i int
the sentence.

Method Description Table

Method Name Purpose


findFrequency(String sentence, char Finds and returns the frequency of the given
alphabet) alphabet in the sentence.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy