Pages

Wednesday, December 16, 2009

Local and global variables

According to the declaration, variables can be of two types – local and global. The variable which are declared inside a function are called “local” variables which those variables that are defined outside a function are called “global” variables.

Local variables
Any variable which has been declared inside a function is called its local variable. The name local denotes that the variable is accessible from within the function it which it is declared. It cannot be used from outside the function. Local variables are also called “private” variables since they are kind of “private property” of a function. We can declare many variables with the same name provided that all of them are declared in different functions.



Example 1 : Working of a local variable


void main()


{


int local=10;


void display();


display();


printf(“\nvalue is %d”,local);


}


void display()


{


int local=20;


printf(“\nvalue is %d”,local);


}


Output


value is 20


value is 10


Description


As you can see we have declared a variable named “local” both in the main() and in display(). The “local” variable declared inside main() has the value 10 while the one declared in display() as the value 20. When the function is called the value 20 is printed first and then 10 is printed. It is quite clear that both the functions are displaying their own value of the variable.





Example 2 : Understanding the function of a local variable






void main()


{


void calculate();


int data;


data=1000;


calculate();


printf(“\nIn main data is %d”,data);


}


void calculate()


{


int data;


data=2000;


printf(“\nIn calculate data is %d”,data);


data+=1000;


}






Output


In calculate data is 2000


In main data is 1000


Description


There are two local variables named “data” each in main () and data(). Before printing the value of data of main, the function is called. Inside calculate () there is another variable with the name “data” which has a value of 2000. After printing 2000 the value is incremented by 1000 making it 3000 but since there is no printf() after it, we won’t see 3000 printed on the screen. After returning to main() , the value of data which was available in main() which is 1000 is printed. The increment has no effect in the main since there are two “data” variables. The “data” of calculate() will be incremented and not the one declared in main()





Example 3 : Local variables and multiple functions






void main()


{


void fun1();


int value=1;


fun1();


value=value+1;


printf(“\nIn main value is %d”,value);


}






void fun1()


{


int value=2;


void fun2();


fun2(); //calling fun2


value=value-1;


printf(“\nIn fun 1 value is %d”,value);


}


void fun2()


{


void fun3();


int value=3;


printf(“\nIn fun2 value is %d”,value);


fun3(); //calling fun3


}


void fun3()


{


int value=4;


printf(“\nIn fun 3 value is %d”,value);


value=value+1;


}






Output


In fun2 value is 3


In fun 3 value is 4


In fun 1 value is 1


In main value is 2










Description


The above program has four function (main(),fun1(),fun2() and fun3()) . All of these functions have a declaration of the variable “value”. Since each function has declared a variable with the same name, there are four different variables with the same name “value”. The compiler starts processing from main() where main declares “its” value variable with the value 1,but before it can get printed the function fun1() is called. The compiler leaves the main() midway and goes to fun1() where another variable “value” is declared with a value of 2. fun1() contains a call to fun2() so the compiler goes on to call fun2(). The printf() inside fun2() is the first value to be printed which is 3 after which the compiler moves to fun3(). The variable declared inside fun3() has the value 4, this is the second value to be printed. After printing 4 the value is incremented by 1. But since there is no printf() after than 4 is not printed. When fun4() has finished its processing the control returns to the calling function which is fun3(). Now that the processing of fun3() is also finished the program returns to the calling function of fun3() which is fun2(). Inside fun2 the value is decremented by 1, remember that all the declarations are local therefore the decrement will take place on the value declared inside fun1() which is 2. After decrementing the result is printed therefore 1 is the next value to be printed. When fun1 () is also finished the controls move to main() since it called fun1() where again 2 is printed which was the local value of the variable.



Global Variables


Variables which are does not fall under a particular function are called global variables. Such variables are declared outside a function scope. Sometimes all referred to as public variables, global variables are accessible from any function within a program.


Example 1 : Using a global variable


int points=10


void main()


{


void show();


printf(“\nPoints in main %d”,points);


points+=10;


show();


}


void show()


{


printf (“Points In show %d”, points);


}


Output


Points in main 10


Points in show 10


Description


The above example declares a variable above “main ()” named points. Since “points” is declared outside main () or any other function it is not a local variable of any function. The value of points is first printed inside main then the value is incremented by 10 making it 20. When the show () is called it will print the incremented value which is 20. As you can see the value of points is shared by both main () and show () and if it is modified in one function the change can be seen in the other function.






Example 2: Declaring a local and a global variable with the same name.






int sample=100; // Global Variable


void main ()


{


int sample=200; // Local Variable


printf(“\nLocal variable %d”,sample);


printf(“\nGlobal variable %d”,::sample); // printed using double colons ( : : )


}


Output


Local variable 200


Global variable 100


Description

If a program has both local and global variable with the same name, then by default the value of the local variable will be processed. If we want to print the global variable then we must prefix the variable name with the symbol :: , called the scope resolution operator. This operator will help the compiler differentiate between the local and the global variable. The scope resolution operator is not required if both the names are different.

Return value

  • What is return value?


The value or output returned by a function is called return value. There are two ways a function can work, first is by printing the result itself within its own body and second is by returning the result to the calling function. Those functions which return a value are called functions with return value.

  • Types of functions on the basis of return value

As discussed in previous posts functions can be categorized according to different criteria like on the basis of declaration the functions are divided as library functions and user defined functions. Another criteria is on the basis of arguments, again we have two varieties, function with arguments and functions without arguments. Similarly we can divide functions on the basis of return value also.

a) functions without return value: functions which do not return a value are called functions without return value. Such functions work by printing the final output themselves. functions like printf(),scanf(),clrscr() are functions without a return value.

b) functions with return value: Although functions without return value are quite capable, there may be some conditions where a return value will be needed. In such a scenario we will have to create a function with return value. Such functions instead of managing the output themselves return the output to the calling function, letting the calling function decide what to do with the output. The calling function can print the value as it is or it can use this value for further processing. Library functions like strcmp(), strlen() are some of the examples of this type.

  • Why do we need return value functions?

Whenever a function is called it is not necessary that the output the function has achieved is the final result. Sometime it can happen that the output is an “intermediate” output and not the final output. Such intermediate output can be sent back to the calling function for final decision. The calling function will have the final say in deciding what to do with the value it has received from the called function. It can print the value as it is or can keep the value for any future processing.

  • How to distinguish between functions with and without return value?

It is quite easy to tell whether a function is returning value or not by looking at its declaration. All the functions which do not return a value are declared using the keyword “void” which means null or nothing. if a function starts with “void” then it is a kind of signal to the compiler that it won’t be returning any value. On the other hand functions that return a value do not start with void instead they have the datatype written in place of void. The datatype will obviously depend on the type of value the function is returning like int or float.



Syntax – functions without return type

void funname()


{


function body;


}



Syntax – functions with return value

datatype funname()


{


function body;


return value;


}

Note that the first declaration starts with the keyword “void” which means that function will not return a value.





Example 1 : Basic return value program

void main()


{


int show(int);


int a,b;


printf(“\nEnter a value “);


scanf(“%d”,&a);


b=show(a);


printf(“\nreturned value is %d”,b);


}


int show(int x)


{


x+=10;


return x;


}



Output

Enter a value 20


returned value is 30



Description

The first line declares a function using the statement “int show(int”). the “int” before show() denotes that the function will return an integer value while the “int” written as argument denotes that the function will take an integer as input. We can also say that the function show will take an integer as input and will return another integer as output. Since the function is declared with an integer value we must declare an extra variable that will handle the returned value. The statement “b=show (a)” denotes that the function will be passed the value of “a” as argument and the value returned by the function will be stored in the variable “b”. When the function is called the value of “a” is passed to “x”, show() increments the value by 10 and returns the incremented value to the calling function which is main(). The returned value (30) is stored in b and this value is then printed.

Example 2 : Program to print cube of the square of a number.




In the following program we want the user to enter a number and the program will calculate the cube of the square of the number. For example if the user enters 2 the value 64 will be printed since 64 is the cube of 4 which is the square of 2.

No. -->  Square --> Cube of square

2 --> 4 -->  64



void main()


{


int square(int);


void cube(int);


int num,sq;


printf(“\nEnter any numeric value “);


scanf(“%d”,&num);


sq=square(num);


cube(sq);


sq=square(4);


printf(“\nSquare of 4 is %d”,sq);


}


int square(int n)


{


int s=n*n;


return (s);


}


void square(int n)


{


int c=n*n*n;


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


}



Output

Enter any numeric value 2


Square is 64


Square is 16



Description

The value entered by the user is passed as an argument to the function square. Square calculates the square of that number but instead of printing the result returns it to main. main() stores this value in the variable “sq”. Since this is not the final output it is sent to cube() to calculate cube. The second time when square is called we don’t want to print the cube of its square. Therefore when square returns the square of 4 it is again stored in sq and printed as it is.



Example 3 : returning a character value.



void main()


{


char showgrade(int);


char gr;


int salary;


printf(“\nEnter your basic salary “);


scanf(“%d”,&salary);


gr=showgrade(salary);


printf(“\nGrade according to the salary is %c”,gr);


}


char showgrade(int sal)


{


char g;


if(sal>=1 && sal<1000)


g=’D’;


else if(sal>=1000 && sal<5000)


g=’C’;


else if(sal>=5000 && sal<10000)


g=’B’;


else if (sal>=10000)


g=’A’;


return (g);


}



Output

Enter your basic salary 4500


Grade according to the salary is B

Description

The function prototype “char showgrade(int)” signifies that the function will return a char value while the argument is of integer type. When the salary is passed as argument the showgrade() will return the grade of the employee as per the salary entered. The returned value is copied to the variable “gr” in main where it is printed. You can also call the function by a statement like “showgrade(2300)” since 2300 is also an integer value.



Example 4: returning a float value

void main()


{


float bankloan(char);


char type;


float interest;


printf(“\nH. Home Loan”);


printf(“\nE. Education Loan”);


printf(“\nP. Personal Loan”);


printf(“\nSelect a loan type (H,E,P) : “);


scanf(“%c”,&type);


interest=bankloan(type);


if (interest==0)


printf(“\nInvalid loan type selected”);


else


printf(“\ninterest rate of this category is %f”,interest);


}


float bankloan(char ty)


{


float roi; // rate of interest


if (ty==’H’  || ty==’h’)


roi=8.5;


else if (ty==’E’  || ty==’e’)


roi=11.25;


else if (ty==’P’  || ty==’p’)


roi=12.75;


else


return 0;


return roi;


}

Output

H. Home Loan


E. Education Loan


P. Personal Loan


Select a loan type (H,E,P) : P


Interest rate of this category is 12.75



Description

The above function has a return value of float while the input value of char. The user selects a type of loan from the given menu (H for home, E for education and P for personal). The function checks the loan type and accordingly returns the interest applicable on it. The return value is sent to the variable “interest” and then printed. if the user enters an invalid choice the function returns 0 and “Invalid loan type selected” message is printed.

Monday, December 7, 2009

Function with arguments

What are arguments ?
Functions can also be categorized on the basis of arguments. Argument or parameter is the value that we pass to a function while calling it. for example while calling the printf(), we always the message that we want to print on the screen, like printf(“Hi there !!”). The value or message written inside the circular brackets is called the argument. Of course, not all functions accept values inside like clrscr(),getch() etc. such functions are called functions without arguments.


Why do we need arguments?

Imagine a program that wants to perform addition,subtraction,product and division on a single pair of values. if we create four different functions for this purpose one each for addition, subtraction and product, we will have to write the code to get the input from the user in each function since we cannot pass values from a function to another. Consider the following example

void main()


{


void add();


void product();


void subtraction();


void division();


add();


product();


subtraction();


division();


}


void add()


{


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);


c=a+b;


printf(“\nAddition is %d”,c);


}


void subtraction()


{


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);


c=a-b;


printf(“\nSubtraction is %d”,c);


}


void product()


{


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);


c=a*b;


printf(“\nProduct is %d”,c);


}


void division()


{


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);


c=a/b;


printf(“\nDivison is %d”,c);


}



As you can see, we have to take input in each function causing the program to lengthen. We cannot move the values of “a” and “b” from one function to another since they are all local variables. The solution to this problem is the use of arguments. Arguments or parameters can be moved to another function so that we don’t have to input the values again and again.

Example : Using arguments


void main()

{


void add(int,int);


void product(int,int);


void subtraction(int,int);


void division(int,int);


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);






add(a,b);


product(a,b);


subtraction(a,b);


division(a,b);


}


void add(int a,int b)


{


int c;


c=a+b;


printf(“\nAddition is %d”,c);


}


void subtraction(int x,int y)


{


int z;


z=x-y;


printf(“\nSubtraction is %d”,z);


}


void product(int i,int j)


{


int k;


k=i*j;


printf(“\nProduct is %d”,k);


}


void division(int m,int n)


{


int o;


o=m/n;


printf(“\nDivison is %d”,o);


}

Description

After accepting values from the user and saving them in a and b the first call is made to the add(). Notice that inside the circular brackets the values a and b are written (a ,b). This is called passing arguments to a function – in this case a and b are arguments while “add” is the name of the function. When the compiler sees that a call is made to add() it will copy the values of a and b defined in main() to the arguments a and b given in the definition of add(). Which means that the value of a will be copied to a and b will be copied to b. inside the add (), c will add both the values and the result is printed. After this the second function subtraction is called using the same arguments (a and b) but this time their value are copied to x and y which are defined in the subtraction () definition. Similarly values of and b are copied to I and j in product() and to m and n in division. The main benefit of using arguments in this program is that we don’t have to ask the user to enter values in all the functions. The values have been entered just once and are copied to all the functions using arguments.

