Function example in C++ - Algomentor

Function example in C++


function example in c++

Hi, Welcome to the section of data structures and algorithms made easy, If you have not read the article of function basic then please read this article first in this article I have given an overview of the function then read this article because in This article we don't learn about the function we solve some real example of a function in this section we discuss 4-5 program of C++ with the help of function mean this article is completely practical based 😁.

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

function example in c++


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

function example in c++


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()
{
cout<<"Enter your name ";
cin>>name;
cout<<"Enter your age ";
cin>>age;
}
void print()
{
cout<<"Welcome "<<name<<" your age is "<<age;
}

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

// Here is the output of code

function example in c++


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[0];
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;
}

// Here is the output of code

function example in c++


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

function example in c++



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.

Thank you very much for reading this article and if you like our article then please make sure to share with your coder friends 😀.

Hi if you want to write a post on our website then please check this article on How to do a guest post.

Post a Comment

0 Comments