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

Write A Program To Calculate Factorial of A Number

The document contains 3 code snippets that solve different problems: 1) A recursive function to calculate the factorial of a number. 2) A program that accepts an integer input and prints the multiplication table of that integer up to 12. 3) A program that reads a number from the user and prints out the Hailstone sequence for that number until it reaches 1.

Uploaded by

R0ck D3m0n
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views3 pages

Write A Program To Calculate Factorial of A Number

The document contains 3 code snippets that solve different problems: 1) A recursive function to calculate the factorial of a number. 2) A program that accepts an integer input and prints the multiplication table of that integer up to 12. 3) A program that reads a number from the user and prints out the Hailstone sequence for that number until it reaches 1.

Uploaded by

R0ck D3m0n
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

1. Write a program to calculate factorial of a number.

Solution:-

public class FActorial {

static int fact(int n) {

if(n==0||n==1)

return 1;

else

return (n*fact(n-1));

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int res = fact(n);

System.out.println(res);

2. Write a program that accepts an integer as input and prints the table of
that integer up to 12.
Solution:-

import java.util.*;

public class Table {

public static void main(String[] args)

{
Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int mul=0;

for(int i=1;i<=12;i++)

mul = n*i;

System.out.println(n+"x"+i+"="+mul);

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.

Solution:-

import java.util.*;

public class Hailstone {

public static void main(String[] args)

Scanner sc =new Scanner(System.in);


int n = sc.nextInt();

int count=0, s1=0,s2=0;

while(n!=1)

if(n%2==0)

System.out.println(n + " is even so I take half: " +


(n/2));

n=n/2;

else

System.out.println(n + " is odd so I make 3n+1: " +


(n*3+1));

n=(3*n)+1;

count++;

System.out.println("There are total "+count+" steps to reach 1");

You might also like