Simple Example Program for Function
#include<iostream>
using namespace std;
void printmessage() {
cout << "Im Function In C++";
}
int main() {
//Call Simple Function printmessage()
printmessage();
return 0;
}
C++ Program Add Two Numbers using Function.
#include<iostream>
using namespace std;
int addition(int a,int b);
int main()
{
int num1, num2,add;
cout<<"Enter first number: ";
cin>>num1;
cout<<"Enter second number: ";
cin>>num2;
add=addition(num1,num2);
cout<<"Addition is: "<< add<< endl;
return 0;
}
int addition(int a,int b)
{
return (a+b);
}
C++ program to swap two numbers using call-by-value method.
#include<iostream>
using namespace std;
void swap(int,int);
int main()
{
int num1,num2;
cout<<"\n Enter First Number : ";
cin>>num1;
cout<<"\n Enter Second Number : ";
cin>>num2;
cout<<"\n Before Swapping the Value : \n"<<" "<< num1<<"\t"<< num2<<"\n";
swap(num1,num2);
cout<<"\n After Swapping the Value : \n"<<" "<< num1<<"\t"<< num2<<"\n";
}
void swap(int num1,int num2)
{
int num3;
num3=num1;
num1=num2;
num2=num3;
}
Write a function using reference variables as arguments to swap the values of pair of integers.
#include<iostream>
using namespace std;
void swap (int &x, int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
int main()
{
int a,b;
cout<<"Enter the value of a and b";
cin>>a>>b;
cout<<"\n Before swapping"<<"\n A = "<< a<<"\n B = " << b<< endl;
swap(a,b);
cout<<"\n After swapping"<<"\n A = "<< a<<"\n B = " << b<< endl;
return 0;
}
C++ program to print the Fibonacci series using recursion function.
#include<iostream>
using namespace std;
int fibonacci(int num)
{
if((num==1)||(num==0))
{
return(num);
}
else
{
return(fibonacci(num-1)+fibonacci(num-2));
}
}
int main()
{
int num,i=0;
cout<<"\n How many numbers you want for Fibonacci Series : ";
cin>>num;
cout<<"\n Fibonacci Series : ";
while(i< num)
{
cout<<" "<< fibonacci(i);
i++;
}
return 0;
}
C++ program to Calculate Factorial of a Number Using Recursion.
#include<iostream>
using namespace std;
int factorial(int n);
int main()
{
int n;
cout << "Enter number: ";
cin >> n;
cout << "Factorial of " << n << " = " << factorial(n);
return 0;
}
int factorial(int n)
{
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}