Last active
January 14, 2019 04:25
-
-
Save theArjun/9e65cc01c06d4e98fc4c1d15117f99ac to your computer and use it in GitHub Desktop.
Factorial By Recursion in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<iostream> | |
| using namespace std; | |
| int factorial(int); | |
| int main(){ | |
| int number, factorialOfNumber; | |
| cout << "Enter a number you want to calculate factorial : "; | |
| cin >> number; | |
| factorialOfNumber = factorial(number); | |
| cout << "Factorial of number is : " << factorialOfNumber << endl; | |
| return 0; | |
| } | |
| int factorial(int number){ | |
| if(number == 1){ | |
| return 1; | |
| }else{ | |
| return number * factorial(number - 1); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Factorial{ | |
| private int number; | |
| // Setter for number. | |
| public void setNumber(int number){ | |
| this.number = number; | |
| } | |
| // Getter for number. | |
| public int getNumber(){ | |
| return this.number; | |
| } | |
| // Getter for factorial number. | |
| public int getFactNumber(){ | |
| return this.factorial(this.number); | |
| } | |
| // Function that calculates factorial of a number by recursion. | |
| public int factorial (int number){ | |
| // Factorial of 0 is suppossed to be 1. | |
| if(number == 0){ | |
| return 1; | |
| }else{ | |
| // This code implements recursion. | |
| return number * factorial(number - 1); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class FactorialDemo{ | |
| public static void main(String[] args){ | |
| Factorial numberOne = new Factorial(); | |
| numberOne.setNumber(5); | |
| System.out.println("Factorial of "+numberOne.getNumber()+" is "+numberOne.getFactNumber()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment