# Function in C and C++ [Quiz included]

*Function in C and C++ is a set of statements that we use in order to take various inputs and perform some calculations or computations to obtain the output*. This tutorial is specially dedicated to functions in the C/C++ programming language, that covers its syntax, types, significance, different ways to call a function, and types of function arguments. Let’s start our journey with an example.

Suppose you want to compute the area of a right-angled triangle for a given set of 10 triangles. A novice at programming who does not have the knowledge of functions would probably say:

Define 10 separate variables to store the area of each triangle and then display it.

Sounds pretty inconvenient, right? What if the number of triangles whose area to be computed is increased to 30? It is not practically feasible to follow the traditional method. This is where the role of functions comes into play.

The above-mentioned problem can easily be resolved by defining a function to compute the area of a triangle taking 2 parameters into consideration, that is, base and height. Then, we can define a single variable that would return its area. The parameters of the 30 triangles in hand simply need to be passed to the function and we get their respective areas without much hassle.

*Don’t forget to check quiz on functions in C and C++ at the end of this tutorial*

## Function in C and C++

**In layman language**, *a function is anything that is done to achieve a specific purpose*.

**In programming**, *a function refers to the collection of statements that together performs a specific task*. Functions give you the provision to divide your code into fragments to reduce code complexity, which you might have already inferred after pondering on the introductory problem statement.

**Key takeaway:** Every program in C and C++ has at least one function, that is, the **main()** **function**.

## Syntax of Function

The basic syntax of a function in C/C++ has 2 parts, namely:

**1. Function Declaration **

*return_type function_name ( parameter list );*

- The function declaration informs the C/C++ compiler about the return type and number of arguments/parameters the function generates.
- It is not necessary to initially declare a function. The function can directly be defined.

**2. Function Definition**

Any function in C and C++ is defined in a similar way the main function is. Before the function name, we need to specify its return type. It depends on the wish of the programmer if he wants to pass any arguments to the function or not. The entire body of the function is enclosed within curly braces “{ }” and a set of statements is written that tells the function what to do.

return_type function_name ( parameter list) { statement(s) }

## Types of Function in C and C++

Functions in C and C++ are broadly classified into two categories, according to the ones already available in the C/C++ compiler and the ones which can be defined and executed in run time. They are:

### 1. Standard Library Functions

- These functions are already pre-defined by the C/C++ compiler and hence cannot be modified. These functions act as pillars to the C and C++.
- They can be used to perform input and output operations using the
**scanf()/cin**and**printf()/cout****function**respectively, mathematical operations like finding the square root of a number or the power of a number using**sqrt() or pow() function**respectively, provided that the required header files are included.

Here is a program that illustrates the use of ** standard library functions**, considering a mathematical function, sqrt() to compute the square root of a positive integer:

#include <stdio.h> #include <math.h> int main() { printf("Welcome to DataFlair tutorials!\n\n"); double number = 3, square_root; square_root = sqrt(number); printf("The square root of %lf is: %lf", number, square_root); return 0; }

**Code on Screen**

**Output-**

##### Example of Standard Library Function in C++

Here is a program in C++ that illustrates the use of standard library functions, considering a mathematical function, sqrt() to compute the square root of a positive integer:

#include <iostream> #include <math.h> using namespace std; int main() { cout<<"Welcome to DataFlair tutorials!"<<endl<<endl; double number = 3, square_root; square_root = sqrt(number); cout<<"The square root of " << number << " is: " << square_root<<endl; return 0; }

**Code- **

**Output-**

### 2. User-defined Functions

As discussed earlier, the C and C++ language give the programmer the provision to declare and define his own functions, according to his own convenience. Another benefit it offers is that the user-defined function can be added to the standard library for standard use.

##### Syntax of user defined function in C

*#include <stdio.h>*

*void function_name()*

*{*

*statement(s) // Body of the function*

*}*

*int main()*

*{*

*statement(s)*

*function_name(); // Function calling*

*statement(s)*

*}*

##### Example of User-defined Function in C

Here is a code in C which illustrates the use of a** user-function in C** to compute the area of a right-angled triangle:

#include<stdio.h> #include<math.h> double area_of_triangle(double,double); // function declaration int main() { printf("Welcome to DataFlair tutorials!\n\n"); double base, height, area; printf("Enter the base and height of the triangle respectively: "); scanf("%lf%lf", &base, &height); area = area_of_triangle(base, height); printf("The area of the triangle is: %.2lf\n", area); return 0; } double area_of_triangle(double base, double height) { double area; area = 0.5*base*height; return area; }

**Code on Screen-**

**Output-**

##### Syntax of User-defined Function in C++

*#include <iostream>*

*using namespace std;*

*void function_name()*

*{*

*statement(s) // Body of the function*

*}*

*int main()*

*{*

*statement(s)*

*function_name(); // Function calling*

*statement(s)*

*}*

##### Example of User-defined Function in C++

Here is a code in C++ which illustrates the use of a user-function to compute the area of a right-angled triangle:

#include <iostream> #include <math.h> using namespace std; double area_of_triangle(double,double); // function declaration int main() { cout<<"Welcome to DataFlair tutorials!"<<endl<<endl; double base, height, area; cout<<"Enter the base and height of the triangle respectively: "; cin>>base; cin>>height; area = area_of_triangle(base, height); cout<<"The area of the triangle is: "<< area <<endl; return 0; } double area_of_triangle(double base, double height) { double area; area = 0.5*base*height; return area; }

**Code**–

**Output-**

**Key takeaway:**

- Program execution starts from the
**main() function**. - As soon as the function is called in the main function, the flow of control goes over to the function and the function gets executed.
- After the function has been executed, the flow of control returns back to the next statement in the main() function.

In order to acquaint you with the syntax of functions, let’s go back to the introductory problem.

For simplicity sake, let’s consider only one set of a triangle.

## Importance of Functions in C and C++

So far we saw a couple of codes for function in C and C++ which helped us gain an insight as to why functions are an integral part of a programming language.

To sum it up, here are the* salient features of functions in C/C++ *which make it so appealing:

**Simple:**It is easy to comprehend, define and apply. It basically increases the readability of the code by dividing the code into smaller fragments.**Control:**The flow of control from one part of the program to the other is made easier.**Reusability:**The reusability of the code increases.**Error-finding:**Debugging the program becomes easy as the entire program is divided into small fragments.**Less-Redundant:**Redundancy is decreased making the program efficient and faster.**Time-saving:**It saves a considerable amount of time.

## Function Call Methods

In order to understand *what a function call is*, we need to understand the difference between actual parameters and formal parameters.

ACTUAL PARAMETER | FORMAL PARAMETER |

We use while calling the function. | Use it in the function header. |

We pass the actual values to the function definition through the function call. | We use it to receive the values that we pass to the function through function calls. |

The values may be variable (global or local) or constant | The values are simply local variables |

In C and C++, there are basically 2 methods to call a function:

**1. Call by value:** The actual parameters get copied to the formal parameters but both the parameters are created in different memory locations. Any changes that are made inside the functions are not reflected in other functions.

**2. Call by reference:** Instead of the actual value, the address of the value is passed to the function and both the parameters will be created in the same memory location. If changes are made inside the functions, it would be reflected in other functions.

## Types of Function Arguments

C and C++ give the programmer the provision to define and use a function with or without arguments or with or without return types.

But it is important to note that in C/C++, functions cannot return arrays or other functions.

Considering the possibilities in hand, we can say that there are basically 4 types of function arguments are available. They are namely:

- Without arguments and without return value
- With arguments and without return value
- Without arguments and with a return value
- With arguments and with a return value

## Math Functions in C and C++

The C/C++ Standard library offers a variety of in-built mathematical functions. Instead of deriving the logic of certain mathematical problems on our own, we can always choose the easier way out. C/C++ gives the programmer the provision to directly use some of the pre-defined functions accessible through the <math.h> header file.

Here are some of the functions available in the C Standard Library:

**pow (parameter1 , parameter2) –**The pow function calculates the power of a number to which it is raised. There are essentially 2 parameters, the first one in which we have to put the base value and the second one in which the exponent value.**sqrt (parameter) –**The sqrt function computes the square root of a number entered as a parameter.**abs (parameter) –**The abs function computes the absolute value of an integer. In other words, if a negative integer is entered, it becomes positive.**ceil (parameter) –**The ceil function rounds off the value of a given number entered as a parameter. It returns an integral value either greater than or equal to that number.**floor (parameter) –**The floor function also rounds off the value of a given number entered as a parameter. It returns an integral value either lesser than or equal to that number.**fabs (parameter) –**Just like the abs function, the fabs function converts the given number into a positive number but the difference is that the fabs function works with floating-point values as well.**log (parameter) –**The log function computes the logarithmic value of the given number with respect to the base taken as constant value ‘e’.**log10 (parameter) –**The log10 function computes the logarithmic value of the given number with respect to the base taken as 10.**fmod (parameter1, parameter2) –**The fmod function computes the remainder when the given value in the first parameter is divided by the given value in the second parameter.**modf (parameter1, *parameter2) –**The modf function returns the fractional part of the given value (The decimal part of a number) entered as the first parameter.**exp (parameter) –**The exp function computes the value of e to the power the value of the parameter entered, that is, eparameter.**sin (parameter) –**The sin function computes the sine of a given number entered as the parameter.**cos (parameter) –**The cos function computes the cosine of a given number entered as the parameter.**tan (parameter) –**The tan function computes the tangent of a given number entered as the parameter.**asin (parameter) –**The asin function computes the arc sine of a given number entered as the parameter.**acos (parameter) – T**he acos function computes the arc cosine of a given number entered as the parameter.**atan (parameter) –**The atan function computes the arc tangent of a given number entered as the parameter.**sinh (parameter) –**The sinh function computes the hyperbolic sine of the value entered as the parameter.**cosh (parameter) –**The cosh function computes the hyperbolic cosine of the value entered as the parameter.**tanh (parameter) –**The tanh function computes the hyperbolic tangent of the value entered as the parameter.

**Learn Virtual Function in C++ with Real-time Example**

**Key takeaway:** All the trigonometric values should be in radian.

##### Example of Math Function in C

Here is a code in C that illustrates the use of some of the basic mathematical functions available in the C programming language.

#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { printf("Welcome to DataFlair tutorials!\n\n"); printf("%f\n",ceil(1.8)); printf("%f\n",ceil(5.2)); printf("%f\n",floor(4.9)); printf("%f\n",floor(3.3)); printf("%f\n",sqrt(144)); printf("%f\n",sqrt(50)); printf("%f\n",pow(2,10)); printf("%f\n",pow(4,4)); printf("%d\n",abs(-18)); printf("%d\n",abs(30)); return 0; }

**Code-**

**Output-**

**Since C++ is the superset of C, it is pretty obvious that C++ supports more functions than C.**

Here are some of the additional mathematical function included in **<math.h>** Library in C++:

**hypot (parameter1 , parameter2) –**The hypot() function computes the hypotenuse of a right-angled triangle by taking the other two known sides of the triangle as parameters.**atan2 (parameter1 , parameter2) –**The atan2 function computes the tangent of parameter1/parameter2

##### Example of Math Function in C++

Here is a code in C++ that illustrates the use of some of the basic mathematical functions:

#include <iostream> #include <stdlib.h> #include<math.h> using namespace std; int main() { cout<<"Welcome to DataFlair tutorials!"<<endl<<endl; double a = 49; double b = 16; double c = 2; double d = -5; double x = 0.785398; // Value in radians of 45 degrees double f = 3; double g = 5; // Basic math functions cout << "The square root value of "<< a << " is: " << sqrt(a) << endl; cout << b << " raised " << " to the power " << c << " is: " << pow(b, c) << endl; cout << "The absolute value of " << d << " is: " << abs(d) << endl; // Trigonometric functions cout << "The sine of " << x << " is: " << sin(x) << endl; cout << "The cosine of " << x << " is: " << cos(x) << endl; cout << "The tangent of " << x << " is: " << tan(x) << endl; cout << "The atan2 of " << b << " and " << c << " is: " << atan2(b,c) << endl; // Pythagoras cout<< "The hypotenuse of the right angled triangle of sides "<< f << " and " << " g " << " is: " << hypot(f,g)<<endl; return 0; }

**Code-**

**Output-**

### Quiz on Functions in C and C++

## Summary

Now, you know the importance of functions in C and C++ and why we declare them. After this discussion, it is safe to say that C/C++ without functions is a sportsman without a ribcage. Hence it is crucial to understand the concept of functions to become a good programmer and become pioneers in the field of programming by developing your own functions.

**Did you know we work 24x7 to provide you best tutorials**

Please encourage us - write a review on **Google**

Q9 none anwer correct