Pages

Wednesday, December 2, 2009

Creating a function

Creating a user defined function
To create a user defined function we have to carry out three basic tasks.
1. Prototype the function (declaration) : Just like a variable a function must also be declared prior to its use. The term “prototyping” is more used instead of the term “declaring”. To prototype the function the following syntax is used returntype functionname(args);
Example : void func1();void test();int square();float interest();
2. Define the function (Function body) : Declaration just tells the compiler about the name, arguments and return value of the function, what it doesn’t tell is what the function will do. The function definition or the function body tells what the function will do.
3. Call the function (Execution) : To see how a function works it must be called explicitly from the program. If we fail to call it we won’t be able to see its output. Therefore it is compulsory to call the function to see it working


Example 1 : Function to print a “Hello World” message.
void main()
{
void hello(); // function prototype
hello(); // function calling
printf(“\nEnd of the program”);

}
void hello() // function definition

{
printf(“Hello World”);
}
Output

Hello World
Description
The statement “void hello()” declares the function. The declaration part starts with the keyword “void” which tells the compiler that the function will not return any kind of value. Some functions do return a value and therefore do not start with “void”. “hello” is the function name which can be any valid name. The rules of naming a function are quite same as those of naming a variable – it shouldn’t contain any space, no symbol is allowed except an underscore, shold begin with a letter or underscore. After prototyping the function the next statement “hello()” calls the function. When the compiler reaches the function call it searches for the function definition which is given at the end of the main(). The body contains just one statement which is “printf(“Hello World”)”. This message is printed and the control moves back to main() which prints “End of the program”.

Note that the main() contains a call to the hello(). Therefore in this example main() will be called the “calling function” and the function which is being called (hello – in this example) will be called the “called function”. After the call to the calling function is complete the control returns to the calling function. A called function cannot close the program. One question which arises here is – if main() is calling hello(), who is calling main() ? the answer is “the compiler or the C software” . the compiler is preprogrammed to search for the main() and start its execution from there. Once the execution of main() begins, it the main() which decides what next to do. In this example main() decides to call hello() apart from printing the message “End of the program”.

Example 2 : Finding out greater number using functions


Keep in mind that functions do not teach a new logic to create a program or solve a problem rather they teach you a different approach towards it. Therefore if you want to create a program using functions the basic logic of the problem will remain same the only thing that will change is that we will divide the program into small functions



void main()


{


void great();//prototype


great(); // function call 1


printf(“\nOther code between the two function calls”);


great();// function call 2


}


void great()


{


int a,b;


printf(“\nEnter any value : “);


scanf(“%d”,&a);


printf(“\nEnter second value : “);


scanf(“%d”,&b);


if(a>b)


                printf(“\nFirst number is greater “);


else if(b>a)


                   printf(“\nSecond number is greater”);


else


                printf(“\nBoth the numbers are equal”);


}

Output

Enter first value : 230


Enter second value : 401


Second number is greater

Description

As you can see there is nothing new inside the function definition. It contains a basic if – else comparison to find out the greater number. So why are we creating a function for it ? The reason has already been explained in the introduction that now if we want to do the same comparison again for another pair of values we don’t need to write the code again. We can just call the function as many times as we want. But can’t it be done using a loop ? yes, of course. But remember that a loop runs continuously without interruption whereas a function is called as and when required. Therefore we can easily do some other tasks between two function calls which we can’t with a loop. Take a look at the next example for more information.



Example 3 : Write a program to first find out the square of a number, then cube of a number and again square of a new number.



Solution

Method 1 : Without using a function or a loop.



void main()


{


int num,square,cube;


printf(“\nEnter the number whose square is to be found : “);


scanf(“%d”,&num);


square=num*num;


printf(“\nSquare is %d”,square);


printf(“\nEnter the number whose cube is to be found : “);


scanf(“%d”,&num);


cube=num*num*num;


printf(“\nCube is %d”,cube);






printf(“\nEnter the number whose square is to be found : “);


scanf(“%d”,&num);


square=num*num;


printf(“\nSquare is %d”,square);


}



Description

The program will ask the user to enter a value and after printing its square will ask the user to enter another value for cube. Once the cube is also printed the program will once again ask for another value to determine the square. The problem ? We are writing the same code of calculating the square twice leading to wastage in terms of memory, time and effort. Let’s see if a loop can provide a solution



Method 2 : Using a loop



void main()

{


int num,square,cube,i;


for(i=0;i<2;i++)


{


printf(“\nEnter the number whose square is to be found : “);


scanf(“%d”,&num);


square=num*num;


printf(“\nSquare is %d”,square);


}


printf(“\nEnter the number whose cube is to be found : “);


scanf(“%d”,&num);


cube=num*num*num;


printf(“\nCube is %d”,cube);


}

Discussion

if you compare both the above methods, you can easily see that the second method is quite short when compared to the first method. So have we found a solution to the problem without having to create a function ? Not exactly. if you can recall the problem wanted the following sequence of events – square, cube and again square. The first method(without loop) though lengthy is following the sequence but the second method is not at all following the correct sequence of events. It will process the result as square,square,cube which is not at all required. Therefore it can be concluded that the first method is lengthy while the second method is not processing the result it the correct sequence. Enter Functions and both the problems will be solved. The program will not only be short but also in correct sequence.



Method 3 : Using functions

void main()


{


void square();


void cube();


square();


cube();


square();


}


void square()


{


int num,square,cube;


printf(“\nEnter the number whose square is to be found : “);


scanf(“%d”,&num);


square=num*num;


printf(“\nSquare is %d”,square


}


void cube()


{


int num,cube;


printf(“\nEnter the number whose cube is to be found : “);


scanf(“%d”,&num);


cube=num*num*num;


printf(“\nCube is %d”,cube);


}



Description

Inside main() first we have called the square() which will print the square followed by the calling of cube. To calculate square again all we have to do is to call it again. As compared to the above two methods we didn’t have to write the code twice and even the sequence is correct.

0 comments:

Post a Comment