functions struct&union

40
Functions There are two types of functions Library functions They are built in functions present in C They cannot be modified They are not written by us Example: Printf, scanf User defined functions While handling large calculations we can write the program as modules. Modules are smallest unit of program. The program is split into number of subprograms and each part can be independently coded and later they can be combined into single unit. They are known as subprograms or functions A function is a module or block of program code which deals with a particular task.. .Defn: A function is a self-contained block of code that performs a particular task It save time & space We can use top down approach We can easily locate the problem they make a block of code reusable General Form: Library (or) Built in function Function type function-name (argument-list) Argument declaration; { Local Variable declaration; Statements; Return (expression); Function header

Upload: uma-parameswari

Post on 07-Apr-2017

41 views

Category:

Education


1 download

TRANSCRIPT

FunctionsThere are two types of functions

Library functions

They are built in functions present in C

They cannot be modified

They are not written by us Example: Printf, scanf

User defined functions

While handling large calculations we can write the program as modules. Modules are smallest unit of program. The program is split into number of subprograms and each part can be independently coded and later they can be combined into single unit. They are known as subprograms or functions A function is a module or block of program code which deals with a particular task..

.Defn: A function is a self-contained block of code that performs a particular task

It save time & space

We can use top down approach

We can easily locate the problem

they make a block of code reusable

General Form:

1

Library (or) Built in function

User defined functions

Function type function-name (argument-list)

Argument declaration;

{

Local Variable declaration; Statements; … … Return (expression);}

Function body

Function header

Function type - represents data type of value returned by the function

Function-name valid C variable name

Arguments list – formal arguments separated by commas

Local variable – declaration of variable in statement body

Return – keyword to return to the function

Calling a Function:

A function can be called by simply using the function name in a statement.

#include<stdio.h>

#include<conio.h>

sum(int,int);//function declaration

void main(){

int x;x=mul(10,2); function calling statementprintf(“%d\n”,x)

}mul(int a,int b){ int x;X=a*b;return (x);}

Category of the functions:

2

Category1: Functions with no arguments and no return values

Category2: Functions with arguments and no return values

Category3:Functions with arguments and return values

Category4:Functions with no arguments and return values

Category5:Functions that return multiple values

Main program

Function 1 Function 2 Function 3 Function 4

Category 1:No Arguments and No Return Values

When a function has no arguments, it does not receive any data from the calling function

When it does not return a value, the calling function does not receive any data from the called function

No Input

No Output

/* Sample Program */#include<stdio.h>

#include<conio.h>

value();

Void main( ){value();

}/* value function*/value( ){

int n,p; float r, sum;printf(“Enter the Amount\n”);scanf(“%d”,&p);printf(“Enter Number of Years\n”);scanf(“%d”,&n);printf(“Enter interest rate\n”);scanf(“%f”,&r);sum=(p*n*r)/100;printf(“Result is %f”,n,sum);

}

Category 2 : Functions with Arguments but No Return Value

When a function has arguments, it receives data from the calling function

When it does not return a value, the calling function does not receive any data from the called function

3

function1(){………function2()……}

function2(){………}

Output:

Enter the Amount 1000

Enter Number of Years 5

Enter interest rate 0.1

Result is 5

Values of

Argument

No Output

/* Sample Program */#include<stdio.h>

#include<conio.h>

value(int,int,float);main( ){

int n,p; float r;printf(“Enter the Amount\n”);scanf(“%d”,&p);printf(“Enter Number of Years\n”);scanf(“%d”,&n);printf(“Enter interest rate\n”);scanf(“%f”,&r); value(p,n,r);

}value(int p,int n,float r){

float sum;sum=(p*n*r)/100;printf(“Result is %f”,sum);

}

Category 3 : Function with Arguments and Return Value

When a function has arguments, it receives data from the calling function

When it has return a value, the calling function receive result from the called

function

Values of

Argument

Result

4

function1(){………function2(arg)……}

function2(arg){………}

function1(){………function2(arg)……}

function2(arg){………return(e)}

Output:

Enter the Amount 1000

Enter Number of Years 5

Enter interest rate 0.1

Result is 5

/* Sample Program */#include<stdio.h>

#include<conio.h>

value(int,int,float);main( ){

int n,p; float r, sum;printf(“Enter the Amount\n”);scanf(“%d”,&p);printf(“Enter Number of Years\n”);scanf(“%d”,&n);printf(“Enter interest rate\n”);scanf(“%f”,&r);sum=value(p,n,r);printf(“Result is %f”,sum);

}value(int p,int n,float r){

float sum1;sum1=(p*n*r)/100;return(sum1);

}Category4:Functions with no arguments and return values

When a function has no arguments.

When it has return a value, the calling function receive result from the called

function.

No input

result

/* Sample Program */#include<stdio.h>

#include<conio.h>

value();

5

Output:

Enter the Amount 1000

Enter Number of Years 5

Enter interest rate 0.1

Result is 5

function1(){………function2()……}

function2(){………return(e)}

main( ){

int m=value();printf(“m=%d”,m);}value(){

int number;printf(“Enter a number:);scanf(“%d”,&number)return(number);

}

Category5:Functions that return multiple values

When a function has arguments, it receives data from the calling function

When it has return multiple values, the calling function receive result from the

called function.

Value of

arguement

result

multiple values

/* Sample Program */#include<stdio.h>

#include<conio.h>

value(int x,int y,int *s,int *d);main( ){

int x=20,y=10,s,d;value(int x,int y,int *s,int *d);

6

Output:

Enter a number:10

m=10

function1(){………function2(arg)……}

function2(arg){………}

Output:

The result s=30

d=10

printf(“The result s =%d\n d=%d\n”,s,d));}value(int x,int y,int *sum,int *diff){

*sum=a+b;*diff= a-b;

}Ref:pg:286(nesting of functions)

