Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Assignment 1

a.Write a number to calculate factorial of a number


import java.util.Scanner;
public class Assignment1a {

public static void main(String[] args) {

int n, c, f = 1;
//Show a message to a user to input a number
System.out.println("Enter an integer to calculate its
factorial");
Scanner in = new Scanner(System.in);

//Read an input to store it in a variable


n = in.nextInt();

//Check whether input value is greater than zero


if (n < 0)
System.out.println("Number should be non-negative.");
else
{
//If not greater than zero proceed with calculation factorial
for (c = 1; c <= n; c++)
f = f*c;

System.out.println("Factorial of "+n+" is = "+f);


}
}

Output :-
b.Write a number that accepts an integer as input and prints the table of that
integer up to 12. For e.g. is the user enters 7
import java.util.Scanner;
public class Assignment1a {

// Driver code
public static void main(String[] args)

{
int j,n;

//Show a message to a user to input a number


System.out.print("Input the number(Table to be calculated): ");
{

Scanner in = new Scanner(System.in);

//Read an input to store it in a variable


n = in.nextInt();

System.out.println ("\n");

//For loop is used for define length of table


for(j=1;j<=n;j++)

System.out.println(n+" X "+j+" = " +n*j);


}
}
}

Output :
c.Write a program that reads in a number form the user and then displays
the Hailstone sequence for the number.
import java.util.*;
public class Assignment1a {
static int c;

// function to print hailstone numbers


static int HailstoneNumbers(int N)
{
System.out.print(N + " ");

if (N == 1 && c == 0) {

// N is initially 1.
return c;
}
else if (N == 1 && c != 0) {

// N is reduced to 1.
c++;
return c;
}
else if (N % 2 == 0) {

// If N is Even.
c++;
HailstoneNumbers(N / 2);
}
else if (N % 2 != 0) {

// N is Odd.
c++;
HailstoneNumbers(3 * N + 1);
}
return c;
}

// Driver code
public static void main(String[] args)
{
int N = 6;
int x;

// Function to generate Hailstone


x = HailstoneNumbers(N);

// Output: Number of Steps


System.out.println();
System.out.println("Number of Steps: " + x);
}
}
Output :

You might also like