Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

THE BASIC JAVA PROGRAMS

The document provides a series of basic Java programs that demonstrate fundamental programming concepts, including a calculator, factorial calculation, Fibonacci series, palindrome checking, permutations and combinations, pattern printing, string reversal, and mirror-inverse array checking. Each program includes code snippets and example outputs to illustrate their functionality. The programs serve as practical examples for beginners to learn Java programming.

Uploaded by

cyrus3620
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

THE BASIC JAVA PROGRAMS

The document provides a series of basic Java programs that demonstrate fundamental programming concepts, including a calculator, factorial calculation, Fibonacci series, palindrome checking, permutations and combinations, pattern printing, string reversal, and mirror-inverse array checking. Each program includes code snippets and example outputs to illustrate their functionality. The programs serve as practical examples for beginners to learn Java programming.

Uploaded by

cyrus3620
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

THE BASIC JAVA PROGRAMS

1. Write a Java program to perform basic Calculator


operations.

When you think about a calculator, operations like addition, subtraction,


multiplication, and division comes into the mind. Let us implement the basic
calculator operations with the help of the below program.

import java.util.Scanner;
1
public class Calculator {
2
public static void main(String[] args) {
3 Scanner reader = new Scanner(System.in);
4 System.out.print("Enter two numbers: ");

5 // nextDouble() reads the next double from the keyboard


double first = reader.nextDouble();
6
double second = reader.nextDouble();
7
System.out.print("Enter an operator (+, -, *, /): ");
8 char operator = reader.next().charAt(0);
9 double result;

10 //switch case for each of the operations


switch(operator)
11
{
12
case '+':
13 result = first + second;
14 break;

15 case '-':
result = first - second;
16
break;
17
case '*':
18 result = first * second;
19 break;

20 case '/':
result = first / second;
21
break;
22
// operator doesn't match any case constant (+, -, *, /)
23
24
25 default:
System.out.printf("Error! operator is not correct");
26
return;
27
}
28 //printing the result of the operations
29 System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
30 }
}
31
32
33
34
35
36
37
38
When you execute the above program, the output looks like as shown below:

1 Enter two numbers: 20 98


2 Enter an operator (+, -, *, /): /

3 20.0 / 98.0 = 0.2

2. Write a Java program to calculate a Factorial of a


number.

Factorial of a number is the product of all the positive numbers less than or equal
to the number. The factorial of a number n is denoted by n!

Now, let us write a program and find factorial of a number using recursion.

1 import java.util.Scanner;
public class Factorial {
2
public static void main(String args[]){
3
//Scanner object for capturing the user input
4 Scanner scanner = new Scanner(System.in);
5 System.out.println("Enter the number:");
6 //Stored the entered value in variable
int num = scanner.nextInt();
7
//Called the user defined function fact
8
int factorial = fact(num);
9 System.out.println("Factorial of entered number is: "+factorial);
10 }
11 static int fact(int n)
{
12
int output;
13
if(n==1){
14 return 1;
15 }
16 //Recursion: Function calling itself!!
output = fact(n-1)* n;
17
return output;
18
}
19 }
20
21
22
23
24
On executing the above program, you will get factorial of a number as shown
below:

1 Enter the number:


2 12

3 Factorial of entered number is: 47900160

3. Write a Java program to calculate Fibonacci Series up


to n numbers.

It is a series in which the next term is the sum of the preceding two terms. For
Example: 0 1 1 2 3 5 8 13……. Let us write a Java program to calculate the
Fibonacci series.

1 public class Fibonacci {


2 public static void main(String[] args) {
//initializing the constants
3
int n = 100, t1 = 0, t2 = 1;
4
System.out.print("Upto " + n + ": ");
5 //while loop to calculate fibonacci series upto n numbers
6 while (t1<= n)
7 {
System.out.print(t1 + " + ");
8
int sum = t1 + t2;
9
t1 = t2;
10 t2 = sum;
11 }
12 }
}
13
14
15
16
On executing the above code, the output looks like :

1 Upto 100: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 +

4. Write a Java program to find out whether the given


String is Palindrome or not.

A palindrome is a number, string or a sequence which will be the same even after
you reverse the order. For example, RACECAR, if spelled backward will be same
as RACECAR.

1 import java.util.Scanner;
2 public class Palindrome {

3 static void checkPalindrome(String input) {


//Assuming result to be true
4
boolean res = true;
5
int length = input.length();
6 //dividing the length of the string by 2 and comparing it.
7 for(int i=0; i<= length/2; i++) {

8 if(input.charAt(i) != input.charAt(length-i-1)) {
9 res = false;
break;
10
}
11
}
12 System.out.println(input + " is palindrome = "+res);
13 }
14 public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
15
System.out.print("Enter your Statement: ");
16
String str = sc.nextLine();
17 //function call
18 checkPalindrome(str);
19 }
}
20
21
22
23
24
When you run the code, it will check whether the given string is a palindrome or not
as shown below:

1 Enter your Statement: RACECAR


2 RACECAR is palindrome = true
3
4 Enter your Statement: EDUREKA
EDUREKA is palindrome = false
5

5. Write a Java program to calculate Permutation and


Combination of 2 numbers.

It is the different arrangements of a given number of elements taken one by one, or