Recursion

When a function calls itself it is called recursion.

“ Calling itself is called recursion ”

Ex 1:

main(){printf(“welcome”);main();)

Explanation: main() function is recursively called here.

Ex 2:

#include<stdio.>#include<conio.h>factorial(int);void main( ){

int f;f=factorial(5);printf(“factorial of 5 is %d\n”,f);

}factorial(int n){

int fact;if(n==1)

7

return(1);else

fact=n*factorial(n-1)return(fact);}

Explanation: Factorial value is calculated for 5 as follows

PASSING ARRAYS TO FUNCTIONS

In C programming, a single array element or an entire array can be passed to a function. Also, both one-dimensional and multi-dimensional array can be passed to function as argument.

Passing One-dimensional Array In FunctionC program to pass a single element of an array to function

#include <stdio.h>

void display(int a)

{

8

printf("%d",a);

}

int main(){

int c[]={2,3,4};

display(c[2]); //Passing array element c[2] only.

return 0;

}

Output

4

Single element of an array can be passed in similar manner as passing variable to a function.

Passing entire one-dimensional array to a functionWhile passing arrays to the argument, the name of the array is passed as an argument(,i.e, starting address of memory area is passed as argument).

Write a C program to pass an array containing age of person to a function. This function should find average age and display the average age in main function.

#include <stdio.h>

float average(float a[]);

int main(){

float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};

avg=average(c); /* Only name of array is passed as argument. */

printf("Average age=%.2f",avg);

return 0;

}

float average(float a[]){

int i;

float avg, sum=0.0;

for(i=0;i<6;++i){

9

sum+=a[i];

}

avg =(sum/6);

return avg;

}

Output

Average age=27.08

Passing Multi-dimensional Arrays to FunctionTo pass two-dimensional array to a function as an argument, starting address of memory area reserved is passed as in one dimensional array

Example to pass two-dimensional arrays to function

#include

void Function(int c[2][2]);

int main(){

int c[2][2],i,j;

printf("Enter 4 numbers:\n");

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

for(j=0;j<2;++j){

scanf("%d",&c[i][j]);

}

Function(c); /* passing multi-dimensional array to function */

return 0;

}

void Function(int c[2][2]){

/* Instead to above line, void Function(int c[][2]){ is also valid */

int i,j;

10

printf("Displaying:\n");

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

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

printf("%d\n",c[i][j]);

}

Output

Enter 4 numbers:

2

3

4

5

Displaying:

2

3

4

5

