U Basic Java Programs
U Basic Java Programs
By :- Utkarsh Shelke
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’s implement the basic calculator operations with the help of the below program.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
// nextDouble() reads the next double from the keyboard
double first = reader.nextDouble();
double second = reader.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = reader.next().charAt(0);
double result;
//switch case for each of the operations
switch(operator)
{
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
// operator doesn't match any case constant (+, -, *, /)
default:
System.out.printf("Error! operator is not correct");
return;
}
//printing the result of the operations
System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
}
}
When you execute the above program, the output looks like as shown below:
Enter two numbers: 20 98
Enter an operator (+, -, *, /): /
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’s write a program and find factorial of a number using recursion.
import java.util.Scanner;
public class Factorial {
public static void main(String args[]){
//Scanner object for capturing the user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
//Stored the entered value in variable
int num = scanner.nextInt();
//Called the user defined function fact
int factorial = fact(num);
System.out.println("Factorial of entered number is: "+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}
On executing the above program, you will get factorial of a number as shown below:
Enter the number:
12
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’s write a Java program to calculate the Fibonacci series.
public class Fibonacci
{
public static void main(String[] args) {
//initializing the constants
int n = 100, t1 = 0, t2 = 1;
System.out.print("Upto " + n + ": ");
//while loop to calculate fibonacci series upto n numbers
while (t1<= n)
{
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
On executing the above code, the output looks like :
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.
import java.util.Scanner;
public class Palindrome {
static void checkPalindrome(String input) {
//Assuming result to be true
boolean res = true;
int length = input.length();
//dividing the length of the string by 2 and comparing it.
for(int i=0; i<= length/2; i++) {
if(input.charAt(i) != input.charAt(length-i-1)) {
res = false;
break;
}
}
System.out.println(input + " is palindrome = "+res);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your Statement: ");
String str = sc.nextLine();
//function call
checkPalindrome(str);
}
}
When you run the code, it will check whether the given string is a palindrome or not as shown below:
Enter your Statement: RACECAR
RACECAR is palindrome = true
Enter your Statement: EDUREKA
EDUREKA is palindrome = false
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’s have a look at its implementation.
import java.util.Scanner;
public class nprandncr {
//calculating a factorial of a number
public static int fact(int num)
{
int fact=1, i;
for(i=1; i<=num; i++)
{
fact = fact*i;
}
return fact;
}
public static void main(String args[])
{
int n, r;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Value of n : ");
n = scan.nextInt();
System.out.print("Enter Value of r : ");
r = scan.nextInt();
// NCR and NPR of a number
System.out.print("NCR = " +(fact(n)/(fact(n-r)*fact(r))));
System.out.print("nNPR = " +(fact(n)/(fact(n-r))));
}
}
On executing the above code, the output looks like as shown below:
Enter Value of n : 5
Enter Value of r : 3
NCR = 10
NPR = 60
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’s now see the implementation of the alphabet A pattern.
import java.util.Scanner;
public class PatternA {
// Java program to print alphabet A pattern
void display(int n)
{
// Outer for loop for number of lines
for (int i = 0; i<=n; i++) {
// Inner for loop for logic execution
for (int j = 0; j<= n / 2; j++) {
// prints two column lines
if ((j == 0 || j == n / 2) && i != 0 ||
// print first line of alphabet
i == 0 && j != n / 2 ||
// prints middle line
i == n / 2)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
PatternA a = new PatternA();
a.display(7);
}
}
Output:
Pattern A Output - Java Programs - Edureka
Diamond Pattern Program in Java
import java.util.Scanner;
public class DiamondPattern
{
public static void main(String args[])
{
int n, i, j, space = 1;
System.out.print("Enter the number of rows: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
space = n - 1;
for (j = 1; j<= n; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(" ");
}
space--;
for (i = 1; i <= 2 * j - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
space = 1;
for (j = 1; j<= n - 1; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(" ");
}
space++;
for (i = 1; i<= 2 * (n - j) - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
}
}
Enter the number of rows: 5
*
***
*****
*******
*********
*******
*****
***
*
This will be the output of Diamond-Shaped Pattern program. Now let’s 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’s implement the same using Java.
public class stringreverse
{
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "Welcome To U Softwares";
String[] strArray = str.split(" ");
for (String temp: strArray){
System.out.println(temp);
}
for(int i=0; i<3; i++){ char[] s1 = strArray[i].toCharArray(); for (int j = s1.length-1; j>=0; j--)
{System.out.print(s1[j]);}
System.out.print(" ");
}
}
}
The output of the above program will be as shown below:
Welcome
To
U Softwares
emocleW oT serawtfoS U
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
public class MirrorInverse
{
// Function that returns true if
// the array is mirror-inverse
static boolean isMirrorInverse(int arr[])
{
for (int i = 0; i<arr.length; i++) {
// If condition fails for any element
if (arr[arr[i]] != i)
return false;
}
// Given array is mirror-inverse
return true;
}
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 0 };
if (isMirrorInverse(arr))
System.out.println("Yes");
else
System.out.println("No");
}
}
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.

Comments
Post a Comment