Functions

the basic concepts of functions are explained in this topic

Last Reviewed and Updated on February 7, 2020
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer

My C/C++ Videos on Youtube

Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.

Functions are the basic building blocks of any program, and in any programming language. They are important both for structural programming and object oriented programming.

Function Syntax

A function consists of the following parts

  1. Name
  2. Return Type
  3. Code Body
  4. Parameters

void fx(int i, int j)
{
    int sum = i + j;
    
    cout << "Sum = " << sum << endl;
 
}
 
The above function has a name called "fx", and it accepts two parameters, i and j. The code body is contained in curly braces and displays the sum of the two parameter variables.

Execution of a Function

The code of a function can be executed only through a function call. It doesn't execute automatically. It is like a calculator where you have to give inputs and press the enter key to start a calculation and display the result. The following code shows how to call a function. The function is being called from the main function by passing 8 and 9 as the input arguments.

void showSum(int x, int y)
{
     // store sum in z
     int z = x + y;
 
     // display the answer
     cout << z << endl;
}
 
int main()
{
 
     // calling the function, pass arguments
     showSum(8, 9);
 
}

Steps in the Execution

I will explain them with the help of an analogy. Suppose you are in a car and driving along a highway. It can be thought of as a journey along the main function of a C program. You are executing statements one by one - like changing the gears, etc.,

After some time you spot an eating restaurant, and wish to have some snacks. For this you take your car out of the highway and move it to the parking of that restaurant. There you spend some time, and then again resume your journey back on the highway.

The highway can be thought of as the main function. When you stop at a restaurant, it is like jumping out of the main function and calling into another function, and when that function is completed you come back to main, and resume your journey towards the return 0 statement.

A function stops its execution at a return statement, or when all the statements have been executed and the closing brace reached.

Return from a function

A function can return data. It could return an int number, or a char, and even objects of classes and structs. The return is usually an end result of the work done by the code of a function. For example, it could be the result of a mathematical calculation.

The return statement is also used to return success or failure. In such cases the return value is a boolean type.

It can also be used to return detailed status codes, like the reason for a failure. For example if you are using a function to connect to a database, your function could return a different integer number, representing different reasons of failure, or success. Usually, zero is for success, and other codes can be given other custom meanings.

Maximum number of Arguments

According to the standard, a C++ compiler should support atleast 256 arguments to a function call. Similarly, the number of parameters that a function should support is 256.

Call by Value

When arguments are passed to a function, they are copied into the parameter variables. The function acts on it's parameters, and any changes it makes to it's parameters have no effect on the arguments passed to it. This is pass by value. In the code below, z is copied into y. The function fx makes changes to y, but not to z. So the output in the main would be "z = 9". This is the default behaviour, and it is called passing an argument by value.


int fx(int y)
{
    y += 10;
    cout << y << endl;
}
 
int main()
{
    int z = 9;
    
    fx(z);
     
    // 9
    cout << "z = " << z << endl;
 
    return 0;
}

Call by Reference

First of all you should be aware of a reference. A reference is an alternate name for the same identifier. It is also called an alias. A student has a certain name in the school, but at home he has another name. The same person can be referred through his home name also. His home name is an alias for him.

In C++ we can give alternate name to any variable. Consider the code below. Here y is a reference to x. It is not a separate variable. If you make changes to x, and later display the variable y, the output would be the latest value of x only, because y is just a second name for x.


int x = 9;
 
// y is a reference or alias to x
int& y = x;
 
x++;
 
// prints 10
cout << y << endl;

Function parameters can be expressed as references. In the code below, The parameter y is an alias name for the argument z. When z is passed to the function, it gets a new name called y. So y is basically z only. The function fx makes changes to y, but since y is a reference for z, the changes are actually taking place on z. When z is printed in main, the output is 19.


int fx(int& y)
{
    y += 10;
    cout << y << endl;
}
 
int main()
{
    int z = 9;
    
    fx(z);
 
    // 19
    cout << "z = " << z << endl;
 
    return 0;
}

Simple function no argument no return type