Passing strings to functions

The strings are treated as character arrays in c.Therefore the rules for Passing strings to functions are similar to Passing arrays to functions.#include <stdio.h>char* upper(char *word);int main(){ char word[100]; printf("Enter a string: "); gets(word);

11

printf("\nThe uppercase equivalent is: %s\n",upper(word)); return 0;}

char* upper(char *word){ int i; for (i=0;i<strlen(word);i++) word[i]=(word[i]>96&&word[i]<123)?word[i]-32:word[i]; return word;}

The Scope and lifetime of the variables in functions

A variable in C can have any one of the four storage classes

Automatic variables

External variables

Static variables

Register variables

Scope of the variable determines in which part of the program a variable is actually available for use (active).

Storage classes

Automatic Variables:

These variables are declared inside a function

These variables created when you enter into the function and destroyed when the function exited

Automatic variables are private to the function and also referred as local or internal variable

A variable declared inside a function without storage class , by default, an automatic variable.

Example: #include<stdio.h>

12

main( ){int number;…………}

main( ){auto int number;…………}

Both are equal

#include<conio.h>

fun1();

fun2();

void main( ){

int m=1000;fun2( );printf(“%d\n”m);

}fun1( ){

int m=10;printf(“%d\n”,m);

}fun2( ){

int m=100;fun1( );printf(“%d\n”,m);

}

External Variables:

Variables are both alive and active through out the program are known as external variables.

They are also known as global variables

External variables are declared outside a function.

Ex:

#include<stdio.h>

#include<conio.h>

fun1();

fun2();

fun3();

int x;void main( ){

x=10;printf(“x=%d\n”,x);printf(“x=%d\n”,fun1( ));printf(“x=%d\n”,fun2( ));printf(“x=%d\n”,fun3( ));

}

13

Output:

10

100

1000

Output

x=10

x=20

x=1

x=30

fun1( ){x=x+10;return(x);

}fun2( ){

int x;x=1;return(x);

}fun3( ){

x=x+10;return(x);

}

Static Variables:

The value of static variables persists until the end of the program

Using static keyword we declare static variables

Ex:

static int x;

static float y;

A static variables maybe either an internal or an external type, depending on the place of declaration

Internal static variables are similar to auto variables but the internal static variables can be used to retain values between function calls

/* Sample Program */#include<stdio.h>

#include<conio.h>

stat();

void main( ){int i;for(i=1;i<=3;i++)stat( );getch();}stat( ){static int x=0;x=x+1;printf(“x=%d\n”,x);

14

Output:

x=1

x=2

x=3

}

Register Variables:

Instead of keeping the value of the variables in memory, register variables

maintained in the registers. (Register access is faster than the memory).

Ex:

register int count;

StructureArrays are used to store large set of data and manipulate them but the

disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure.

Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types.(A structure is a package of one or usually more variables which are grouped under a single name. Structures are not like arrays: a structure can hold any mixture of different types of data: it can even hold arrays of different types or Combine variables into a single package called a structure..)or it is collection of heterogeneous(different) types of data can be grouped to form structure. The entire collection can be referred to by structure name, the individual components which are called fields or members can be accessed and processed separately.

syntax

The word struct is a keyword .

The tag is the name that identifies structures of type and menber1,member2..

member n are individual member declaration.

An individual structure type variable can be declared as follows:

15

struct tag_name { data type member1; data type member2; … … data type member n;} ;

struct tag variable1, variable2,….,variable n;

The declaration of the structure composition with that of structure variables,

Example:

Structures are declared by using the struct keyword

struct samplename{    int a;    char b;}

This structure is named sampleName.

It contains two variables: an integer named a and a character named b.

