Friday, March 27, 2009

What is formal & Actual parameter along with examples

Often in Interviews we are prompted with question what is formal & actual parameter & explain difference in btw:-

Ok here we go ,

What are Formal Parameters ?

Ans:-

*Formal Parameter*
1)Consider y = f(x) // where x is independent & value of y is dependent on value returned by f.Here f(x) is formal parameter or argument to f

2)Formal parameters are place holders for values of "Actual parameter"

3)Formal parameters are declared/defined during function definition.

4)Examples :-

A)int f ( int x) --> x is formal paremter
B)int miles ( int km ,int mileage) --> km & mileage are formal parameter

5)In short in laymen language any fun. parameter that comes outside parenthesis is Formal parameter


*Actual parameter

1)In C prg. values that appears inside the parentheses are called "Actual Parameter"

2)Formal parameters must match in position,number & type

3)When a function call is made,a memory location is allocated for each formal parameter & a copy of corresponding actual parameter is kept in that memory location. All calculations involving the formal parameter use this memory location.

4)Actual parameters are always "Passed" & variables that are declared & passed as arguments to procedure by caller

5)Examples :-

A)#define MILEAGE 25 // Here MILEAGE is actual parameter
B)int miles(int gallons, int mileage) is Formal parameter

Consider following example:-
Problem:- Accepts a number of gallons as input from end user and calculates & displays the number of miles that can be traveled

#include
#define MILEAGE 25
int miles(int gallons,int mileage); // -->Both gallons & mileage are formal parameters

int main(void)
{
int f ; // --> f is actual parameter & f stores value in Gallons
printf("Enter number of Gallons of Gas : ");
scanf("%d",&f);
printf("\nYou will be able to travel %d miles from %d Gallons of Gasoline",miles(f,MILEAGE),f);/* here f & MILEAGE are actual parameters whose values are stored into gallons & mileage respectively which are formal parameters*/
return 0;
}

int miles(int gallons,int mileage)
{
return ( gallons * mileage); //Here both are formal parameters ie: gallons & mileage
}

*** Above example and some logic was taken from C by discovery by Foster & Foster

No comments: