Program to
Find Factorial of given number.
/* A for loop is used to repeat a statement until a condition is
met. Although for loops frequently are used for simple iteration in
which a statement is repeated a certain number of
times, for loops can be used for just about any kind of loop.
The for loop in Java looks roughly like the following:
for (initialization; test; increment) {
statement;
}
The start of the for loop has three parts:
1. initialization is an expression that initializes the start of the
loop. If you have a
loop index, this expression might declare and initialize it, such as
int i = 0.
Variables that you declare in this part of the for loop are local to
the loop itself;
they cease to exist after the loop is finished executing. You can
initialize more than
one variable in this section by separating each expression with a
comma. The statement int i = 0, int j = 10 in this section would
declare the variables i and j,and both would be local to the loop.
2. test is the test that occurs before each pass of the loop. The
test must be a Boolean expression or a function that returns a
boolean value, such as i < 10. If the test is true, the loop
executes. When the test is false, the loop stops executing.
3. increment is any expression or function call. Commonly, the
increment is used to
change the value of the loop index to bring the state of the loop
closer to returning false and stopping the loop. The increment takes
place after each pass of the loop.
Similar to the initialization section, you can put more than one
expression in this section by separating each expression with a
comma. */
/*Write a program to Find Factorial of Given no. */
class Factorial{
public static void main(String args[]){
int num = 5;
int result = 1;
int result2 = 1;
//using while loop
while(num>0){
result = result * num;
num--;
}
//using for loop
num = 5;
for(int i=num;i>=1;i--){
result2=result2*i;
}
System.out.println("Factorial of Given no. is : "+result);
System.out.println("Factorial of Given no. is : "+result2);
}
} |