The above command only creates the structure. (it doesn't declare any variables.)

(structure)

(member)

(member)

The following line declares a structure variable named

s1.

struct sample s1;

Items within the structure are referred to by using dot notation.

printf("Character 1 is %s\n",g1.name);

EXAMPLE

Program1

16

samplename

a

b

struct tag_name { data type member1; data type member2; … … data type member n;}variable1, variable2,….,variable n;

#include <stdio.h>struct student{    char *name;    float marks;}   student1, student2; main ( ){    struct student student3;    student1.name = "rose";    student2.marks = 99.9;    printf (" Name is %s \n", student1.name);    printf (" Marks are %f \n", student2.marks);}

Output Name is rose

Mark are 99.900002

Program2#include <stdio.h> main(){  struct{    int a;    int b;  } x, y;   x.a = 10;  y = x;  /* assign one structure to another */  printf("%d", y.a);}Program3#include <stdio.h>struct stype{  int i;  char ch;  double d;  char str[80];} s;main(){  printf("Enter an integer: ");  scanf("%d:", &s.i);  printf("Enter a character: ");  scanf(" %c", &s.ch);   printf("Enter a floating point number: ");  scanf("%lf", &s.d);  printf("Enter a string: ");  scanf("%s", s.str);  printf("%d %c %f %s", s.i, s.ch, s.d, s.str);}

Note: A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure.

17

Initializing structure:

Like other data type we can initialize structure when we declare them. As for initialization goes structure obeys the same set of rules as arrays we initialize the fields of a structure by the following structure declaration with a list containing values for each fields as with arrays these values must be evaluate at compile time.

Example1(Consider the program 3):

struct stype st1{12345; ‘a’; 2.43; “KSR college”;};

this initializes the 12345 to i, ‘a’ to ch, 2.43 to d, and the string “KSR college” to str.

Example2:

#include<stdio.h>main(){

strut student{int rollno;float mark1,mark2,mark3;

};static struct student class={52,50.5,67.8,89.0};printf(“Rollno=%d\n”,class.rollno);printf(“Marks=%d\n%d\n%d”,class.mark1,class.mark2,class.mark3);

}

Declaring Structure Variables & Accessing Structure Members:

A field or member of structure is unique name if more than one structure is declared.

The same field or member name may be used with different data types.

Here each structure member will treated as a separate variable and reverse the memory space according to their data type member.

Example

#include<stdio.h>main(){

struct first{int a;float b;char c;

};struct second{

char a;int b;float c;

};

18

struct first f;struct second t;f.a=20;f.b=17.986;f.c=’z’;t.a=10;t.b=12.56;t.c=’g’;printf(“First Structure\n”);printf(“%d\n%f\n%c\n”, f.a,f.b,f.c);printf(“Second Structure\n”);printf(“%d\n%f\n%c\n”, t.a,t.b,t.c);

}Structures within Structures

Structures are said to nest. This means that structure templates can contain other structures as members. Consider two structure types: struct first_structure { int value; float number; };

and

struct second_structure {

int tag; struct first_structure fs;

} x;

These two structures are of different types, yet the first of the two is included in the second. An instance of the second structure would be initialized by the following assignments. The structure variable name is x:

x.tag = 10;

x.fs.value = 20;

x.fs.number = 30.0;

The way in which the member operator .(dot) can be used over and over again. No parentheses are necessary, because the reference which is calculated by this operator is worked out from left to right.(Ref:pg324:topic).

Array of structuresStructure is collection of different data type. An object of structure represents a single record in memory, if we want more than one record of structure type, we have to create an

19

array of structure or object. As we know, an array is a collection of similar type, therefore an array can be of structure type.

Syntax for declaring structure array

struct struct-name

{

datatype var1;

datatype var2;

- - - - - - - - - -

- - - - - - - - - -

datatype varN;

};

struct struct-name obj [ size ];

Example for declaring structure array

#include<stdio.h>

struct Employee

{

int Id;

char Name[25];

int Age;

long Salary;

};

void main()

{

int i;

struct Employee Emp[ 3 ]; //Statement 1

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

20

{

printf("\nEnter details of %d Employee",i+1);

printf("\n\tEnter Employee Id : ");

scanf("%d",&Emp[i].Id);

printf("\n\tEnter Employee Name : ");

scanf("%s",&Emp[i].Name);

printf("\n\tEnter Employee Age : ");

scanf("%d",&Emp[i].Age);

printf("\n\tEnter Employee Salary : ");

scanf("%ld",&Emp[i].Salary);

}

printf("\nDetails of Employees");

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

printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);

}

Output :

Enter details of 1 Employee

Enter Employee Id : 101

