Assignment 1
[Link] a number to calculate factorial of a number
import [Link];
public class Assignment1a {
public static void main(String[] args) {
int n, c, f = 1;
//Show a message to a user to input a number
[Link]("Enter an integer to calculate its
factorial");
Scanner in = new Scanner([Link]);
//Read an input to store it in a variable
n = [Link]();
//Check whether input value is greater than zero
if (n < 0)
[Link]("Number should be non-negative.");
else
{
//If not greater than zero proceed with calculation factorial
for (c = 1; c <= n; c++)
f = f*c;
[Link]("Factorial of "+n+" is = "+f);
}
}
Output :-
[Link] 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 [Link];
public class Assignment1a {
// Driver code
public static void main(String[] args)
{
int j,n;
//Show a message to a user to input a number
[Link]("Input the number(Table to be calculated): ");
{
Scanner in = new Scanner([Link]);
//Read an input to store it in a variable
n = [Link]();
[Link] ("\n");
//For loop is used for define length of table
for(j=1;j<=n;j++)
[Link](n+" X "+j+" = " +n*j);
}
}
}
Output :
[Link] a program that reads in a number form the user and then displays
the Hailstone sequence for the number.
import [Link].*;
public class Assignment1a {
static int c;
// function to print hailstone numbers
static int HailstoneNumbers(int N)
{
[Link](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
[Link]();
[Link]("Number of Steps: " + x);
}
}
Output :