1.
Write a program to calculate factorial of a number
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number to calculate factorial");
int n=s.nextInt();
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("Factorial of a given number is "+fact);
}
}
Output:
Enter the number to calculate factorial
5
Factorial of a given number is 120
2.Write a program that accepts an integer as input and prints the table
of that integer up to 12. For example, is the user enters 7, the output
should be:
7x1=7
7 x 2 = 14
.....
7 x 12 = 84
import java.util.*;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter the numer");
int num =s.nextInt();
for(int i = 1; i <= 12; ++i)
{
System.out.printf("%d * %d = %d \n", num, i, num * i);
}
}
}
Output:
Enter the number
7
7*1=7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
7 * 11 = 77
7 * 12 = 84
3.Write a program that reads in a number from the user and then
displays the Hailstone sequence for that number. The problem can be
expressed as follows:
• Pick some positive integer and call it n.
• If n is even, divide it by two.
• If n is odd, multiply it by three and add one.
• Continue this process until n is equal to one.
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the number");
int n=s.nextInt();
int count=0;
while(n!=1)
{
if(n%2==0)
{
System.out.println(n+" is even so i take half: "+(n/2));
n=n/2;
}
else if(n%2!=0)
{
System.out.println(n+" is odd so i make 3n+1: "+(3*n+1));
n=3*n+1;
}
count++;
}
System.out.println("There are total "+count+" steps to reach 1");
}
}
Output
Enter the number
14
14 is even so i take half: 7
7 is odd so i make 3n+1: 22
22 is even so i take half: 11
11 is odd so i make 3n+1: 34
34 is even so i take half: 17
17 is odd so i make 3n+1: 52
52 is even so i take half: 26
26 is even so i take half: 13
13 is odd so i make 3n+1: 40
40 is even so i take half: 20
20 is even so i take half: 10
10 is even so i take half: 5
5 is odd so i make 3n+1: 16
16 is even so i take half: 8
8 is even so i take half: 4
4 is even so i take half: 2
2 is even so i take half: 1
There are total 17 steps to reach 1