EXP-1 Functions and Recursion in C++
EXP-1 Functions and Recursion in C++
#include <iostream>
using namespace std;
// declaring a function
void greet() {
cout << "Hello there!";
}
int main()
{
return 0;
}
Output
Hello there!
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
#include <iostream>
// declaring a function
int add(int a, int b) {
return (a + b);
}
int main() {
int sum;
return 0;
}
Output
100 + 78 = 178
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
int factorial(int);
int main() {
int n, result;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Output
Enter a non-negative number: 4
Factorial of 4 = 24
Example2: C++ Program to calculate the sum of first N natural numbers using recursion
#include <iostream>
using namespace std;
int nSum(int n)
{
// base condition to terminate the recursion when N = 0
if (n == 0) {
return 0;
}
return res;
}
int main()
{
int n = 5;
// calling the function
int sum = nSum(n);
Output
Sum = 15