[Go to site: main page, start]

0% found this document useful (0 votes)
49 views3 pages

Java Programs for Common Algorithms

The document contains eight Java programs that perform various tasks: expressing a number as a sum of consecutive numbers, adding two binary numbers, checking for Armstrong numbers in a range, testing if a word is a palindrome, finding prime factors of a number, generating Fibonacci numbers, sorting an array using bubble sort while counting swaps, and counting vowels, consonants, digits, and spaces in a sentence. Each program includes a main method that takes user input and processes it accordingly. The solutions demonstrate fundamental programming concepts such as loops, conditionals, and data structures.

Uploaded by

sksinghgameing
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)
49 views3 pages

Java Programs for Common Algorithms

The document contains eight Java programs that perform various tasks: expressing a number as a sum of consecutive numbers, adding two binary numbers, checking for Armstrong numbers in a range, testing if a word is a palindrome, finding prime factors of a number, generating Fibonacci numbers, sorting an array using bubble sort while counting swaps, and counting vowels, consonants, digits, and spaces in a sentence. Each program includes a main method that takes user input and processes it accordingly. The solutions demonstrate fundamental programming concepts such as loops, conditionals, and data structures.

Uploaded by

sksinghgameing
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

Q1) Express a number as sum of consecutive numbers

import [Link].*;
class ConsecutiveSum {
static void printRange(int last, int first){
[Link](first);
for (int x = first + 1; x <= last; x++) [Link](" + " + x);
[Link]();
}
static int process(int n){
int printed = 0;
for (int len = 2; len < n; len++){
for (int first = 1; first < len; first++){
if (2*n == len*(len+2*first-1)){
[Link](n + " = ");
printRange(first+len-1, first);
printed++;
}
}
}
return printed==0 ? -1 : printed;
}
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int n = [Link]();
if (process(n)==-1) [Link](-1);
}
}

Q2) Add two binary numbers (as strings)


import [Link].*;
class BinaryAdd {
static String add(String a, String b){
StringBuilder sb = new StringBuilder();
int i=[Link]()-1, j=[Link]()-1, carry=0;
while(i>=0 || j>=0 || carry>0){
int d = carry;
if (i>=0) d += [Link](i--)-'0';
if (j>=0) d += [Link](j--)-'0';
[Link](d%2);
carry = d/2;
}
return [Link]().toString();
}
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
String a=[Link](), b=[Link]();
[Link]("Sum: " + add(a,b));
}
}

Q3) Check if a number is Armstrong (3-digit) and list all in a range


import [Link].*;
class ArmstrongRange {
static boolean isArm(int n){
int s=0, t=n;
while(t>0){ int d=t%10; s+=d*d*d; t/=10; }
return s==n;
}
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int L=[Link](), R=[Link]();
boolean found=false;
for(int x=L; x<=R; x++){
if(x>=100 && x<=999 && isArm(x)){
[Link](x + " ");
found=true;
}
}
if(!found) [Link](-1);
else [Link]();
}
}

Q4) Palindrome test for a word (ignore case)


import [Link].*;
class PalWord {
static boolean isPal(String s){
s=[Link]();
int i=0,j=[Link]()-1;
while(i<j) if([Link](i++)!=[Link](j--)) return false;
return true;
}
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
String s=[Link]();
[Link](isPal(s) ? "PALINDROME" : "NOT PALINDROME");
}
}

Q5) Prime factors of a number (ascending)


import [Link].*;
class PrimeFactors {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link]();
if(n<=1){ [Link](-1); return; }
for(int p=2; p*p<=n; p++){
while(n%p==0){ [Link](p + " "); n/=p; }
}
if(n>1) [Link](n);
[Link]();
}
}

Q6) Generate first N Fibonacci numbers


import [Link].*;
class FibonacciN {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link]();
if(n<=0){ [Link](-1); return; }
long a=0,b=1;
for(int i=1;i<=n;i++){
[Link](a + (i==n?"":" "));
long c=a+b; a=b; b=c;
}
[Link]();
}
}

Q7) Sort an array using Bubble Sort and print swaps count
import [Link].*;
class BubbleSortCount {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link]();
if(n<=0){ [Link](-1); return; }
int[] a=new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
int swaps=0;
for(int i=0;i<n-1;i++){
for(int j=0;j<n-1-i;j++){
if(a[j]>a[j+1]){
int t=a[j]; a[j]=a[j+1]; a[j+1]=t; swaps++;
}
}
}
for(int x:a) [Link](x+" ");
[Link]("\nSwaps: "+swaps);
}
}

