Functions in C++

               “A set of statements that performs a specific task” is called a function. Generally, the code is reusable in anywhere.

Features:

  • ·       Easy to read.
  • ·       It has modularity.
  • ·       The maintenance of code is easy.

First, consider about the syntax of creating a function.

Syntax:

Function declaration:

‘return_value function_name(datatype parameter1,…datatype parameter);

Eg:

int factorial(int n);

Function Definition:

return_type function_name(parameter1,parameter2,…… parametern)

{

Code;

return();

}

Eg:

int factorial(int n)

{

 Code…

return();

}

The functions can be classified into two types.

·       User defined functions: user can create this function.

·       Built-in functions: these are the system files.

Example:

#include <iostream>

using namespace std;

// Declare the function

int biggest_number(int x, int y,int z);

// code for main() function

int main() {

    int x,y,z;

    cout<< "Enter the three numbers:"<<endl;

    cin>>x>>y>>z;

    int res = biggest_number(x,y,z); // Function call

    cout << "The biggest number is :" << res << endl;

    return 0;

}

// Define the function

int biggest_number(int x, int y,int z) {

    if(x>y && x>z)

     return(x);

    else if(y>z)

     return(y);

    else

    return (z);

}

Output:

Enter the three numbers:

56 78 36

The biggest number is :78

Next one is built in function example.

Built-in function:

This function definition is already available in the system itself. Here, we find the square root of a number.

C++ program to find square root of a number using built-in function:

#include <iostream>

#include<cmath>

using namespace std;

int main() {

    int r,n;

    cout<<"Enter the number :"<<endl;

    cin>>n;

    r=sqrt(n);

    cout<<"The square root of the value is:"<<r<<endl;

    return 0;

}

Output:

Enter the number :

49

The square root of the value is:7

That’s all. Various functions in C++ was explained in detail. Hope you understood. Keep coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.