Write a program to print "I am Hoven trained" using a function.

#include<iostream>
#include<cstdio>
 
using namespace std;
 
void show() // function definition 
{
 
    cout << "I am Hoven trained ";
    
}
 
int main()
{
    
    show(); // function call
        
}

A function with argument but no return type

Write a function called prod to display the product of two numbers a = 3 , b = 4. The function accepts two arguments. Call it in main.

#include<iostream>
#include<cstdio>
 
using namespace std;

void prod( int a,int b) // function definition
{ 
            
    int s; 
         
    s = a * b;
        
    printf("prod = %d", s); 
        
}
     
int main()
{
    
    prod (3, 4); // function call
     
    return 0; 
     
}
 
    
 

Many functions

Write functions for sum, product, division, subtraction. Each function accepts two parameters. Pass a = 100, b =15 as arguments from main.
#include<iostream>
#include<cstdio>
 
using namespace std;
 
void addition(int a, int b) // function defination
{
    
    int i;
    
    i = a + b ;
    
    cout <<"After addition = " << i << endl;
    
}
 
void product(int a, int b)
{
    
    int i;
    
    i = a * b ;
    
    cout <<"After product = " << i << endl;
 
}
 
 
void division(int a, int b)
{
    
    int i;
    
    i = a / b ;
    
    cout <<"After division = " << i << endl;
    
}
 
void subtraction(int a, int b)
{
    
    int i;
    
     i = a - b ;
    
    cout <<"After subtraction = " << i<< endl ;
    
}
 
 
 
int main()
{
    
    addition(6, 7); 
    
    subtraction(5, 9);
    
    product(23, 98);
    
    division(145, 5);
    
    return 0;
    
}

Function, no argument with return type

Write a program to find the circumference of a circle. Take radius 5. The function should calculate and return the value of the circumference.
#include<iostream>
#include<cstdio>
 
using namespace std;
 
float Circumference()
{

    int radius = 5;
    
    float f = 2 * 3.14 * radius;
    
    return f ;
        
}
 

int main()
{

    cout <<"Circumference of circle = " << Circumference() ;
    
    return 0;
    
}

Function with argument and return type

Write a function that has two parameters num1 and num2. It adds them and returns their sum. Use this function to display the sum of two numbers.
#include<iostream>
#include<cstdio>
 
using namespace std;
 
int sum (int num1, int num2) 
{ 
 
    int num3; 
    
    num3 = num1 + num2 ; 
    
    return num3 ; 
 
}
 
int main() 
{
    
    int a, b; 
    
    printf("\nEnter the two numbers one by one: ");
    
    cin >> a; 
    
    cin >> b;
    
    int c = sum( a, b );
    
    printf("\nSum is: %d",c); 
    
    return 0;
 
}
 

Function with return type and parameters

Write a program to get cube and square of a number. Write two functions called cube and square and call them from main, by taking an input value from the user.
#include<iostream>
#include<cstdio>
 
using namespace std;
 
int cube (int num1) 
{ 
 
    int num3 = num1 * num1 * num1; 
    
    return num3 ; 
 
}
 
int square (int num1) 
{ 
 
    int num3 = num1 * num1 ; 
    
    return num3 ; 
 
}
 
int main() 
{
    
    int a; 
    
    printf("Enter a number: ");
    
    cin >> a; 
        
    int c = cube(a);
    
    printf("\n Cube of number is : %d", c); 
    
    int d = square(a);
    
    printf("\nSquare of number is : %d", d); 
    
    return 0;
 
}
 

Call by value

write a function called "call_by_value". This function takes its argument by value. Call this function from main by passing some argument.


#include<iostream>
#include<cstdio>
 
using namespace std;
 
void call_by_value(int x) 
{
    
    printf("Inside call_by_value x = %d before adding 10.\n", x);
    
    x += 10;
    
    printf("Inside call_by_value x = %d after adding 10.\n", x);
    
}
 
