# Function example in C++ - Algomentor

## Function example in C++

1. program to find factorial of the number using a function.

#include<iostream>
using namespace std;

int fact(int num)
{
int fact = 1;
for(int i=1;i<=num;i++)
{
fact = fact*i;
}
return fact;
}
int main()
{
int n;
cout<<"Enter a number ";
cin>>n;
cout<<fact(n);
}

// Here is the output of code

2. program to print the first 20 Fibonacci number using a function.

#include<iostream>
using namespace std;

void fibo()
{
int num1=0;
int num2=1;
cout<<num1<<" "<<num2<<" ";
for(int i=2;i<=10;i++)
{
num1 = num1+num2;
num2 = num2+num1;
cout<<num1<<" "<<num2<<" ";
}
}

int main()
{
fibo();
}

// Here is the output of code

3. program to take user name and age from one function and print using the second function

#include<iostream>
using namespace std;

int age;
string name;
void get()
{
cin>>name;
cin>>age;
}
void print()
{
cout<<"Welcome "<<name<<" your age is "<<age;
}

int main()
{
get();
print();
}

// Here is the output of code

4. Program to print the maximum of the array using the function.

#include<iostream>
using namespace std;

int getMax(int arr[],int n)
{
int max = arr;
for(int i=1;i<n;i++)
{
if(max<arr[i])
{
max = arr[i];
}
}
return max;
}

int main()
{
int arr[] = {2,4,8,9,41,56,12,94,12,23};
int maxVal = getMax(arr,10);
cout<<maxVal;
}
5. program to print the number of one in the binary string using the function.

#include<iostream>
using namespace std;

int getNumberOfOne(string str)
{
int counter = 0;
for(int i=0;i<str.size();i++)
{
if(str[i]=='1')
{
counter++;
}
}
return counter;

}

int main()
{
string str;
cout<<"Enter a binary string ";
cin>>str;
int numberOfOne = getNumberOfOne(str);
cout<<numberOfOne;
}

// Here is the output of code

Hope you enjoy to learn tutorial on a series of data structure and algorithms made easy we make a tutorial on c++ programming language and data structure and algorithm so please follow us on our social handle.