Pages

Friday, February 12, 2010

Creating multiple objects

Once we have created a structure we can declare as many objects as we want based on the structure. How many objects will be created solely depends how many records do you want to store. for example to maintain records/data of 20 doctors you can create 20 objects.

Method 1 : Creating individual objects

Example 2 : Storing multiple records

struct doctors
{
char name[20],qualification[10];
int exp,surgeries;
}
void main()
{
doctors doc1,doc2,doc3; // to store data of 3 doctors
printf(“\nEnter Details Of The First doctor “);
printf(“\nName : “);
gets(doc1.name); // to let the user enter spaces
printf(“\nQualification : “);
scanf(“%s”,&doc1.qualification);
printf(“\nExperience in years : “);
scanf(“%d”,&doc1.exp);
printf(“\nEnter surgeries performed : “);
scanf(“\n%d”,&doc1.surgeries);
printf(“\nEnter Details Of The Second doctor “);
printf(“\nName : “);
gets(doc2.name);
printf(“\nQualification : “);
scanf(“%s”,&doc2.qualification);
printf(“\nExperience in years : “);
scanf(“%d”,&doc2.exp);
printf(“\nEnter surgeries performed : “);
scanf(“\n%d”,&doc2.surgeries);
printf(“\nEnter Details Of The Third doctor “);
printf(“\nName : “);
gets(doc3.name);
printf(“\nQualification : “);
scanf(“%s”,&doc3.qualification);
printf(“\nExperience in years : “);
scanf(“%d”,&doc3.exp);
printf(“\nEnter surgeries performed : “);
scanf(“\n%d”,&doc3.surgeries);

printf(“\nList of doctors entered “);
printf(“\nDOCTOR 1”);
printf(“\nName of the doctor : %s”,doc1.name);
printf(“\nQualification : %s”,doc1.qualification);
printf(“\nExperience in years : %d”,doc1.exp);
printf(“\nSurgeries performed : %d”,doc1.surgeries);
printf(“\nDOCTOR 2”);
printf(“\nName of the doctor : %s”,doc2.name);
printf(“\nQualification : %s”,doc2.qualification);
printf(“\nExperience in years : %d”,doc2.exp);
printf(“\nSurgeries performed : %d”,doc2.surgeries);
printf(“\nDOCTOR 3”);
printf(“\nName of the doctor : %s”,doc3.name);
printf(“\nQualification : %s”,doc3.qualification);
printf(“\nExperience in years : %d”,doc3.exp);
printf(“\nSurgeries performed : %d”,doc3.surgeries);
}


 
Description
In the above code we have created three objects namely doc1,doc2 and doc3 to store data of 3 doctors. Each doctor has a name, qualification, experience and surgeries as their properties. To accept the data we have used multiple printf,scanf statements so that the records can be stored. When we use individual objects like doc1,doc2 etc. we will have to write many printf/scanf statements to input and output data. Of course, the program will work fine but won’t this method make it too lengthy if data of more doctors needed to be added.



Method 2 : Creating array object

Example 3 : Storing multiple records using an array object