some, or all at a time. Let us have a look at its implementation.

1 import java.util.Scanner;
2 public class nprandncr {

3 //calculating a factorial of a number


4 public static int fact(int num)
{
5
int fact=1, i;
6
for(i=1; i<=num; i++)
7 {
8 fact = fact*i;
9 }
return fact;
10
}
11
public static void main(String args[])
12 {
13 int n, r;
14 Scanner scan = new Scanner(System.in);
System.out.print("Enter Value of n : ");
15
n = scan.nextInt();
16
System.out.print("Enter Value of r : ");
17 r = scan.nextInt();
18 // NCR and NPR of a number
19 System.out.print("NCR = " +(fact(n)/(fact(n-r)*fact(r))));
System.out.print("nNPR = " +(fact(n)/(fact(n-r))));
20
}
21
}
22
23
24
25
26
On executing the above code, the output looks like as shown below:

1 Enter Value of n : 5
2 Enter Value of r : 3
3 NCR = 10
NPR = 60
4

6. Write a program in Java to find out Alphabet and


Diamond Pattern.
Here, you can use the for loop to print various patterns in Java. I will be
implementing two different patterns in this article. First one will be Alphabet A
pattern and the next one will be Diamond shaped pattern. Let us now see the
implementation of the alphabet A pattern.

1
2
import java.util.Scanner;
3
public class PatternA {
4
// Java program to print alphabet A pattern
5 void display(int n)
6 {
7 // Outer for loop for number of lines
for (int i = 0; i<=n; i++) {
8
// Inner for loop for logic execution
9
for (int j = 0; j<= n / 2; j++) {
10 // prints two column lines
11 if ((j == 0 || j == n / 2) && i != 0 ||
12 // print first line of alphabet

13 i == 0 && j != n / 2 ||
// prints middle line
14
i == n / 2)
15
System.out.print("*");
16 else
17 System.out.print(" ");
18 }
System.out.println();
19
}
20
}
21 public static void main(String[] args)
22 {
23 Scanner sc = new Scanner(System.in);
PatternA a = new PatternA();
24
a.display(7);
25
}
26 }
27
28
29
30
Output:

Diamond Pattern Program in Java


1 import java.util.Scanner;
2 public class DiamondPattern

3 {
public static void main(String args[])
4
{
5
int n, i, j, space = 1;
6 System.out.print("Enter the number of rows: ");
7 Scanner s = new Scanner(System.in);

8 n = s.nextInt();
space = n - 1;
9
for (j = 1; j<= n; j++)
10
{
11 for (i = 1; i<= space; i++)
12 {

13 System.out.print(" ");
}
14
space--;
15
for (i = 1; i <= 2 * j - 1; i++)
16 {
17 System.out.print("*");

18 }
System.out.println("");
19
}
20
space = 1;
21 for (j = 1; j<= n - 1; j++)
22 {

23 for (i = 1; i<= space; i++)


24 {
System.out.print(" ");
25
}
26
space++;
27 for (i = 1; i<= 2 * (n - j) - 1; i++)
28 {
29 System.out.print("*");
}
30
System.out.println("");
31
}
32 }
33 }
34
35
36
37
38
39
40
1
Enter the number of rows: 5
2
3
*
4
***
5 *****
6 *******
7 *********
*******
8
*****
9
***
10 *
11
This will be the output of Diamond-Shaped Pattern program. Now let us move
further and see what’s next.

7. Write a Java Program to reverse the letters present in


the given String.
This Java program reverses letters present in the string entered by a user. For
example, Hello People will be termed as olleH elpoeP. Let us implement the same
using Java.

1
2
public class stringreverse {
3
public static void main(String[] args) {
4 // TODO Auto-generated method stub
5 String str = "Welcome To Edureka";
6 String[] strArray = str.split(" ");
for (String temp: strArray){
7
System.out.println(temp);
8
}
9 for(int i=0; i<3; i++){ char[] s1 = strArray[i].toCharArray(); for (int j = s1.length-1; j>=0; j--)
10 {System.out.print(s1[j]);}
11 System.out.print(" ");
}
12
}
13
}
14
15
The output of the above program will be as shown below:

1 Welcome
2 To
3 Edureka
emocleW oT akerudE
4

8. Write a Java Program to check whether the given array


is Mirror Inverse or not.

An array is called mirror–inverse if its inverse is equal to itself. Let’s now write
a program and check whether the given array is mirror inverse or not.
//Java implementation of the approach
1
public class MirrorInverse {
2
// Function that returns true if
3 // the array is mirror-inverse
static boolean isMirrorInverse(int arr[])
4
{
5
for (int i = 0; i<arr.length; i++) {
6 // If condition fails for any element
7 if (arr[arr[i]] != i)
8 return false;
}
9
// Given array is mirror-inverse
10
return true;
11 }
12
13 public static void main(String[] args)
14 {
int arr[] = { 1, 2, 3, 0 };
15
if (isMirrorInverse(arr))
16
System.out.println("Yes");
17 else
18 System.out.println("No");
19 }
}
20
21
22
23
24
25
Output: No

// If the given array was {3,4,2,0,1} then it would have printed yes as the output
because the array is mirror inverse.

You might also like