[Go to site: main page, start]

0% found this document useful (0 votes)
7 views7 pages

Java Programs for Basic Algorithms

The document contains multiple Java programs demonstrating various programming concepts such as listing even numbers, calculating factorials, comparing numbers, determining leap years, generating Fibonacci series, checking for palindromes, generating prime numbers, and creating star pyramids. Each program includes a brief description, code implementation, and expected output. The examples serve as practical illustrations for beginners learning Java programming.

Uploaded by

rincejohn80
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)
7 views7 pages

Java Programs for Basic Algorithms

The document contains multiple Java programs demonstrating various programming concepts such as listing even numbers, calculating factorials, comparing numbers, determining leap years, generating Fibonacci series, checking for palindromes, generating prime numbers, and creating star pyramids. Each program includes a brief description, code implementation, and expected output. The examples serve as practical illustrations for beginners learning Java programming.

Uploaded by

rincejohn80
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

Program1 – List of even numbers

/*
List Even Numbers Java Example
This List Even Numbers Java Example shows how to find and list even
numbers between 1 and any given number.
*/

public class ListEvenNumbers {

public static void main(String[] args) {

//define limit
int limit = 50;

[Link]("Printing Even numbers between 1 and " +


limit);

for(int i=1; i <= limit; i++){

// if the number is divisible by 2 then it is even


if( i % 2 == 0){
[Link](i + " ");
}
}
}
}

/*
Output of List Even Numbers Java Example would be
Printing Even numbers between 1 and 50
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
*/

Program2 - Factorial of a number


/*
This program shows how to calculate
Factorial of a number.
*/

public class NumberFactorial {

public static void main(String[] args) {

int number = 5;

/*
* Factorial of any number is! n.
* For example, factorial of 4 is 4*3*2*1.
*/

int factorial = number;

for(int i =(number - 1); i > 1; i--)

4
{
factorial = factorial * i;
}

[Link]("Factorial of a number is " + factorial);


}
}

/*
Output of the Factorial program would be
Factorial of a number is 120
*/

Program3 - Compare Two Numbers using else-if


/*

Compare Two Numbers Java Example

This Compare Two Numbers Java Example shows how to compare two numbers

using if else if statements.

*/