struct doctors
{
char name[20],qualification[10];
int exp,surgeries;
}
void main()
{
doctors doc[5]; // an array of 5 doctors.
int I;
//Getting the input
for (i=0;i<5;i++) { printf(“\nEnter Name “); scanf(“%s”,&doc[i].name); printf(“\nEnter Qualification “); scanf(“%s”,&doc[i].qualification); printf(“\nEnter Experience “); scanf(“%d”,&doc[i].exp); printf(“\nEnter surgeries performed : “); scanf(“%d”,&doc[i].surgieries); } //Printing the output for(i=0;i<5;i++) { printf(“\nName : %s”,doc[i].name); printf(“\nQualification : %s”,doc[i].qualification); printf(“\nExperience : %d”,doc[i].experience); printf(“\nSurgeries : %d”,doc[i].surgeries); printf(“\n==========================”);// will act as a separator between 2 records. }


Description :The above code instead of creating individual objects creates an array of 5 objects. As far as memory is concerened creating an array of 5 objects will require the same amount of memory as 5 individual objects but the main benefit in creating the array is that the effort required in writing in printf/scanf statements has be largely reduced. The use of loop has made the program easier to write and not to mention has made it shorter.
When the statement “doc[5]” is compiled it creates an array of type “doctors”. Remember that a structure is a user defined data type therefore the array is capable of storing “name,qualification,expereicne and surgeries of doctor per index/element. It can be said that the array has a name,qualificaition, experience and surgeries variables in each of the 5 indexes. So the name of the first doctor is stored in index no [0], second doctor’s name is stored in index no[1] and so on. The loop stores the first set of data in the index no [0] and the last record is stored in index [4].
It is not necessary that all the records are printed. if we want to print a particular record it is fairly easy to do so. Consider the following code snippet which can be appended to the above example.


int no;
printf(“\nEnter record number to be displayed : “);
scanf(“%d”,&no);
if(no<1>5)
printf(“\nInvalid record no. Enter a value between 1 and 5 “);
else
{
printf(“\nName : %S”,doc[no-1].name);
printf(“\nQualification : %s”,doc[no-1].qualifcation);
printf(“\nExperience : %d”,doc[no-1].exp);
printf(“\nSurgeries : %d”,doc[no-1].surgeries);
}


Description
The values are stored in the array from index no. 0 to index no. 4 but the user is not aware that the values start from 0. for the end user the data is stored from record number 1 to 5 therefore when asked to enter the desired record number he/she will enter a value from 1 to 5 and not 0 to 4 since he/she is not familiar with the concept of programming or arrays. if a number less than 1 or more than 5 is entered the program will display an error message reading “Invalid record no. Enter a value between 1 and 5”, but if the value falls between the range(1-5) the code given in the else part will display the data of that particular doctor by subtracting 1 from the entered value. for example if the user enters 3 to view the data of the third doctor, the third record is stored in the index no. 2 (since array start from 0) therefore subtracting 1 from the user value will take us to index no 2 which is the desired record.

Example 3 : Performing calculations in a structure.


All the program created till now were examples of basic input/output. The data that was being entered by the user was shown back without much of processing. The example given below is slightly different. It will ask the user to enter some data and will calculate the remaining values based on those values.



struct products


{


int prodno,price,qty,discount,total,net;


}


void main()


{


products prod[10];


int I;


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


{


printf(“\nEnter Product No. “);


scanf(“%d”,&prod[i].prodno);


printf(“\nEnter maximum retail price :”);


scanf(“%d”,&prod[i].price);


printf(“\nEnter Quantity Purchased : “);


scanf(“%d”,&prod[i].qty);


prod[i].total=prod[i].price*prod[i].qty;


prod[i].discount=prod[i].total*3/100;


prod[i].net=prod[i].total-prod[i].discount;


}


printf(“\n NOW PRINTING DATA “);


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


{


printf(“\nProduct No. %d”,prod[i].prodno);


printf(“\nPrice %d”,prod[i].price);


printf(“\nQuantity %d”,prod[i].qty);


printf(“\nTotal %d”,prod[i].total);


printf(“\nDiscount %d”,prod[i].dis);


printf(“\nNet Payable %d”,prod[i].net);


}


}



Description

The user is prompted to enter product no,price and quantity only. The rest of the values are then calculated using basic formulas like total is price *qty, discount is calculated at 3% of total and net amount is total – discount. It is evident from the code that it is not necessary that all the values must be entered by the user only. Some values are entered by the user and remaining are determined by applying simple calculations.

Each product has six properties namely , product no (prodno), price (price), quantity(qty),total(total),discount(dis) and net payable (net). There are five products which are stored in the form of an array from 0 till 4. Each index of the array has all the six properties mentioned above. Which means that the “prodno” of the first product will be called “prod[0].prodno” where “prod” is name of the array, [0] is the index no, and prodno is the name of the structure variable. Similarly the second “prodno” will be called prod[1].prodno and so on. The easiest way to access all these values is by using a loop from 0 to 4 which will ask the user to enter the values to the array. Values like prodno and price are entered directly by the user whereas the other ones are calculated by the program itself.

Sunday, January 3, 2010

Structures

  • What is a structure?

A structure is a user defined data type created by the user as per his/her requirement. It can be also called as a composite data type since it contains more than one data types. C has many inbuilt data types like int,char,float,long etc. but it also has the option of letting the user create his/her own datatype as per the requirement. Classes in C++ and structures in C are the example of user defined datatype.

  • What is the need of a structure?

C has many primitive(inbuilt) data types like int,float,char etc. and most of the programs can easily made using them, but many times you would like to store data about a single entity. Such data when stored has a relation with other data of the same entity. Creating multiple variables will pose a problem since it will be too difficult to create so many variables. Structures are useful when data is to be stored in the form of records. A record is a collection of values where each value is related to the other value. For example, record of students, record of books etc.
Assume that we want to store information about employees of an organization which consists of employee number, name, salary etc. if there is only one employee then it wouldn’t be a problem we can easily create three different variables each for employee number,name and salary and store the data. The problem arises when there are more than one employees (which will always be the case) then creating so many variables will a huge problem. To cite an example, if there are 50 employees then we will have to create 50 x 3 = 150 variables, three (employee number,name,salary) for each employee. Arrays can be used here but even that will not be a big respite since we will have to create three arrays and the values will not have any relation with each other.

Declaring a structure

To declare a structure we can use the following syntax

struct structname
{
datatype variablename;
datatype variablename;
Datatype variablename;
};

Example

struct employees
{
int empno;
char name[10];
int salary;
};

Note :
1. The declaration must begin with the keyword “struct” followed by the name of the structure. The name of the structure can be any valid name which follows the standard rules of variable names.
2. A structure can have any number of variables declared inside it. All the variables declared inside the structure are called “members” of the structure.
3. Don’t forget to close the structure declaration with a “;”.
4. The above declaration can be made inside or outside the main() body. If it is made outside then the structure will a global structure which can be accessed from any function while if the declaration is made inside then the structure will be accessible only from the main().

Example 1 : Basic structure input/output example.

struct employees
{
int empno;
char name[10];
int salary;
};

void main()
{
clrscr();
employees manager;
printf(“\nEnter employee number : “);
scanf(“%d”,&manager.empno);
printf(“\nEnter name : “);
scanf(“%s”,&manager.name);
printf(“\nEnter Salary : “);
scanf(“%s”,&manager.salary);


printf(“\nYou’ve entered….”);
printf(“\nEmployee number %d”,manager.empno);
printf(“\nName %s”,manager.name);
printf(“\nSalary %s”,manager.salary);
}

Description
The above example contains a structure “employees”. The structure has three member variables empno,name,salary. The members of a structure cannot be accessed directly from outside the structure, therefore we must first create an object of the structure which in this example is “manager”. All the structure members will now be accessed by putting the object name before the member variable name like “manager.empno” . To access a structure member we must use the following syntax
Objectname.membername


  • Why can’t we use the structure members directly?
The answer is simple – because since they are declared inside the structure they are local members of the structure. If we omit the name of the object (manager) from the above code the compiler will flash an error saying that the variables empno,name and salary must be declared.It is true that we have declared the variables but keep in mind that they have been declared within the structure. To let the compiler find these variables we must use a proper channel to access these variables. The object name comes into play here. Remember that a structure is a user defined data type so it can be used to declare a variable just like we declare variables using inbuilt data types like int or char.In the above code manager is a variable which has a user defined data type, employee.

  • What is the difference between an object and a variable?
Nothing.An object and a variable are virtually two names of same thing. The two names are just to distinguish between variables created using primitive data type and the ones created through user defined data types. The word variable is used for variables creating through inbuilt data types while object is used for structure variables. We can also use the word variable instead of object but the word “object” is more used with reference to structures.

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.