Q8) Count vowels, consonants, digits, and spaces in a sentence


import [Link].*;
class CharTally {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
String s=[Link]();
int v=0,c=0,d=0,sp=0,oth=0;
for(char ch: [Link]()){
if("aeiouAEIOU".indexOf(ch)>=0) v++;
else if([Link](ch)) c++;
else if([Link](ch)) d++;
else if([Link](ch)) sp++;
else oth++;
}
[Link]("Vowels: "+v);
[Link]("Consonants: "+c);
[Link]("Digits: "+d);
[Link]("Spaces: "+sp);
[Link]("Others: "+oth);
}
}

Common questions

Powered by AI

The program computes prime factors of a given number by using a loop to test consecutive integers starting from 2. For each integer, it checks if it divides the number evenly; if so, it prints and continues dividing the number by the prime until it's no longer divisible. After the loop, if the remaining number is greater than 1, it's also a prime factor and is printed. This method ensures prime factors are printed in ascending order and prevents unnecessary computations beyond the square root of the number, thus optimizing the factorization process .

The Java program identifies 3-digit Armstrong numbers in a range by using a loop to iterate over each number within the specified range. For each number, it calculates the sum of the cubes of its digits by extracting each digit using modulus arithmetic and division. If the sum equals the original number, it is printed as an Armstrong number. This verification process relies on the property that an Armstrong number for 3 digits is equal to the sum of the cubes of its digits .

The Java program identifies and counts different character types in a sentence by iterating through each character and checking its type based on specific conditions. It uses predefined checks for vowels, consonants, digits, and spaces using character comparison and built-in Java methods like `Character.isLetter`, `Character.isDigit`, and `Character.isWhitespace`. A separate counter is maintained for vowels, consonants, digits, spaces, and any other character types, which are then printed at the end of the iteration .

The Java code limits the input number for generating prime factors by returning -1 for any number less than or equal to 1. This limitation prevents attempting to factorize numbers that do not have meaningful prime factors, such as zero and negative numbers. This validation ensures that only valid inputs are processed, maintaining the integrity of the prime factorization process and avoiding unnecessary computations .

The output format of the Fibonacci number generation program presents the Fibonacci sequence as a space-separated string of numbers up to the Nth Fibonacci number. The program checks for input errors by testing if the input number N is less than or equal to zero, in which case it outputs -1, indicating an invalid input. This error handling prevents generating an incorrectly defined Fibonacci sequence and ensures the logic runs only for valid, positive integer inputs .

The Java code sorts an array using the Bubble Sort technique, which repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated for each element in the array, with each pass through the array ensuring that at least one element is placed in its correct position. The number of swaps is calculated by incrementing a swap counter each time two elements are swapped. This count is printed at the end to denote the number of swaps performed during the sort .

The program generates the first N Fibonacci numbers using an iterative approach. It initializes the first two Fibonacci numbers as 0 and 1, then iteratively calculates the next Fibonacci number by summing the last two numbers in the sequence. This is done using a loop that continues until N numbers are generated. The constraint enforced is that N must be positive, otherwise it returns -1. This ensures incorrect inputs do not lead to errors in execution .

The Java program adds two binary strings by iterating from the end of both strings towards the start while maintaining a carry. At each step, it adds corresponding digits from both strings (or zero if out of bounds) and the carry, appending the result's least significant bit to a StringBuilder. It updates the carry to hold the most significant bit of the sum by integer division by two. After processing all digits, any remaining carry is appended, and the result is reversed to form the final binary sum .

The Java code checks if a word is a palindrome by converting the string to lowercase to ensure case insensitivity and then using a two-pointer technique: one starts from the beginning and the other from the end of the string. The characters at these pointers are compared, and the pointers move towards the center. If any character mismatch is found, the word is not a palindrome. If the pointers cross without mismatches, the word is a palindrome .

The Java program determines if a number can be expressed as a sum of consecutive numbers by iteratively checking combinations of potential consecutive numbers. It uses two nested loops; the outer loop varies the length of the sequence, while the inner loop varies the starting number of the sequence. The equation checked is if \(2n = \text{len} \times (\text{len} + 2 \times \text{first} - 1)\) holds true, where \(n\) is the input number, \(\text{len}\) is the length of the sequence, and \(\text{first}\) is the starting number. If true, it prints the sequence. The complexity comes from checking all possible starting points and sequence lengths .

You might also like