Wednesday 31 January 2018

C++ functions

In this article, you will learn about the functions in C++.why and how we use functions.

What is a function in C++?

A function is a block of code that performs some operation.If we want to use a piece of code again and again in the program we wrap that piece of code in the function and use that piece of code in the program by calling it.

There are two types of functions in C++.
  • Library function or built-in function
  • User-defined function 
Library function:-

Library  function are built-in function in C++.

you can use these function by invoking function directly, you don't need to write these functions.Example sqrt() in cmath header file,strcat() in string header file.

User-defined function:-

C++ allows the programmer to define their own function.

If you want to reuse a piece of code.so you can define that code of piece outside the main() function then you can call it in main() function and it will execute in the piece of code.

Program:

C++  program to add two integers by using user-defined function:-
#include <iostream>
using namespace std;

// Function declaration
int add(int, int);

int main()
{
    int num1, num2, sum;
    cout<<"Enter first number to add: ";
    cin >> num1;
    cout<<"Enter second number to add: ";
    cin >> num2;

    // Function call
    sum = add(num1, num2); //actual parameters
    cout << "Sum = " << sum;
    return 0;
}

// Function definition
int add(int a, int b) //formal parameters
{
    int add;
    add = a + b;

    // Return statement
    return add;
}
Output:-
Enter first number to add: 56
Enter second number to add: 43
sum = 99
Function declaration:-

User-defined functions are unknown to the compiler if we define functions after the main() function, the compiler will show an error.
In C++, declaration of function Without its body to give compiler information about the user-defined function.
// Function declaration
int add(int, int);
Note:

  • No need to write arguments.
  • It is not necessary to declare function if user-defined function exists before main() function.


Function call:-

For the execution of a function, we call it inside the main() function.

    // Function call
    sum = add(num1, num2);
num1 and num2 are actual parameters.

Function definition:-

It is the piece of code or function itself.
// Function definition
int add(int a, int b) //formal parameters
{
    int add;
    add = a + b;

    // Return statement
    return add;
}
int a and int b are formal parameters.
we provide actual parameters to the function, they are copied to the formal parameters and function use these parameters for the result. 

Return statement:

A function can return a single value to the program.
return add;
In this, function returning the sum of a and b;

HAPPY CODING.........













1 comment:

  1. if we want to send a array then
    and that too multidimentional

    ReplyDelete