SlideShare uma empresa Scribd logo
1 de 33
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:
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 statement
printf(“%dn”,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 Amountn”);
scanf(“%d”,&p);
printf(“Enter Number of Yearsn”);
scanf(“%d”,&n);
printf(“Enter interest raten”);
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 Amountn”);
scanf(“%d”,&p);
printf(“Enter Number of Yearsn”);
scanf(“%d”,&n);
printf(“Enter interest raten”);
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
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
Result
/* Sample Program */
#include<stdio.h>
#include<conio.h>
value(int,int,float);
main( )
{
int n,p; float r, sum;
printf(“Enter the Amountn”);
scanf(“%d”,&p);
printf(“Enter Number of Yearsn”);
scanf(“%d”,&n);
printf(“Enter interest raten”);
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>
5
Output:
Enter the Amount 1000
Enter Number of Years 5
Enter interest rate 0.1
Result is 5
function1()
{
…
…
…
function2()
…
…
}
function2()
{
…
…
…
return(e)
}
value();
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 =%dn d=%dn”,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 %dn”,f);
}
factorial(int n){
int fact;
7
if(n==1)
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 Function
C 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 function
While 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 Function
To 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("%dn",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: %sn",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.
12
main( )
{
int number;
……
……
}
main( )
{
auto int number;
……
……
}
Both are equal
Example: #include<stdio.h>
#include<conio.h>
fun1();
fun2();
void main( )
{
int m=1000;
fun2( );
printf(“%dn”m);
}
fun1( )
{
int m=10;
printf(“%dn”,m);
}
fun2( )
{
int m=100;
fun1( );
printf(“%dn”,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=%dn”,x);
printf(“x=%dn”,fun1( ));
13
Output:
10
100
1000
printf(“x=%dn”,fun2( ));
printf(“x=%dn”,fun3( ));
}
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( )
14
Output
x=10
x=20
x=1
x=30
Output:
x=1
x=2
x=3
{
static int x=0;
x=x+1;
printf(“x=%dn”,x);
}
• 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;
Structure
Arrays 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..
15
struct tag_name
{
data type member1;
data type member2;
…
…
data type member n;
} ;
member n are individual member declaration.
An individual structure type variable can be declared as follows:
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;
16
samplename
a
b
struct tag variable1, variable2,….,variable n;
struct tag_name
{
data type member1;
data type member2;
…
…
data type member n;
}variable1, variable2,….,variable n;
Items within the structure are referred to by using dot notation.
printf("Character 1 is %sn",g1.name);
EXAMPLE
Program1
#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: ");
17
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.
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=%dn”,class.rollno);
printf(“Marks=%dn%dn%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;
18
};
struct second{
char a;
int b;
float c;
};
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 Structuren”);
printf(“%dn%fn%cn”, f.a,f.b,f.c);
printf(“Second Structuren”);
printf(“%dn%fn%cn”, 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;
19
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 structures
Structure 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
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;
};
20
void main()
{
int i;
struct Employee Emp[ 3 ]; //Statement 1
for(i=0;i<3;i++)
{
printf("nEnter details of %d Employee",i+1);
printf("ntEnter Employee Id : ");
scanf("%d",&Emp[i].Id);
printf("ntEnter Employee Name : ");
scanf("%s",&Emp[i].Name);
printf("ntEnter Employee Age : ");
scanf("%d",&Emp[i].Age);
printf("ntEnter Employee Salary : ");
scanf("%ld",&Emp[i].Salary);
}
printf("nDetails of Employees");
for(i=0;i<3;i++)
printf("n%dt%st%dt%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}
Output :
Enter details of 1 Employee
Enter Employee Id : 101
21
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000
Enter details of 2 Employee
Enter Employee Id : 102
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 structures
structure 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
22
datatype array [size]; // array variable
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
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("nnEnter Student Roll : ");
scanf("%d",&S.Roll);
printf("nnEnter Student Name : ");
scanf("%s",&S.Name);
S.Total = 0;
for(i=0;i<3;i++)
23
{
printf("nnEnter Marks %d : ",i+1);
scanf("%d",&S.Marks[i]);
S.Total = S.Total + S.Marks[i];
}
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 C
Using function we can pass structure as function argument and we can also return
structure from function.
Passing structure as function argument
Structure 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
24
represents the structure. Like normal variable, structure variable(structure object) can be
pass by value or by references / addresses.
Passing Structure by Value
In 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
#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("nnEmployee Id : %d",E.Id);
printf("nEmployee Name : %s",E.Name);
printf("nEmployee Age : %d",E.Age);
printf("nEmployee Salary : %ld",E.Salary);
}
25
Output :
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
Passing Structure by Reference
In 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)
26
{
printf("nnEmployee 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
Function Returning Structure
Structure 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()
{
27
struct Employee Emp;
Emp = Input();
printf("nnEmployee Id : %d",Emp.Id);
printf("nEmployee Name : %s",Emp.Name);
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
28
Enter Employee Age : 25
Enter Employee Salary : 15000
Employee Id : 10
Employee Name : Ajay
Employee Age : 25
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 C
Both 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 declaration
Declaration 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;
- - - - - - - - - -
29
- - - - - - - - - -
datatype varN;
};
Accessing the union members
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);
30
printf("nnEnter Employee Name : ");
scanf("%s",&E.Name);
printf("Employee Name : %s",E.Name);
printf("nnEnter Employee Age : ");
scanf("%d",&E.Age);
printf("Employee Age : %d",E.Age);
printf("nnEnter 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
31
#include<stdio.h>
struct Employee1
{
int Id;
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 :
32
Size of Employee1 is : 31
Size of Employee2 is : 25
Bit fields in C
There 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

Mais conteúdo relacionado

Mais procurados

Mais procurados (19)

lets play with "c"..!!! :):)
lets play with "c"..!!! :):)lets play with "c"..!!! :):)
lets play with "c"..!!! :):)
 