public class CompareTwoNumbers {

public static void main(String[] args) {

//declare two numbers to compare

int num1 = 324;

int num2 = 234;

if(num1 > num2){

[Link](num1 + " is greater than " + num2);

else if(num1 < num2){

5
[Link](num1 + " is less than " + num2);

else{

[Link](num1 + " is equal to " + num2);

/*

Output of Compare Two Numbers Java Example would be

324 is greater than 234

*/

Program4 - Determine If Year Is Leap Year


/*

Determine If Year Is Leap Year Java Example

This Determine If Year Is Leap Year Java Example shows how to

determine whether the given year is leap year or not.

*/

public class DetermineLeapYearExample {

public static void main(String[] args) {

6
//year we want to check

int year = 2004;

//if year is divisible by 4, it is a leap year

if(year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))

[Link]("Year " + year + " is a leap year");

else

[Link]("Year " + year + " is not a leap year");

/*

Output of the example would be

Year 2004 is a leap year

*/

Program5 - Fibonacci Series


/* Fibonacci Series Java Example
This Fibonacci Series Java Example shows how to create and print
Fibonacci Series using Java.
*/

public class JavaFibonacciSeriesExample {

public static void main(String[] args) {

//number of elements to generate in a series


int limit = 20;

long[] series = new long[limit];

//create first 2 series elements

7
series[0] = 0;
series[1] = 1;

//create the Fibonacci series and store it in an array


for(int i=2; i < limit; i++){
series[i] = series[i-1] + series[i-2];
}

//print the Fibonacci series numbers

[Link]("Fibonacci Series upto " + limit);


for(int i=0; i< limit; i++){
[Link](series[i] + " ");
}
}
}

/*
Output of the Fibonacci Series Java Example would be
Fibonacci Series upto 20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
*/

Program6 - Palindrome Number


/*
This program shows how to check for in the given list of numbers
whether each number is palindrome or not
*/

public class JavaPalindromeNumberExample {

public static void main(String[] args) {

//array of numbers to be checked


int numbers[] = new int[]{121,13,34,11,22,54};

//iterate through the numbers


for(int i=0; i < [Link]; i++){

int number = numbers[i];


int reversedNumber = 0;
int temp=0;

/*
* If the number is equal to it's reversed number, then
* the given number is a palindrome number.
*
* For ex,121 is a palindrome number while 12 is not.
*/
//reverse the number

while(number > 0){


temp = number % 10;
number = number / 10;
reversedNumber = reversedNumber * 10 + temp;

8
}

if(numbers[i] == reversedNumber)
[Link](numbers[i] + " is a palindrome");
else
[Link](numbers[i] + " not a palindrome ");
}

}
}

/*
Output of Java Palindrome Number Example would be
121 is a palindrome number
13 is not a palindrome number
34 is not a palindrome number
11 is a palindrome number
22 is a palindrome number
54 is not a palindrome number
*/

Program7- Generate prime numbers between 1 & given


number
/*
Prime Numbers Java Example
This Prime Numbers Java example shows how to generate prime numbers
between 1 and given number using for loop.
*/

public class GeneratePrimeNumbersExample {

public static void main(String[] args) {

//define limit
int limit = 100;

[Link]("Prime numbers between 1 and " + limit);

//loop through the numbers one by one


for(int i=1; i < 100; i++){

boolean isPrime = true;

//check to see if the number is prime


for(int j=2; j < i ; j++){

if(i % j == 0){
isPrime = false;
break;
}
}
// print the number
if(isPrime)
[Link](i + " ");
}

9
}
}

/*
Output of Prime Numbers example would be
Prime numbers between 1 and 100
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
*/

Program8- Pyramid of stars using nested for loops


/*

Java Pyramid 1 Example


This Java Pyramid example shows how to generate pyramid or triangle
like given below using for loop.

*
**
***
****
*****
*/

public class JavaPyramid1 {

public static void main(String[] args) {

for(int i=1; i<= 5 ;i++){

for(int j=0; j < i; j++){


[Link]("*");
}
//generate a new line
[Link]("");
}
}
}

/*
Output of the above program would be
*
**
***
****
*****
*/
Program9 – Reversed pyramid using for loops &
decrement operator.
/*

10

Common questions

Powered by AI

The Java program lists prime numbers between 1 and a given number by iterating through each number within the range and checking its divisibility. For each number `i`, an inner loop checks divisibility by all preceding numbers starting from 2. If `i` is divisible by any number other than 1 and itself, it is flagged as non-prime. Otherwise, it is printed as a prime number. The complexity is managed by breaking the loop as soon as a divisor is found, thus reducing unnecessary checks .

The program that determines a leap year differs from simple division tests by employing a compound conditional logic that accounts for leap year exceptions. Unlike a basic division test which might only check for divisibility by 4, this program evaluates both divisibility by 400 (indicating a leap year outright) and the combined condition of divisibility by 4 but not by 100. This distinction is crucial as it handles century years systematically, matching the Gregorian calendar rules .

The factorial computation Java program initializes the factorial variable with the target number. It then uses a for-loop starting from one less than the number down to 2, multiplying the current factorial value by the iterator at each step. This iterative multiplication continues until the loop completes, resulting in the factorial of the original number. The concept is based on successive multiplication of all positive integers up to the number itself .

The Java program checks each number in the list to see if it is a palindrome by reversing the number and comparing it to the original number. The reversal process involves dividing the number to extract each digit, which is then appended to a new number variable (`reversedNumber`) using multiplication and addition. This is repeated in a loop until all digits are reversed. If the reversed number equals the original number, it indicates the number is a palindrome .

The Java program generates a Fibonacci series by using an array to store the series elements. Initially, the first two Fibonacci numbers, 0 and 1, are assigned to the first two elements of the array. The program then uses a loop starting from the third position, calculating each Fibonacci number as the sum of the two preceding numbers, i.e., series[i] = series[i-1] + series[i-2]. This continues until the specified limit is reached, populating the array with Fibonacci numbers .

Structured loops contribute to efficient program execution in generating prime numbers by reducing unnecessary computations. The outer loop iterates over potential prime candidates, while the inner loop is used to check divisibility, reducing iterations as soon as a divisor is found by breaking out of the loop. This logic minimizes the number of divisions performed, especially as numbers increase, hence decreasing time complexity. By primarily checking factors up to the square root instead of the number itself in advanced implementations, efficiency could be increased further .

The Java program prints star pyramids by using nested loops. The outer loop controls the number of lines, iterating from 1 up to 5, suggesting the height of the pyramid. For each iteration of the outer loop, an inner loop runs to print the corresponding number of stars in that line, equal to the outer loop's current count. After printing the stars in each inner loop iteration, a newline character is printed to progress to the next line, thus creating a pyramid shape of increasing stars .

The Java program handles edge cases when comparing two numbers by utilizing if-else statements that account for all possible scenarios: whether one number is greater than, less than, or equal to the other. The logic sequentially checks if the first number is greater than the second; if true, it prints the appropriate message. If not, it checks if the first number is less than the second. If neither condition is met, it concludes the numbers are equal, handling all edges of comparison .

The Java program uses conditional statements to determine if a year is a leap year. A year is considered a leap year if it is divisible by 400, or it is divisible by 4 but not divisible by 100. The program checks these conditions using the following logical statement: if (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)). If either condition is true, the year is a leap year .

The rules for the even numbers listing program are simple: iterate a loop from 1 up to a specific limit (e.g., 50), and use the modulo operation `i % 2 == 0` to determine if a number is even. An even number will result in zero when divided by 2. The program prints numbers only when this condition is satisfied, ensuring only even values are outputted between the range .

You might also like