Lab CSE 304-02
Lab CSE 304-02
Algorithm: Algorithm of adding two numbers using user define function is given below:
Step-1: start
Step-2: Input- Take an integer n as input from the user.
Step-3: Define a Recursive Function factorial(n):
• If n == 1, return 1 (base case).
• Otherwise, return n * factorial(n - 1).
Step-4: Call the factorial() function with the input n and store the result.
Step-5: Output- Print the result.
Step-6: End the program.
Pseudocode:
1. Start
2. Input the number n
3. Define function factorial(n):
• If n == 1, return 1
• Else, return n * factorial(n - 1)
4. Call factorial(n) and store the result in result
5. Print result
6. End
Source code:
#include<bits/stdc++.h>
using namespace std;
int factorial(int n){
if(n==1){
return 1;
}
return n*factorial(n-1);
}
int main(){
int n;
cout<<"Enter the number: ";
cin>>n;
cout<<"Factorial of "<<n<<" is: "<<factorial(n)<<endl;
return 0;
}
Conclusion:
In this lab report, we successfully implemented a program in C++ to calculate the factorial of
a number using a user-defined recursive function. The program demonstrates the use of
recursion, where a function calls itself to solve a problem. By utilizing the base case (n == 1),
we were able to terminate the recursion and compute the factorial for any positive integer input.
This lab enhanced our understanding of recursion and how it can be used to solve problems
efficiently in programming. Overall, the experiment strengthened our knowledge of recursive
functions, basic input/output handling, and C++ programming concepts.