README.md

December 4, 2022 · View on GitHub

Introducing C++ - Functions

Description

This tutorial intends to teach beginners how to use functions in programs along with the various terms used like 'calling' a function and 'passing' values to a function and so on.

More Info

Submitted On
ByKarthik A
LevelBeginner
User Rating5.0 (15 globes from 3 users)
CompatibilityC, C++ (general)
CategoryDocuments
WorldC / C++
Archive File

Source Code

Introducing C++ - Part 3

 

Functions

 

        We will now see the usage of functions is C++. Functions are very useful if you desire to use a particular set of statements or a particular operation again and again. With the help of a simple example i will explain the concept of functions.

The general form of a function is

     return-type function-name (parameter 1, parameter 2)

     {

 

     }

        return-type     -> Its the value that the function will return after various calculations.

        function-name -> This is the name of the function that we like to use

        parameter 1    ->  This is also called as the argument. These are the variables that are being passed on to the function

        parameter 2    ->  Another variable that is passed to the function

        I will illustrate the use of functions with the help of the following example

#include<iostream.h>

int add(int x, int y)

{

int z;

z=x+y;

return z;

}

void main()

{

int a=3,b=5,c;

c=add(a,b);

cout<<"The sum is "<<c;

}

 

Let us see how the code works

int add(int x, int y)

{

int z;

z=x+y;

return z;

}

        In the above code segment 'add' is the function name and 'int' is the return-type.

       There are two parameters 'int x' and 'int y'.

       The variable int z is used to store the sum of the two numbers.

        As mentioned before,

              return z;

         the integer z is returned back.

 

            Ok but where does the terms 'calling' and 'returning' the values arises? We will see that...

        In the main section you will be able to the lines

int a=3,b=5,c;

        Here we are declaring (and initializing) a and b and declaring a variable c.

        Consider the following line:

c=add(a,b);

        At this point the function gets 'CALLED'. The function 'add' is called with two parameters 'a' and 'b'. It is said that the integers a and b are passed to the function 'add'.

        When the function is called the program control is transferred to the 'add' function. The two parameters a and b are added and 'RETURNED' through the variable 'z'. This variable is stored in 'c' and then printed.

        This is how functions work in C++ and any other language. This is just one way of using functions and you will know more as you proceed.

RATE THE TUTORIAL IF YOU LIKE IT and GIVE YOUR COMMENTS TOO.

THANK YOU!