Wednesday, March 4, 2020

Functions


1.    Functions
function is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and programs can define additional functions. You can divide up your code into separate functions.

One reason forthe use of functions is to avoid clutter in the main() logic of the code and enhance its readability. Other reasons are ease of debugging (since functions can be separately tested than the actual code they are used in), ease of development in bigger teams where lots of programmers code, remove redundancy in code, etc.

You can divide your code into separate functions. How you split code among different functions is up to you, but logically the division usually is such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return type, and parameters (or arguments). A function definition provides the actual body of the function.

When the segment of code within a function is required at a certain point in the code, the functionis called (invoked) by the name of the function, passing the necessary parameters (arguments) by value or by reference and storing the return value of the function if needed. Note that a function may or may not not return a value.

The C++ standard library provides numerous built-in functions that your program can use. For example, function memcpy() to copy one memory location to another location etc.

Functions are also called methods, sub-routines or procedures.

Defining a function:
The general form of a C++ function definition is as follows:




return type function_name( parameters list ){
//body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the parts of a function:

·         Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

·         Function Name − This is the actual name of the function.

·         Parameters − A parameter is like a placeholder. The When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function; all three are important. Parameters are optional; that is, a function may contain no parameters.

·         Function Header − The function name and the parameter list together constitute the function signature. When the return type is also included, this is called function header. Parameters in the header are called formal parameters.

·         Function Body − The function body contains a collection of statements that define what the function does.

Example 1:

Following is the source code for a function called maxval(). This function takes two parameters num1 and num2 and returns the larger of both:

// function returning the max between two numbers
int maxval(int num1, int num2)
{
   // local variable declaration
   int result;
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
}



Function Declaration:
A function declaration tells the compiler about the name of a function and the parameters to the function. The actual body of the function may be defined separately.

A function declaration has the following parts:

return_type function_name( parameters list );

For the above defined function maxval(), following is the function declaration:

int maxval(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so following is also valid declaration:

int maxval(int, int);

Calling (invoking) a function:
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.

When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store or print the returned value. For example:

Example 2:

#include <iostream>
using namespace std;

int main () {
   int a = 100, b = 200, ret;
   ret = maxval(a, b);// calling a function to get max value.
   cout << "Max value is: " << ret << endl;
   return 0;
}

int maxval(int num1, int num2){ //returns max of two numbers
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result;
}

Try to compile the above code. It will result in a syntax error. Why?
Correct the error by declaring the function maxval() above main():

int maxval(int num1, int num2);//function declaration

This time, the compile will run fine. After running the final executable, it would produce the following result:

Max value is: 200

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function:

1.    Call by Value: This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
2.    Call by Reference: This method copies the reference (address) of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the actual argument.

There is a third type -- call by pointer, but you would know about it in subsequent courses.

By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function. The example above called maxval() function using the same method.

Calling a function by reference:
To call a function by reference you need to change the function declaration/definition. However, calling of the function is not changed. Instead of declaring the parameters as variables, you use the ampersand sign (‘&’) to specify the names of the parameters as references to the variables passed to the function upon calling. In this call type, new (local) variables are not created in the function; rather it is just a new name given to the same variable (alias). Since new variable is not created, if you change the value of the variable in the function, the variable in the main() would also change. To demonstrate calling by reference, the code in example 2 is changed. Look keenly at the changes:

Example 3:

#include <iostream>
using namespace std;

int maxval(int &num1, int &num2);// function declaration

int main () {
   int a = 100, b = 200, ret;
   ret = maxval(a, b);// calling a function to get max value.
   cout << "Max value is: " << ret << endl;
   return 0;
}

int maxval(int &num1, int &num2){ //returns max of two numbers
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result;
}

There are no changes except the use of & in the formal parameter list! In all other respects, example 2 and example 3 codes are alike.

Example 4:

#include <iostream>
using namespace std;

void maxval(int num1, int num2, int &max);// function declaration

int main() {
   int a = 100, b = 200, ret;
maxval(a, b, ret);//a,b passed by value,ret passed by reference
   cout << "Max value is: " << ret << endl;
   return 0;
}

void maxval(int num1, int num2, int &m){ //finds max of two numbers
   if (num1 > num2)
m = num1;
   else
m = num2;
}

Lastly look at the following code and see how multiple functions with the same name can also be used in the same code. The compiler has no ambiguity about which function to call since the parameter list of each is different. This is known as function-overloading.

Try to identify which function call invokes which specific function:

 

Example 5:

#include <iostream>
using namespace std;

int maxval(int num1, int num2);
void maxval(int, int, int &);      //names not needed in declaration

const int SIZE = 2;

int main () {
   int a = 100, b = 200, ret;

   cout << "Max value is : " <<maxval(a,b) << endl;
   maxval(a, b, ret); //note this cannot be used within cout statement!
   cout << "Max value is : " << ret << endl;

   return 0;
}

int maxval(int num1, int num2) {
return (num1 > num2) ? num1 : num2;
}

void maxval(int num1, int num2, int &m){
m = (num1 > num2) ? num1 : num2;
}


---------------------------------------------------------------------------------------------------------------------
Passing Array to function:
If you want to pass a single-dimension array as an argument in a function, you would have to declare function formal parameter in one of following two ways and both declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received.



Way-1

Formal parameters as a sized array as follows −
void myFunction(int param[10]) {
   .
   .
   .
}

Way-2

Formal parameters as an unsized array as follows −
void myFunction(int param[]) {
   .
   .
   .
}

Example 6:
Calculating average of array elements.
#include <iostream>
using namespace std;

// function declaration:
double getAverage(int arr[], int size);

int main () {
   // an int array with 5 elements.
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   // pass pointer to the array as an argument.
   avg = getAverage( balance, 5 ) ;

   // output the returned value
   cout << "Average value is: " << avg << endl;
   
   return 0;}
double getAverage(int arr[], int size) {
  int i, sum = 0;      
  double avg;         

   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }
   avg = double(sum) / size;
   return avg;
}
Remember: Arrays are always passed by reference into the function.
Task # 1:
In code of example 2, change the values of num1 and num2 in maxval() and see if the values of a and b used in main have changed or not?

CODE:
#include <iostream>
using namespace std;
int maxval(int, int);
int main () {
   int a = 100, b = 200, ret;
   ret = maxval(a, b);// calling a function to get max value.
   cout << "Max value is: " << ret << endl;
   cout<<"value of a i.e num 1 :"<<a;
   cout<<endl<<"value of b i.e num 2 : "<<b;
   return 0;
}

int maxval(int num1, int num2){ //returns max of two numbers
   int result;
  num2=120;////does not change value in main () as integer is passed by value
  num1=220;    ////does not change value in main () as integer is passed by value
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result;   /// only result is returned
}



Task # 2:
In code of example 3, change the values of num1 and num2 in maxval() and see if the values of a and b used in main have changed or not?
CODE:
#include <iostream>
using namespace std;

int maxval(int &num1, int &num2);// function declaration

int main () {
   int a = 100, b = 200, ret;
   ret = maxval(a, b);// calling a function to get max value.
   cout << "Max value is: " << ret << endl;
  cout<<"value of a i.e num1 :"<<a;
   cout<<endl<<"valuve of b i.e num 2 : "<<b;
   return 0;
}

int maxval(int &num1, int &num2){ //returns max of two numbers
   int result;
   num2=120;              ////changes value in main as integer is passed by refrence
   num1=220;////changes value in main as integer is passed by refrence
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result;
}
Task # 3:
Make functions for the four arithmetic operations (+, -, *, /) to be used in a code. For example, if a user wants to perform an operation 15 + 7 then a function Add must be used in the code to calculate the answer i.e. 22 and then display on the console. Print all answers in main() function.

void add(----,------)
double subtract(----,----)
void multiply(----,----)
double division(-----,------)
CODE:
#include <iostream>
using namespace std;

void sum(double & ,double&,double&);
double subtract(double,double);
void multiply(double &,double&,double &);
double division(double,double);
int main()
{
            double nsubtract,nmultiply,ret;
             
double num1,num2;
char a;
cout<<"Input Expression e.g  2+2 :";
cin>>num1>>a>>num2;
switch(a)
    {
        case '+':
         sum(num1,num2,ret);
        // ret = sum(num1, num2,ret);
             cout<<"Result of calculation : "<<ret ;
            break;
        case '-':
            ret=subtract(num1,num2);
             cout<<"Result of calculation : "<<ret;
            break;
        case '*':
            multiply(num1,num2,ret);
             cout<<"Result of calculation : "<<ret;
            break;
        case '/':
          ret= division(num1,num2);
             cout<<"Result of calculation : "<<ret;
            break;
}

            return 0;
}
void sum(double& a ,double& b, double & n)
{
           
            n=a+b;
           
}
double subtract(double a,double b)
{
            double nsubtract;
            nsubtract=a-b;
            return nsubtract;
}  
void multiply(double& a,double& b,double & n)
{
           
            n=a*b;
}
double division(double a ,double b)
{
            double ndivision;
            ndivision=a/b;
            return ndivision;
}
Task # 4:
Ask the user to enter marks of upto 50 students of a class. Print the highest marks obtained by any student. In main(), call only input() and highest_marks() functions. Function input() should ask the user how many students are present in the class.
CODE:
#include <iostream>
using namespace std;
double input(double array[50]);
double highest_marks(double array[50]);
int main()
{
double array[50],result;
input(array);
result=highest_marks(array);
cout<<"Highest marks are : "<<result;


      return 0;
}
double input(double a[50])
{int i,count;
cout<<"Input number of students that are present : ";
cin>>count;
for (int i=0;i<count;i++)
{
      cout<<"Input marks of student no "<<i+1<<": ";
      cin>>a[i];
}

}
double highest_marks(double a[50])
{

double result=0;
      {
                   for (int i = 0; i < 50; i++)
             {
                if (a[i] > result)
                        result = a[i];
             }
            
             return result;
      }}

No comments:

Post a Comment

Functions & BASIC FILE I/O

A.    Files : For storage of data for later use, files are used. Files are stored on the Hard Disk Drive (HDD). There are two types of f...