Enter Employee Name : Suresh

Enter Employee Age : 29

Enter Employee Salary : 45000

Enter details of 2 Employee

Enter Employee Id : 102

21

Enter Employee Name : Mukesh

Enter Employee Age : 31

Enter Employee Salary : 51000

Enter details of 3 Employee

Enter Employee Id : 103

Enter Employee Name : Ramesh

Enter Employee Age : 28

Enter Employee Salary : 47000

Details of Employees

101 Suresh 29 45000

102 Mukesh 31 51000

103 Ramesh 28 47000

In the above example, we are getting and displaying the data of 3 employee using array of object. Statement 1 is creating an array of Employee Emp to store the records of 3 employees.

Arrays within structuresstructure is collection of different data type. Like normal data type, It can also store an array as well.

Syntax for array within structure

struct struct-name

{

datatype var1; // normal variable

datatype array [size]; // array variable

- - - - - - - - - -

- - - - - - - - - -

datatype varN;

};

22

struct struct-name obj;

Example for array within structure

struct Student

{

int Roll;

char Name[25];

int Marks[3]; //Statement 1 : array of marks

int Total;

float Avg;

};

void main()

{

int i;

struct Student S;

printf("\n\nEnter Student Roll : ");

scanf("%d",&S.Roll);

printf("\n\nEnter Student Name : ");

scanf("%s",&S.Name);

S.Total = 0;

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

{

printf("\n\nEnter Marks %d : ",i+1);

scanf("%d",&S.Marks[i]);

S.Total = S.Total + S.Marks[i];

}

23

S.Avg = S.Total / 3;

printf("\nRoll : %d",S.Roll);

printf("\nName : %s",S.Name);

printf("\nTotal : %d",S.Total);

printf("\nAverage : %f",S.Avg);

}

Output :

Enter Student Roll : 10

Enter Student Name : Kumar

Enter Marks 1 : 78

Enter Marks 2 : 89

Enter Marks 3 : 56

Roll : 10

Name : Kumar

Total : 223

Average : 74.00000

Structure and Function in CUsing function we can pass structure as function argument and we can also return structure from function.

Passing structure as function argumentStructure can be passed to function through its object therefore passing structure to function or passing structure object to function is same thing because structure object represents the structure. Like normal variable, structure variable(structure object) can be pass by value or by references / addresses.

Passing Structure by ValueIn this approach, the structure object is passed as function argument to the definition of function, here object is reperesenting the members of structure with their values.

Example for passing structure object by value

24

#include<stdio.h>

struct Employee

{

int Id;

char Name[25];

int Age;

long Salary;

};

void Display(struct Employee);

void main()

{

struct Employee Emp = {1,"Kumar",29,45000};

Display(Emp);

}

void Display(struct Employee E)

{

printf("\n\nEmployee Id : %d",E.Id);

printf("\nEmployee Name : %s",E.Name);

printf("\nEmployee Age : %d",E.Age);

printf("\nEmployee Salary : %ld",E.Salary);

}

Output :

Employee Id : 1

Employee Name : Kumar

Employee Age : 29

Employee Salary : 45000

25

Passing Structure by ReferenceIn this approach, the reference/address structure object is passed as function argument to the definition of function.

Example for passing structure object by reference

#include<stdio.h>

struct Employee

{

int Id;

char Name[25];

int Age;

long Salary;

};

void Display(struct Employee*);

void main()

{

struct Employee Emp = {1,"Kumar",29,45000};

Display(&Emp);

}

void Display(struct Employee *E)

{

printf("\n\nEmployee Id : %d",E->Id);

printf("\nEmployee Name : %s",E->Name);

printf("\nEmployee Age : %d",E->Age);

printf("\nEmployee Salary : %ld",E->Salary);

}

26

Output :

Employee Id : 1

Employee Name : Kumar

Employee Age : 29

Employee Salary : 45000

Function Returning StructureStructure is user-defined data type, like built-in data types structure can be return from function.

Example for passing structure object by reference

#include<stdio.h>

struct Employee

{

int Id;

char Name[25];

int Age;

long Salary;

};

Employee Input(); //Statement 1

void main()

