C++
Recursion & Struct
Recursion Function
# include <iostream>
using namespace std;
void fun (int n) {
if (n<1);
return; \\ base condition
else
cout <<“round:”<< n <<endl;\\ logic output
fun (n-1); } \\ sub problem
int main () {
fun (5) ;
return 0;}
Recursion without condition
• # include <iostream>
• using namespace std;
• void fun (int n) {
• \\ if (n<1);
• \\ return; \\ base condition
• \\ else
• cout <<“round:”<< n <<endl;\\ logic output
• fun (n-1); } \\ sub problem
• int main () {
• fun (5) ;
• return 0;}
4
C++ Programming Code to Find Factorial of Number
Following C++ program ask to the user to enter a
number to find its factorial, then display the result on
the screen :
#include<iostream.h>
using namespace std;
int main() {
int num, i, fact=1;
cout<<"Enter a number : ";
cin>>num;
for(i=num; i>0; i--) {
fact=fact*i;
}
cout <<"Factorial of "<<num<<" is "<<fact;
return 0;
}
Factorial Recursion Function
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
Factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) =
3 * ( 2 * (1 * factorial(0))) =
3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) = 3 * 2 = 6
5
\\ Factorial recursion function
#include<iostream>
using namespace std;
int fact (int n) {
if (n == 0 || n == 1)
return 1;
else
return n * fact (n - 1);
}
int main() {
cout << fact (5);
return 0;
}
\\ Fibonacci recursion function
#include<iostream>
using namespace std;
\\ 0 1 2 3 4 5 6 7………….
\\ 0 1 1 2 3 5 8 13………….
int fib (int n) {
if (n == 0 || n == 1)
return n;
else
return fib (n - 1) + fib (n - 2);
}
int main() {
cout << fib (3);
return 0;
Recursion function to calculate the sum of the
first n natural numbers.
The first n natural numbersare the numbers
from 1 to n.
#include <iostream>
using namespace std;
int sum(int n) {
if (n == 1) return 1;
else return n + sum(n - 1);
}
int main() {
cout << sum(5) << endl;
return 0; }
Drawing rectangle shape (*) using
Nested loop
#include<iostream>
using namespace std;
int main(){
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 6 ; j++)
{
cout << "*";
}
cout << endl;}}
Drawing triangle shape using Nested loop
#include<iostream>
using namespace std;
int main(){
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i ; j++)
{
cout << "*";
}
cout << endl;}}
Drawing triangle shape using Nested loop
#include<iostream>
using namespace std;
int main(){
for (int i = 1; i <= 5; i++)
{
for (int j = 4; j >= i ; j--)
{
cout << “ ";
}
for (int k = 1; i <= i; k++) {
cout << “*” ; }
cout <<endl;}}
Drawing triangle shape using Nested loop
#include<iostream>
using namespace std;
int main(){
for (int i = 5; i >= 1; i--)
{
for (int j = 4; j >= i ; j--)
{
cout << “ ";
}
for (int k = 1; i <= i; k++) {
cout << “*” ; }
cout <<endl;}}
#include <iostream>
using namespace std;
void f(int n)
{
if (n < 0)
return;
else for (i = 0; i < n; i++) {
cout << "*";
}
cout << endl;
f(n - 1); }
int main() {
f(5);
return 0; }
Inbuilt C++ functions