Bitcoin

Bitcoin
Bitcoin

Reverse and Randomise Numbers

Here we will write programs to find out the factorial of a number using recursion.
Program 1:
Program will prompt user for the input number. Once user provide the input, the program will calculate the factorial for the provided input number.
/**
 * @description: User would enter the 10 elements
 * and the program will store them into an array and 
 * will display the sum of them.
 */
import java.util.Scanner;
class FactorialDemo{
   public static void main(String args[]){
      //Scanner object for capturing the user input
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the number:");
      //Stored the entered value in variable
      int num = scanner.nextInt();
      //Called the user defined function fact
      int factorial = fact(num);
      System.out.println("Factorial of entered number is: "+factorial);
   }
   static int fact(int n)
   {
       int output;
       if(n==1){
         return 1;
       }
       //Recursion: Function calling itself!!
       output = fact(n-1)* n;
       return output;
   }
}
Output:
Enter the number:
5
Factorial of entered number is: 120
Program 2: 
If you do not want user intervention and simply want to specify the number in program itself then refer this example.
class FactorialDemo2{
   public static void main(String args[]){
      int factorial = fact(4);
      System.out.println("Factorial of 4 is: "+factorial);
   }
   static int fact(int n)
   {
       int output;
       if(n==1){
         return 1;
       }
       //Recursion: Function calling itself!!
       output = fact(n-1)* n;
       return output;
   }
}
Output:
Factorial of 4 is: 24

Example Program to generate random numbers

In the below program, we are using the nextInt() method of Random class to serve our purpose.
/* Program: Random number generator
 * Written by: Chaitanya from beginnersbook.com
 * Input: None
 * Output:Random number between o and 200*/
import java.util.*;
class GenerateRandomNumber {
   public static void main(String[] args) {
      int counter;
      Random rnum = new Random();
      /* Below code would generate 5 random numbers
       * between 0 and 200.
       */
      System.out.println("Random Numbers:");
      System.out.println("***************");
      for (counter = 1; counter <= 5; counter++) {
         System.out.println(rnum.nextInt(200));
      }
   }
}
Output:
Random Numbers:
***************
135
173
5
17
15

No comments:

Post a Comment

Facebook