{

struct Employee Emp;

Emp = Input();

printf("\n\nEmployee Id : %d",Emp.Id);

printf("\nEmployee Name : %s",Emp.Name);

27

printf("\nEmployee Age : %d",Emp.Age);

printf("\nEmployee Salary : %ld",Emp.Salary);

}

Employee Input()

{

struct Employee E;

printf("\nEnter Employee Id : ");

scanf("%d",&E.Id);

printf("\nEnter Employee Name : ");

scanf("%s",&E.Name);

printf("\nEnter Employee Age : ");

scanf("%d",&E.Age);

printf("\nEnter Employee Salary : ");

scanf("%ld",&E.Salary);

return E; //Statement 2

}

Output :

Enter Employee Id : 10

Enter Employee Name : Ajay

Enter Employee Age : 25

Enter Employee Salary : 15000

Employee Id : 10

Employee Name : Ajay

Employee Age : 25

28

Employee Salary : 15000

In the above example, statement 1 is declaring Input() with return type Employee. As we know structure is user-defined data type and structure name acts as our new user-defined data type, therefore we use structure name as function return type.

Input() have local variable E of Employee type. After getting values from user statement 2 returns E to the calling function and display the values.

Union in CBoth structure and union are collection of different datatype. They are used to group number of variables of different type in a single unit.

Difference betweenw Structure and union.1. Declaration and Initialization of structure starts with struct keyword. Declaration and Initialization of union starts with union keyword.

2. Structure allocates different memory locations for all its members while union allocates common memory location for all its members. The memory occupied by a union will be large enough to hold the largest member of the union.

Union declarationDeclaration of union must start with the keyword union followed by the union name and union's member variables are declared within braces.

Syntax for declaring union

union union-name

{

datatype var1;

datatype var2;

- - - - - - - - - -

- - - - - - - - - -

datatype varN;

};

Accessing the union members

29

We have to create an object of union to access its members. Object is a variable of type union. Union members are accessed using the dot operator(.) between union's object and union's member name.

Syntax for creating object of union

union union-name obj;

Example for creating object & accessing union members

#include<stdio.h>

union Employee

{

int Id;

char Name[25];

int Age;

long Salary;

};

void main()

{

union Employee E;

printf("\nEnter Employee Id : ");

scanf("%d",&E.Id);

printf("Employee Id : %d",E.Id);

printf("\n\nEnter Employee Name : ");

scanf("%s",&E.Name);

printf("Employee Name : %s",E.Name);

printf("\n\nEnter Employee Age : ");

scanf("%d",&E.Age);

30

printf("Employee Age : %d",E.Age);

printf("\n\nEnter Employee Salary : ");

scanf("%ld",&E.Salary);

printf("Employee Salary : %ld",E.Salary);

}

Output :

Enter Employee Id : 1

Employee Id : 1

Enter Employee Name : Kumar

Employee Name : Kumar

Enter Employee Age : 29

Employee Age : 29

Enter Employee Salary : 45000

Employee Salary : 45000

Here, all the members are getting printed very well because one member is being used at a time.

Example of comparing size of union and structure

#include<stdio.h>

struct Employee1

{

int Id;

31

char Name[25];

long Salary;

};

union Employee2

{

int Id;

char Name[25];

long Salary;

};

void main()

{

printf("\nSize of Employee1 is : %d",sizeof(Employee1));

printf("\nSize of Employee2 is : %d",sizeof(Employee2));

}

Output :

Size of Employee1 is : 31

Size of Employee2 is : 25

32

Bit fields in CThere are times when the member variables of a structure represent some flags that store either 0 or 1. Here is an example :

struct info

{

int isMemoryFreed;

int isObjectAllocated;

}

If you observe, though a value of 0 or 1 would be stored in these variables but the memory used would be complete 8 bytes.

To reduce memory consumption when it is known that only some bits would be used for a variable, the concept of bit fields can be used.

Bit fields allow efficient packaging of data in the memory. Here is how bit fields are defined :

struct info

{

int isMemoryFreed : 1;

int isObjectAllocated : 1;

}

The above declaration tells the compiler that only 1 bit each from the two variables would be used. After seeing this, the compiler reduces the memory size of the structure.

33