Top Ad unit 728 × 90

What is function ?

 What is function ?

A function is a self-contained block of statements that perform a coherent task of some kind. Let us now look at a simple program that introduces us to the idea of a function 

#inckude<stdio.h>
void message(); /*function prototype declaration */
int main( )
{
      message(); /* function call */
      printf("Cry, and you stop the monotony!\n");
      return 0;
}
void message() /* function definition */
{
     printf("Smile, and the world smiles with you....\n");
}

And here's the output.....

Smile, and the world smiles with you....
Cry, and you stop the monotony!

Here, we have defined two functions---main() and message (). In fact, we have used the word message at three places in the program. Let us understand the meaning of each.

The first is the function prototype declaration and is written as:

void message( )

This prototype declaration indicates that message( ) is a function which after completing its executed does not return any value. This 'does not return any value' is indicated using the keyword  void.  It is necessary to declare the prototype of every function that we intend to define in the program.

The second usage of message is.....
void message( )
{
      printf("Smile, and the world smiles with you...\n");
}

This is the function definition. In this definition right now we are having only printf( ). but we can also use if, for, while, switch, etc., within it.

The third usage is....
message ( );
Here the function message( ) is being called by main( ). When we call the  message( ) function, control passes to the function message( ). The activity of main( ) is temporarily suspended; it falls asleep while the message ( ), function wakes up and goes to work. When the message( ) function runs out of statements to execute, the control returns to main( ), which comes to life again and begins executing its code at the exact point where it left off. Thus, main( ) becomes the 'calling ' function, whereas message( ) becomes the 'called' function.

If you have grasped the concept of 'calling ' a function, you are prepared for a call to more than one function. Consider the following example:

#include<stdio.h>
void italy( );
void brazil( );
void argentina( );
int main ( )
{
      printf("I an in main \n");
      italy( );
      brazil( );
      argentina( );
      return 0;
}
void italy ( )
{
      printf("I am in italy \n");
{
void brazil( )
{
      printf("I am in brazil \n");
}
void argentina( )
{
       printf("I am in argentina \n");
}

The output of the above program when executed would be as under:

I am in main
I am in italy
I am in brazil
I am in argentina 

A number of conclusions can be drawn from this program:
─      A C program is a collection of one or more functions.
─      If a C program contains only one function, it must be main ( ).
─      If a C program contains more than one function, then one (and only one ) of these
         functions must be main( ).

─      Each function in a program is called in the sequence specified by the function calls
         in main( ). 

─      After each function has done its thing, control returns to main( ). When main( ) runs
        out of statements and function calls, the program ends.

Given below are a few additional tips about functions.
  1. program execution always begins with main( ). Except for this fact, all  C functions enjoy a state of perfect equality. No precedence, no priorities, nobody is nobody's boss.
  2. Since program execution always begins with main( ), every function gets called directly or indirectly from main( ). In other words, the main( ) function drives other functions.
  3. Any function can be called from any other function. Even main( ) can be called from other functions.
  4. A function can be called multiple times.
  5. The order in which the functions are defined in a program and the order in which they get called need not necessarily be same. However , it is advisable to define the functions in the same order in which they are called. This makes the program easier to understand.
  6. A function cannot be defined in another function. Thus, the following program would be wrong since argentina( ) is being defined inside another function, main( ):  
         int main( )
         {
               printf (" I am in main \n");
               void argentian ( )
              { 
                 printf (" I am in argentina \n" );
              }
         }
   
       7. There are basically two types of functions:

            Library functions Ex. printf(), scanf(), etc.
            User-defined functions Ex. argentina(), brazil(), etc.

            Library functions are a collection of commonly required functions grouped together
            and stored in a Library file on the disk. This library of functions comes ready-made
            with development environments like Turbo C, Visual Studio, GCC, etc. The
            procedure for calling both types of  functions is exactly same.

Why use Functions?


Why write separate functions at all? Why not squeeze the entire logic into one function, main()? Well, for two reasons given below.

(a). Writing functions avoids rewriting the same code over and over and promotes code reuse. Suppose you have statements in your program that calculate area of a triangle. If later in the program, you want to calculate the area of a different triangle, it would be improper to write the same instructions again. Instead, you would prefer to jump to a function that calculates area and then jump back to the place from where you left off.

(b).  If the operation of a program can be divided into separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code into modular functions also makes the program easier to
design and understand.

So, don't try to cram the entire logic in one function. Instead, break a program into small units and write functions for each of these isolated subdivisions. Don't hesitate to write functions that are called only once. What is important is that these functions perform some logically isolated tasks.

Communication between Functions


The functions that we have used so far weren't very flexible. We called them and they did what they were designed to do. Now we wish to communicate between the 'calling' and the 'called' functions.

Communication between functions is facilitated by arguments and return values. You have unknowingly used the arguments in the printf() and scanf() functions-the format string and the list of variables used inside the parentheses in these functions are arguments. The arguments are also called parameters.

Consider the following program. In this program, in main() we receive the values of a, b and c through the keyboard and then output their sum. However, sum is calculated in the function calsum(). So the values of a, b and c must be passed to calsum(). Similarly, once the sum is calculated it must be returned back to main(). That's communication in short.

 /* Sending and receiving values between functions */
 #include <stdio.h>
 int calsum (int x, int y, int z);
 int main()
 {
      int a, b, c, sum;
      printf("Enter any three numbers ");
      scanf("%d %d %d", &a, &b, &c); 
      sum = calsum (a, b, c); 
      printf("Sum = %d\n", sum);
      return 0;
 }
 int calsum (int x, int y, int z)
 {
      int d;
      d=x+y+z;
      return 0;
 } 

And here is the output of the program...

Enter any three numbers 10 20 30
Sum=60

There are a number of things to note about this program:

(a).  The values of a, b and c are passed from main() to calsum() by mentioning a, b and c in the parentheses while making the call.

sum=calsum (a, b, c);

In calsum() these values are collected in three variables x, y and z:

int calsum (int x, int y, int z)

Passing values of a, b, c is necessary, because variables are available only to the statements of a function in which they are defined.

(b).  The variables a, b and c are called 'actual arguments', whereas the variables x, y and z are called 'formal arguments'. The type, order and number of the actual and formal arguments must always be same.

Instead of x, y and z, we could have used the same variable names a, b and c. But the compiler would still treat them as different variables since they are in different functions.

(c).  Note the function prototype declaration of calsum(). Instead of the usual void, we are using int. This indicates that calsum() is going to return a value of the type int. It is not compulsory to use variable names in the prototype declaration. Hence, we could have written the prototype as:

int calsum (int, int, int);

In the definition of calsum too, void has been replaced by int.

(d).  In the earlier programs, the moment closing brace (}) of the called function was encountered, the control returned to the calling function. No separate return statement was necessary to send back the control.

his approach is fine if the called function is not going to return any meaningful value to the calling function. In our program, however, we want to return the sum. Therefore, it is necessary to use the return statement. It serves two purposes:

(1) It transfers the control back to the calling function.

(2) It returns the value present in the parentheses (d in our program) after return, to the calling function.

(e).  There is no restriction on the number of return statements that may be present in a function. Also, the return statement need not always be present at the end of the called function. The following function illustrates these facts:

int fun(int n)
{
      if(n<=10)
          return (n*n);
     else
          return (n*n*n);
}

In this function, different return statements would be executed depending on value of n.

(f).  When control returns from calsum( ), the returned value is collected in the variable sum through the statement

Sum=calsum (a, b, c):

(g). All the following are valid return statements.

return (a); /* or return a; */ 
return (23); /* or return 23: */
return;

In the last statement, only control is returned to the calling function. Note that, the parentheses after return are optional.

(h).  A function can return only one value at a time. Thus, the following statements are invalid:

return(a, b);
return (x, 12):

(i). If the value of a formal argument is changed in the called function, the corresponding change does not take place in the calling function. For example,

#include <stdio.h> 
void fun (int);
 int main()
{
     int a = 30; 
     printf("%d\n", a);
     fun (a);
     return 0;
}
void fun ( int b)
{
     b= 60;
     printf("%d\n", b);
}

The output of the above program would be:
60
30

Thus, even though the value of b is changed in fun(), the value of a in main() remains unchanged. This means that when values are passed to a called function, copies of values in actual arguments are made into formal arguments.

Order of Passing Arguments

Consider the following function call:

fun (a, b, c, d);

In this call, it doesn't matter whether the arguments are passed from left to right or from right to left. However, in some function calls, the order of passing arguments becomes an important consideration. For example:

int a = 1;
printf("%d %d %d\n", a, ++a, a++);

It appears that this printf() would output 1 2 2.

This however is not the case. Surprisingly, it outputs 3 3 1. This is because, during a function call, the arguments are passed from right to left. That is, firstly 1 is passed through the expression a++ and then a is incremented to 2. Then result of ++a is passed. That is, a is incremented to 3 and then passed. Finally, latest value of a, i.e., 3, is passed. Thus, in right to left order, 1, 3, 3 get passed. Once printf() collects them, it prints them in the order in which we have asked it to get them printed (and not the order in which they were passed). Thus 3 3 1 gets printed.

It is important to note that the order of passing arguments to a function is not specified by the language, and hence is compiler-dependent. Consequently, any code that is written disregarding this is bound to show unpredictable behavior. For instance, the printf() example in question may give different outputs with different compilers.


Using Library Functions

Consider the following program:

#include <stdio.h>
#include <math.h>
int main()
{
     float a = 0.5;
     float W, X, Y, Z;
     w = sin (a);
     x = cos(a);
     y = tan (a);
     z = pow ( a, 2);
    printf("%f %f %f %f\n", w, x, y, z); 
    return 0;
}

Here we have called four standard library functions-sin(), cos(), tan() and pow(). As we know, before calling any function, we must declare its prototype. This helps the compiler in checking whether the values being passed and returned are as per the prototype declaration. But since we didn't define the library functions (we merely called them), we do not know the prototype declarations of library functions. Hence, along with library functions a set of 'h' files are also provided. These header files contain the prototype declarations of library functions.

Library functions are divided into different groups and one header file is provided for each group. For example, prototypes of all input/output functions are provided in the file 'stdio.h', prototypes of all mathematical functions (like sin(), cos(), tan() and pow()) are provided in the file 'math.h', etc. If you open the header file 'math.h', the prototypes would appear as shown below.

double sin (double);
double cos(double);
double tan (double);
double pow(double, double);

Here double indicates a real number.

Whenever we wish to call any library function, we must include the header file that contains its prototype declaration.

One Dicey Issue

Now consider the following program:

#include <stdio.h>
int main()
{
       int i-10, J=20;
       printf("%d %d %d\n", i,j);
       print("%d\n",i,j);
       return 0;
{

This program gets successfully compiled, even though there is a mismatch in the format specifiers and the variables in the list used in printf(). This is because, printf() accepts variable number of arguments -sometimes 2 arguments, sometimes 3 arguments, etc. Hence, even with the mismatch above, the call still matches with the prototype of printf() present in 'stdio.h'. At run-time, when the first printf() is executed, since there is no variable matching with the last specifier %d, a garbage integer gets printed. Similarly, in the second printf(), since the format specifier for j has not been mentioned, its value does not get printed.

Return Type of Function

Suppose we want to obtain square of a floating-point number using a function. This can be achieved through a simple program shown below.

#include <stdio.h> 
float square (float); 
int main()
{
       float a, b:
       printf("Enter any number "); 
       scanf("%f",&a); 
       printf("Square of %f is %\n", a, b);
       b = square (a);
       return 0;
}
float square (float x)
{
    float y
    y=x*x;
    return (y);
 }

And here are three sample runs of this program...

Enter any number 3
Square of 3 is 9.000000
Enter any number 1.5 Enter any number 2.5
Square of 1.5 is 2.250000
Square of 2.5 is 6.250000

Since we are returning a float value from this function, we have indicated the return type of the square() function as float in the prototype declaration as well as in the function definition. Had we dropped float from the prototype and the definition, the compiler would have assumed that square() is supposed to return an integer value. This is because, default return type of any function is int.


Question :- Write a function to calculate the factorial value of any integer entered through the keyboard.

program:
  
/* Calculate factorial value of an integer using a function */ #include <stdio.h>

int fact (int);
int main()
{
       int num;
       int factorial;
       printf("\nEnter a number: ");
       scanf("%d", &num); 
       printf("Factorial of %d %ld\n", num, factorial);  
       return 0;
}
int fact (int num)
{
         int i;
         int factorial = 1;
         for (i=1;i<=num; i++) 
         factorial = factorial * ¡; 
         return (factorial);
}

Output:

Enter a number: 6
Factorial of 6 = 720







What is function ? Reviewed by For Learnig on September 17, 2023 Rating: 5

No comments:

If you have any doubts, please tell me know

Contact Form

Name

Email *

Message *

Powered by Blogger.