Function in c
Function in cFunction in c
Function in c
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and types
 
Function lecture
Function lectureFunction lecture
Function lecture
 
Function in c program
Function in c programFunction in c program
Function in c program
 
C programming function
C  programming functionC  programming function
C programming function
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Function
FunctionFunction
Function
 
C functions
C functionsC functions
C functions
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Functions in c
Functions in cFunctions in c
Functions in c
 
C function presentation
C function presentationC function presentation
C function presentation
 
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions
FunctionsFunctions
Functions
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Functions in c
Functions in cFunctions in c
Functions in c
 

Destaque (6)

update cv
update cvupdate cv
update cv
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
Revista Norte Sul
Revista Norte SulRevista Norte Sul
Revista Norte Sul
 
Array &strings
Array &stringsArray &strings
Array &strings
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
Glasgow cal seminar
Glasgow cal seminarGlasgow cal seminar
Glasgow cal seminar
 

Semelhante a Functions struct&union

Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
alish sha
 

Semelhante a Functions struct&union (20)

Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
CHAPTER 6
CHAPTER 6CHAPTER 6
CHAPTER 6
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Functions
Functions Functions
Functions
 
Function
FunctionFunction
Function
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
Array Cont
Array ContArray Cont
Array Cont
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 
C functions list
C functions listC functions list
C functions list
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
 
Function
Function Function
Function
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Último (20)

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

