Site icon DataFlair

Function in C and C++ [Quiz included]

Function in C and C++

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 );

 

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

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:

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:

  1. Simple: It is easy to comprehend, define and apply. It basically increases the readability of the code by dividing the code into smaller fragments.
  2. Control: The flow of control from one part of the program to the other is made easier.
  3. Reusability: The reusability of the code increases.
  4. Error-finding: Debugging the program becomes easy as the entire program is divided into small fragments.
  5. Less-Redundant: Redundancy is decreased making the program efficient and faster.
  6. 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:

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:

  1. 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.
  2. sqrt (parameter) – The sqrt function computes the square root of a number entered as a parameter.
  3. abs (parameter) – The abs function computes the absolute value of an integer. In other words, if a negative integer is entered, it becomes positive.
  4. 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.
  5. 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.
  6. 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.
  7. log (parameter) – The log function computes the logarithmic value of the given number with respect to the base taken as constant value ‘e’.
  8. log10 (parameter) – The log10 function computes the logarithmic value of the given number with respect to the base taken as 10.
  9. 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.
  10. 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.
  11. exp (parameter) – The exp function computes the value of e to the power the value of the parameter entered, that is, eparameter.
  12. sin (parameter) – The sin function computes the sine of a given number entered as the parameter.
  13. cos (parameter) – The cos function computes the cosine of a given number entered as the parameter.
  14. tan (parameter) – The tan function computes the tangent of a given number entered as the parameter.
  15. asin (parameter) – The asin function computes the arc sine of a given number entered as the parameter.
  16. acos (parameter) – The acos function computes the arc cosine of a given number entered as the parameter.
  17. atan (parameter) – The atan function computes the arc tangent of a given number entered as the parameter.
  18. sinh (parameter) – The sinh function computes the hyperbolic sine of the value entered as the parameter.
  19. cosh (parameter) –  The cosh function computes the hyperbolic cosine of the value entered as the parameter.
  20. 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++:

  1. 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.
  2. 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++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    What will be the output of the following code?

    #include

    using namespace std;
    int add(int x, int y)
    {
    return x+y;
    }
    int main()
    {
    int a=5, b=6;
    int result=add(a,b);
    cout<<result;
    return 0;
    }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    What will be the output of the following code?

    #include

    using namespace std;
    void change(int *x)
    {
    *x=*x*2;
    }
    int main()
    {
    int a=5;
    change(&a);
    cout<<a;
    return 0;
    }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    What will be the output of the following code?

    #include

    using namespace std;
    int *change(int *x)
    {
    *x=*x+15;
    }
    int main()
    {
    int a=5, b=0;
    b=*change(&a);
    cout<<b;
    return 0;
    }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    What will be the output of the following code?

    #include

    using namespace std;
    int *Ascii(char c)
    {
    int a=c;
    }
    int main()
    {
    char c=’z’;
    int b=*Ascii(c);
    cout<<b;
    return 0;
    }

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    What will be the output of the following code?

    #include

    using namespace std;
    char *Ascii(char *c)
    {
    *c=122;

    }
    int main()
    {
    char b, c=’h’;
    b=*Ascii(&c);
    cout<<b;
    return 0;
    }

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    What will be the output of the following code?

    #include

    using namespace std;
    int convert(char x)
    {
    int b =x;
    }
    int main()
    {
    char c=’a’;
    int b=convert(c);
    cout<<b;
    return 0;
    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    What will be the output of the following code?

    #include
    #include

    using namespace std;
    float func(char x, int y)
    {
    float f = x/y;
    }
    int main()
    {
    char c=’z’; int a=50;
    float b=func(c,a);
    cout<<fixed<<setprecision(3)<<b;
    return 0;
    }

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    What will be the output of the following code?

    #include
    #include

    using namespace std;
    int max(int x, int y)
    {
    if(x>y)
    return x;
    else
    return y;
    }
    int main()
    {
    int a=10, b=12;
    cout<<max(a,b);
    return 0;
    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    What will be the output of the following code?

    #include
    #include

    using namespace std;
    int count(string x)
    {
    int a=sizeof(x);
    return a;
    }
    int main()
    {
    string S=”Delhi”;
    int a=count(S);
    cout<<a;
    return 0;
    }

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    What will be the output of the following code?

    #include
    #include

    using namespace std;
    int count(string x)
    {
    int a=sizeof(x);

    }
    int main()
    {
    string S=”Delhi”;
    int a=count(S);
    cout<<a;
    return 0;
    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    What parameter passing method is it, if values of actual parameters are copied to functional parameters?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    What function is called by the operating system when a user runs a program?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    If the actual and formal parameter refers to the same location, what parameter passing method is it?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    Putting passed parameters name is necessary in:

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    What among the following is not an advantage of function?

    Correct
    Incorrect

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.

Exit mobile version