Friday, December 23, 2016

Passing a 'Function' as a argument to another Function-C++

#include<iostream>
using namespace std;

int sum(int a,int b)
{
   return a+b;
}
void f2(int (*f)(int,int),int a,int b) //'*f' is a POINTER TO A FUNCTION whose RETURN TYPE is                                                           //'int' and arg type (int,int)  . Here, '*f' is FORMAL PARAMETER
{                                                                
  cout<<sum(a,b)<<endl;
}
int main()
{   int (*p1)(int,int)=&sum;          //Here, '*pf1' is ACTUAL PARAMETER
    f2(sum,10,20);                         //NAME OF A FUNCTION IS ITSELF A POINTER TO ITSELF
    f2(p1,20,79);
    return 0;

}

Array as Function Argument -C++

#include<iostream>
using namespace std;

void f1(int a[], int size)    //A user-defined function which takes an 'int array'  as arguments
{
  for(int i=0;i<size;i++)
 {
   cout<<a[i]<<endl;
 }

}

int main()
{
    int ar[]={1,2,3,4,5,6,7,8,9,10,11};
    f1(ar,7);    //passing array name and no. of elements(less than actual) to be displayed as args
    f1(ar,11);   //passing array name and no. of elements(equal to actual) to be displayed as args
    f1(ar,15);   //passing array name and no. of elements(more than actual) to be displayed as args
    return 0;
}

Sacred Thought

28 April 2024 Today I am going to explain verse 31 - 38 chapter two for you all. There is no opportunity better than a righteous war (सत्य औ...