Functions struct&union

  • 1. 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: 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
  • 2.  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 statement printf(“%dn”,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
  • 3. 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 Amountn”); scanf(“%d”,&p); printf(“Enter Number of Yearsn”); scanf(“%d”,&n); printf(“Enter interest raten”); 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
  • 4. 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 Amountn”); scanf(“%d”,&p); printf(“Enter Number of Yearsn”); scanf(“%d”,&n); printf(“Enter interest raten”); 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 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
  • 5. Result /* Sample Program */ #include<stdio.h> #include<conio.h> value(int,int,float); main( ) { int n,p; float r, sum; printf(“Enter the Amountn”); scanf(“%d”,&p); printf(“Enter Number of Yearsn”); scanf(“%d”,&n); printf(“Enter interest raten”); 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> 5 Output: Enter the Amount 1000 Enter Number of Years 5 Enter interest rate 0.1 Result is 5 function1() { … … … function2() … … } function2() { … … … return(e) }
  • 6. value(); 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
  • 7. printf(“The result s =%dn d=%dn”,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 %dn”,f); } factorial(int n){ int fact; 7
  • 8. if(n==1) 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 Function C program to pass a single element of an array to function #include <stdio.h> void display(int a) { 8
  • 9. 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 function While 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
  • 10. sum+=a[i]; } avg =(sum/6); return avg; } Output Average age=27.08 Passing Multi-dimensional Arrays to Function To 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
  • 11. printf("Displaying:n"); for(i=0;i<2;++i) for(j=0;j<2;++j) printf("%dn",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
  • 12. printf("nThe uppercase equivalent is: %sn",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. 12 main( ) { int number; …… …… } main( ) { auto int number; …… …… } Both are equal
  • 13. Example: #include<stdio.h> #include<conio.h> fun1(); fun2(); void main( ) { int m=1000; fun2( ); printf(“%dn”m); } fun1( ) { int m=10; printf(“%dn”,m); } fun2( ) { int m=100; fun1( ); printf(“%dn”,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=%dn”,x); printf(“x=%dn”,fun1( )); 13 Output: 10 100 1000
  • 14. printf(“x=%dn”,fun2( )); printf(“x=%dn”,fun3( )); } 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( ) 14 Output x=10 x=20 x=1 x=30 Output: x=1 x=2 x=3
  • 15. { static int x=0; x=x+1; printf(“x=%dn”,x); } • 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; Structure Arrays 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.. 15 struct tag_name { data type member1; data type member2; … … data type member n; } ;
  • 16. member n are individual member declaration. An individual structure type variable can be declared as follows: 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; 16 samplename a b struct tag variable1, variable2,….,variable n; struct tag_name { data type member1; data type member2; … … data type member n; }variable1, variable2,….,variable n;
  • 17. Items within the structure are referred to by using dot notation. printf("Character 1 is %sn",g1.name); EXAMPLE Program1 #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: "); 17
  • 18. 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. 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=%dn”,class.rollno); printf(“Marks=%dn%dn%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; 18
  • 19. }; struct second{ char a; int b; float c; }; 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 Structuren”); printf(“%dn%fn%cn”, f.a,f.b,f.c); printf(“Second Structuren”); printf(“%dn%fn%cn”, 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; 19
  • 20. 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 structures Structure 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 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; }; 20
  • 21. void main() { int i; struct Employee Emp[ 3 ]; //Statement 1 for(i=0;i<3;i++) { printf("nEnter details of %d Employee",i+1); printf("ntEnter Employee Id : "); scanf("%d",&Emp[i].Id); printf("ntEnter Employee Name : "); scanf("%s",&Emp[i].Name); printf("ntEnter Employee Age : "); scanf("%d",&Emp[i].Age); printf("ntEnter Employee Salary : "); scanf("%ld",&Emp[i].Salary); } printf("nDetails of Employees"); for(i=0;i<3;i++) printf("n%dt%st%dt%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary); } Output : Enter details of 1 Employee Enter Employee Id : 101 21
  • 22. Enter Employee Name : Suresh Enter Employee Age : 29 Enter Employee Salary : 45000 Enter details of 2 Employee Enter Employee Id : 102 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 structures structure 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 22
  • 23. datatype array [size]; // array variable - - - - - - - - - - - - - - - - - - - - datatype varN; }; 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("nnEnter Student Roll : "); scanf("%d",&S.Roll); printf("nnEnter Student Name : "); scanf("%s",&S.Name); S.Total = 0; for(i=0;i<3;i++) 23
  • 24. { printf("nnEnter Marks %d : ",i+1); scanf("%d",&S.Marks[i]); S.Total = S.Total + S.Marks[i]; } 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 C Using function we can pass structure as function argument and we can also return structure from function. Passing structure as function argument Structure 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 24
  • 25. represents the structure. Like normal variable, structure variable(structure object) can be pass by value or by references / addresses. Passing Structure by Value In 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 #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("nnEmployee Id : %d",E.Id); printf("nEmployee Name : %s",E.Name); printf("nEmployee Age : %d",E.Age); printf("nEmployee Salary : %ld",E.Salary); } 25
  • 26. Output : Employee Id : 1 Employee Name : Kumar Employee Age : 29 Employee Salary : 45000 Passing Structure by Reference In 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) 26
  • 27. { printf("nnEmployee 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 Function Returning Structure Structure 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() { 27
  • 28. struct Employee Emp; Emp = Input(); printf("nnEmployee Id : %d",Emp.Id); printf("nEmployee Name : %s",Emp.Name); 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 28
  • 29. Enter Employee Age : 25 Enter Employee Salary : 15000 Employee Id : 10 Employee Name : Ajay Employee Age : 25 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 C Both 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 declaration Declaration 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; - - - - - - - - - - 29
  • 30. - - - - - - - - - - datatype varN; }; Accessing the union members 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); 30
  • 31. printf("nnEnter Employee Name : "); scanf("%s",&E.Name); printf("Employee Name : %s",E.Name); printf("nnEnter Employee Age : "); scanf("%d",&E.Age); printf("Employee Age : %d",E.Age); printf("nnEnter 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 31
  • 32. #include<stdio.h> struct Employee1 { int Id; 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 : 32
  • 33. Size of Employee1 is : 31 Size of Employee2 is : 25 Bit fields in C There 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