Function in C++

 Function in C++ 
Function in cpp


A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main().we can also say that A function is block of code that performs specific task.

Syntax of function:
                      return_type  Function_Name(parameters){
                                code performs that task;
}

Types of function:


There are two type function in C++

1.Standard Library Functions: Predefined in C++

2.User define Function: C++ allows the programmer to define their own function .

Program: Write a program to find out the sum of two number using Function   in C++.
Code:
#include<iostream>
using namespace std; 
int sum(int num1,int num2)
{
int c=num1+num2;
return c;
}
int main()
{
int num1,num2;
cout<<"Enter the two number for addtion ";
cin>>num1;
cin>>num2;
cout<<"The sum of "<<num1<<" and "<<num2<<" is "<<sum(num1,num2);
return 0;
}
Output:
Enter the two number for addtion 10
30
The sum of 10 and 30 is 40
--------------------------------

Program: Write a program to find the sum of natural number using function in CPP.
Code:
#include<iostream>
using namespace std;
int addNumbers(int n);
int main()
{
int num, sum;
cout<<"Enter a number ";
cin>>num;
sum=addNumbers(num);
cout<<"The sum of "<<num<<" natural number is "<<sum;

}
int addNumbers(int n) 
{
    if (n != 0)
    return n + addNumbers(n - 1);
    else
        return n;
       }
Output:

Enter a number 100
The sum of 100 natural number is 5050
--------------------------------

Program: Write a program to find the fibonaci serise at that postion using function in cpp.
Code:
#include<iostream>
using namespace std;
int fib(int n)
{
if((n==1)||(n==0))
return n;
else 
return fib(n-2)+fib(n-1);
}
int main()
{ int num;
cout<<"Enter the number to find the fibonaci serise at that postion ";
cin>>num;
cout<<"The fibonaci serise at "<<num<<" is "<<fib(num);
return  0;

}

Output:
Enter the number to find the fibonaci serise at that postion 3
The fibonaci serise at 3 is 2
--------------------------------







Comments

Popular posts from this blog

CYBER SECURITY & CRACKING PASSWORDS

"The Dark Side of Social Media: How It Fuels Digital Addiction and Impacts Mental Health"

Online Platforms to Learn Coding