int main() 
{
    
    int a = 10;
    
    printf("a = %d before function call_by_value.\n", a);
    
    call_by_value(a);
    
    printf("a = %d after function call_by_value.\n", a);
    
    return 0;
 
}
 

Use of global variable with function

Write a program having two global variables, A and B. Put some values to the global variables in main, and then get sum of the variables with a function called "Add". This function accepts no arguments, and returns the sum of A and B.

#include<iostream>
#include<cstdio>
 
using namespace std;
 
// global variables
int A;
 
int B;
 
int Add()
{
 
    return A + B;
 
}
 
int main()
{
    
    int answer; // Local variable
        
    A = 5;
        
    B = 7;
        
    answer = Add();
        
    printf("%d\n",answer);
        
    return 0;
        
}

Calling a function from another

Write a program having four different functions, and call them one by one from another function. And call that function from main. Each of the five functions should print some message so that you can trace the sequence of calls.

#include<iostream>
#include<cstdio> 
 
using namespace std;
 
void funct4()
{
 
    cout << "function 4 is called "<< endl;
 
} 
 
void funct3()
{
 
    printf("function 3 is called \n");
    
    funct4(); 
 
}
 
void funct2()
{
 
    printf("function 2 is called \n");
    
    funct3();
 
}
 
void funct1()
{
 
    printf("function 1 is called \n");
    
    funct2();
 
}
 
void func()
{
    printf("function is called \n");

    funct1();
    
    funct2();

    funct3();

    funct4();
}

int main()
{ 
 
    func();
    
    return 0;
    
}

Function overloading

Write a program having 3 functions with same name funct, but different signatures. Call them one by one from the main function.
#include<iostream>
#include<cstdio> 
 
using namespace std;
 

void funct(int a, int b, char c)
{
 
    printf("function with three params: %d %d %c\n",a,b,c);    
 
}
 
void funct(int a, int b)
{
 
    printf("function with two params:%d %d\n",a,b);

}
 
void funct(int a) 
{
 
    printf("function with one param: %d\n", a);
 
}
 
 
int main()
{ 
 
    funct(11); 

    funct(88, 9);

    funct('G', 'A', 'M');
    
    return 0;
    
}

Classroom Training

Classroom training in C/C++ is available at our training institute. Click here for details. You can also register yourself here.

Video Tutorial

We have created a video tutorial that can be downloaded and watched offline on your windows based computer. It is in the form of an exe file. No installation is required, it runs by double clicking the file. Since the exe file is hosted on the Google Drive, it should be very safe because Google itself checks for any virus or malware. The video can be watched offline, no internet is required.

Pricing

This single video will cost you USD $5. When you download the video, you will be able to watch the first few minutes for free, as a sample. The video app will prompt you for payment through PayPal and other payment options. If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials The entire set is priced at USD $50.

Screenshots

This is a screenshot of the software that should give you a good idea of the available functionality. Click on the image to see a larger view.screenshot of the video being played in the software

Installation

This software doesn't require any installation. Just download and double-click to run it. It doesn't require administrative priviliges to run. It runs in limited access mode, so should be very safe.

supports windows xp and later Supported Operating Systems

These videos can be run on 32-bit as well as 64-bit versions of the Microsoft Windows Operating Systems. Windows XP and all later OS are supported. If you want to run it on Windows XP and Windows Vista, then you must also have the .NET Framework Version 3.5 installed on your machines. Those users who have Windows 7 and later donot have to worry because these operating systems already have the .NET Framework installed on them.

Download Links

IMPORTANT NOTE: This download contains ONLY ONE video. The video is about the topic of this tutorial.

Want ALL Videos? If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials. TIP: If you plan to buy these videos, then it would be more economical to buy the entire set.

DISCLAIMER: Even though every care has been taken in making this software bug-free, but still please take a proper backup of your PC data before you use it. We shall not be responsible for any damages or consequential damages arising out of the use of this software. Please use it solely at your own risk.

Please download the software here.
download the video Basic Concepts of Functions in C



Creative Commons License
This Blog Post/Article "Functions" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2020-02-07. Published on: 2015-10-05