Points to remember

1. The argument given while calling the function is called actual arguments, while the arguments given in the function definition are called formal arguments.

2. The names of the formal and actual arguments can be same or different.





Example : Calculating area of circle using functions with arguments






void main()


{


clrscr(); // to clear all previous messages on the screen (optional)


void area(int r); // prototyping the function with the name area and one integer arg.


int radius;


printf(“\nEnter Radius Of The Circle : “);


scanf(“%d”,&radius);


area(radius);//calling the function with user defined radius as argument


area(4); // calling the function with a constant


}


void area(int rad)// the value of radius will be copied to rad


{


float ar;


ar=3.14*r*r; // calculating area of circle using the formula pi * radius * radius


printf(“\nArea of circle is %f”,ar);


}



Description

As you can see the function is declared to accept an integer value as argument and therefore must be given while calling it. Before calling the function for the first time, the user is prompted to enter a value as radius. After this the function is called with the statement “area(radius)”. At this point the value of the actual argument “radius” is copied to the formal argument “rad” declared in the function definition. The area function calculates the area using the mathematical formula “3.14*radius*radius”. When the area is printed the control returns to the calling function (which is main()) which again calls the function with a constant value of 4. Please note that the function need an integer value to run. Whether this value is being provided by the user as in the first case or if it is a fixed value like in the second case is immaterial. The function definition does not care how the argument is passed – by the user or as a fixed value – as long as the method of passing the value is correct.



Example : Calling a function with arguments passed in four ways



void main()


{


void si(int,float,float);


int p;


float r,t;


printf(“\nEnter Principle Amount : “);


scanf(“%d”,&p);


printf(“\nEnter Rate Of Interest : “);


scanf(“%f”,&r);


printf(“\nEnter Time Duration : “);


scanf(“%f”,&t);


si(p,r,t);// function call with user values


si(4000,5.3,3.2); // function call with constant values


si(p,6.4,4);// calling the function with a user defined value and two constants


si(4000+2000,r,t*3); // calling the function with different type of arguments.


}






void si(int princ,float rate,float time)


{


float s=(princ*rate*time)/100;


printf(“\nSimple Interest is %f”,s);


}



Description

In this example a function named “si” is declared to calculate simple interest. The function has three arguments one integer and two floats. The function has been called four time 1) With the values entered by the user 2) With fixed values 3) With a combination of user entered values and constants 4) With a formula result, user entered values and again a formula result.

As exaplained earlier the function has nothing to do with the way the arguments are passed to it. It will only check whether the number of arguments is correct and whether the datatype of arguments is matching or not. If these things are correct it will calulcate and print the result.

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.

Functions

In our day to day life we depend on several individuals to us in our daily activities. Like we depend on the plumber to fix the taps and pipes, carpenter to mend our furniture etc. we cannot perform all these tasks alone so we need the help and support of these persons. When we need their services we call them, they visit our place, perform the tasks and leave. Similarly in a program all the tasks cannot be performed by a single function or code. We’ll require many small programs to carry out the various tasks for us. These small programs are called functions.
By definition, function is “a small program that has a name and a particular task”. Of course, there are many predefined functions in C but since the requirements vary from user to user we cannot have a predefined function for every occasion. Therefore we need to create our own functions called “User Defined Functions”. A user defined function or UDF is a function created by the user as per his/her requirements.

Types of functions on the basis of declaration

On the basis of declaration we can divide functions in two categories

  1. Library functions : Those function which come precompiled in the language are called library functions or inbuilt functions. All such kind of functions is declared in some header files which must be included prior to calling these functions. For example the library function strcmp() is defined in the header file string.h, clrscr() in conio.h and isalpha() in ctype.h. The user is not required to create these functions as they are already declared in their respective header files.
    Examples : printf(),scanf(),strcmp(),strcpy(),clrscr(),getch() etc.
  2. User defined function: Functions which are declared by the user as per his/her need are called user defined functions. Since they are not pre-defined the user to provide all the definition to make it work. There can be no specific example of a user defined function since it depends on the user requirements.
Advantages of functions

1.
Functions encourage the concept of modular programming where a large problem is divided into small manageable chunks. These small parts are easy to understand and debug than a large problem.
2. One of the biggest advantages of a function is its reusability. A function once declared can be used again and again without having to retype the whole code.
3. Reusability in turn offers many other benefits like saving on resources. If a function can be called multiple times it saves both primary and secondary memory.
4. The time taken in compiling the code is also reduced since a function will be compiled just once irrespective of how many times it is being called.
5. Functions are tested for errors only once. Once the errors are removed we can call it as many times as we want.