0% found this document useful (0 votes)
15 views

UNIT-IV (C Programming I BSC)

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

UNIT-IV (C Programming I BSC)

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter – 1 POINTERS

A pointer is a variable which holds address of another variable.


A pointer is a derived data type in C. It is built from one of the fundamental data
types available in C.
Pointers contain memory addresses as their values. Since these memory addresses
are the locations in the computer memory where program instructions and data are
stored, pointers can be used to access and manipulate data stored in the memory.

int quantity = 179;


This statement instructs the system to find a location for the integer variable
quantity

Consider int x=10;


This will store the value of x in a memory location that is having a unique
memory address. Assume that the address is 5000 for x. Since memory addresses
are numbers, they can be assigned to some variables called as pointer. Since pointer
is a variable, its value is also stored in the memory in another location. Suppose p is
a pointer pointing to 5000, we can access the value of x using p.

variable value address

X 10
5000

p 5000 5048

Advantages of pointers:
1. Pointers are more efficient in handling the data tables.
2. Pointers reduce the length and complexity of a program.
3. They increase the execution speed.

UNIT-IV C PROGRAMMING (I BSC) 1


4. Pointers can be used to return multiple values from a function through function
arguments.
5. Pointers allows C to support dynamic memory management.
6. The use of a pointer array to character strings results in saving of storage space
in memory.
7. Pointers provide efficient tool for manipulating Linked list, Stack, Queue and
Trees.

Disadvantages of Pointer
• Pointers are little confusing and difficult to understand for beginner.
• Compiler may not detect the error when there is wrong usage of pointers. In
such cases program is likely to produce unexpected results.

Declaring a Pointer

General form of declaring a pointer variable :

data type *pointer-name;

This tells the compiler three things about the pointer-name.


1. * tells that the variable is a pointer variable.
2. pointer-name needs a memory location.
3. pointer-name points to a variable of type data type.
Example:
int *p;
declares p as a pointer points to an integer data type.
float *p1;
declares p1 as a pointer to a floating point variable.

Initializing Pointers
The process of assigning the address of a variable to a pointer is known as pointer
initialization.
Once a pointer variable has been declared, it can be initialized using assignment
operator and address operator
Example: p=&x;
which causes p to point to x. Now p contains the address of x.
• Before a pointer is initialized, it should not be used.

UNIT-IV C PROGRAMMING (I BSC) 2


Example: int x;
int *p;
p=&x;
• Can combine declaration of pointer and initialization of pointer in one statement.
Example:
int x,*p=&x;
• But int *p=&x,x; is invalid because x is not declared first.
• Pointer variables always point to corresponding type of data.

Accessing the address of a variable (& - address of operator)


The actual location of a variable in the memory is system dependent and therefore
the address of a variable is not known. The & operator (address of operator)
preceding a variable returns the address of a variable.
Example:
p=&x; will assign the address 5000 to the variable p.
The & operator can be used only with a simple variable or an array element.

Accessing a variable through its pointer (Accessing Value of variable using


Pointer)
Value of a variable can be accessed by using * operator known as the indirection
operator. Indirection operator is referred as value at address.
It is also called as dereferencing operator
Example: int x,*p,n;
x=10;
p=&x;
n=*p;
The last statement contains indirection operator * When the operator * is placed
before a pointer variable, the pointer returns the value of the variable to which it
points to.

Pointer expressions
Pointer variables can be used in expressions.
Example: if p1 and p2 are properly declared and initialized pointers then the
following statements are valid.
X= *p1 * *p2;
sum=sum+ *p1;
*p2=*p2+10;

UNIT-IV C PROGRAMMING (I BSC) 3


Z=*p1/ *p2; Note that there is a space between / and * otherwise /* is
considered as the beginning of a comment.

• Can add integers to or subtract integers from pointers as well as to subtract one
pointer from another.
p1+4,p2-2 and p1-p2 are all allowed.
• also use short-hand operators with pointers.
p1++;
--p2;
sum+=*p2;
• Pointers can also be compared using relational operators.
p1>p2, p1==p2,p1!=p2 are allowed.
• Cannot use pointers in multiplication, addition or division.
p1/p2, p1+p2, p1*p2 are not allowed.

Pointer increments and scale factor


When we increment a pointer, its value is increased by the length of the data type
that it points to. This length is called the scale factor. char 1 byte
Pointers can be incremented like p1++, p1=p1+2
int 2 bytes
and so on.
The expression like p1++; will cause the pointer p1 to float 4 bytes
point to the next value of its type. For e.g. if p1 is an
long int 4 bytes
integer pointer with an initial value say 2000 then after
p1++; the value of p1 will be 2002 and not 2001. double 8 bytes

Pointers and arrays


When an array is declared, the compiler allocates a base address and sufficient
amount of storage to hold all the elements of the array in sequential memory
locations. The base address is the location of the first element (index 0) of the array.
Example: int x[5]={1,2,3,4,5};
Suppose the base address of x is 1000. Each integer requires 2 bytes. The 5
elements will be stored as follows:

UNIT-IV C PROGRAMMING (I BSC) 4


The name x is defined as a constant pointer pointing to the first element x[0] and
therefore x is 1000, where x[0] is stored.
x=&x[0]=1000
If we declare p as a pointer then we can make p to point to the array x by using p=x;
this is same as p=&x[0];
Every element of x can be accessed using p++ to move from one to another.
p+1=&x[1] (1002)
p+2=&x[2] (1004)
p+3=&x[3] (1006)
p+4=&x[4] (1008)

When handling arrays, instead of using array indexing, we can use pointers to access
array elements.
Example: *(p+3) gives the value of x[3].
• Pointers can be used to manipulate two-dimensional array

UNIT-IV C PROGRAMMING (I BSC) 5


Pointers And Strings
A string is an array of characters which is terminated by the null character “\0'.
Thus the concept of pointers and one dimensional arrays can be extended to
array of characters.
Example : To access elements of a string with pointers
main()
{ char str[25] = “Pointers”, *cp; Output:
Character: P Address : 65472
int length; Character: o Address : 65473
Character: i Address : 65474
cp = &str[0]; Character: n Address : 65475
while(*cp != ‘\0’) Character: t Address : 65476
Character: e Address : 65477
{ printf(“\nCharacter :%c\tAddress : %u”, *cp, cp); Character: r Address : 65478
Character: s Address : 65479
cp++; Length of the string : 8
}
length = cp –str;
printf(“Length of the string “%d”, length);
}
Since characters require one byte of storage in memory, incrementing
pointer cp will increment its value by 1 and it will point to the next character in
the string. The concept of string can be extended to the table of strings. When we
declare a two dimensional array of strings, each string will be allocated equal
length as specified in its declaration. However, all strings of the table are rarely
equal in length. Hence instead of making each row of a fixed number of characters
we can make each row a pointer to a string of varying lengths.
Eg. char *name[3] = { “Jimmy”, “Jill”, “Joseph” };
The above declaration declares name to be an array of three pointers where
each pointer points to the particular name. This can be shown as follows :
name[0]----------> Jimmy
name[1]----------> Jill
name[2]----------> Joseph
Had we declared name to be a two dimensional array of strings as
name[3][10] it would have reserved 30 bytes for the array name, where each name
would be allocated 10 bytes. But when we declare name to be an array of pointers,
where each element points to a name, the total memory allocated would be 18
bytes as follows:
In order to access the jth character of the ith row : *(name[i] + j) would be
useful.

UNIT-IV C PROGRAMMING (I BSC) 6


Example : To demonstrate an array of pointers to strings.
main()
{ int i;
char *name[3] = { “Jimmy”, “Jill”, “Joseph” };
printf(“\nNames in the array :”);
for(i=0; i<3; i++)
printf(“\n%s”, name[i]);
}

Chapter – 2 USER DEFINED FUNCTIONS


A function is a self-contained block of code that performs a particular task.
OR
A function is a logical group of statements designed to solve a problem
C functions can be classified into two categories:
• Library functions (Built –in Functions) : These are pre-defined functions
designed by C developer
Example: printf, scanf, strlen( )etc
• User defined functions: A user defined function is a function designed by the
user to solve a problem.

Need For User-Defined functions:


If any program is developed with only main () function, Then

1. The program may become too large and complex so that debugging becomes
difficult.
2. Testing & maintenance becomes difficult.
3. For programs, which involve several repetitions of the same task, main() function
grows lengthy and leads to confusion.
4. More comment lines are required to be written to make the program
understandable.

To overcome all these difficulties, the program can be divided into a number
of user-defined functions & then each of them may be independently coded and later
combined into a single unit.

UNIT-IV C PROGRAMMING (I BSC) 7


Advantages :
1. It facilitates top-down modular programming.
2. The length of a source program can be reduced by using functions at
appropriate places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other program

Elements of User-Defined Functions


Elements of User-defined functions are:
1. Function definition
2. Function call
3. Function declaration
• The function definition is an independent program module that is specially
written to implement the requirements of the function.
• In order to use this function we need to invoke (call) it at a required place in
the program. This is known as the function call.
• The program that calls the function is referred to as the calling program or
calling function. The calling program should declare any function that is to
be used later in the program. This is known as the function declaration or
function prototype.

DEFINITION OF FUNCTIONS (Function Definition)


Defining a function refers to the process of writing the actual code of a function
that performs a specific task. A function can be defined before or after the main
program. It can be even defined in another file.
Format of a user defined function (General Form of Function definition)

User defined function includes two parts:


• Function header

UNIT-IV C PROGRAMMING (I BSC) 8


• Function body.
Function Header: It consists of three parts Return type, Function name and
Argument list with declaration.

i. return type (or function type): It denotes the data type of the value returned by
the function.
• Return type can be any data type such as int , float, char or void.
• If the return type is omitted (skipped) in the declaration then the function is
assumed to return integer data type.
• void data type is used when the function does not return any value to the calling
function.

ii. Function Name: Function name can be any valid C identifier that is used to
uniquely identify the user defined function.

iii. Argument list with declaration (Parameter list): The argument list indicates the
set of variables that will receive the values sent by the calling function. Like every
other variables, the argument list should be declared along with their data type.

Function Body: The function body is enclosed in flower brackets.


It has three parts :

i). Local variable declaration that specify the variables needed by the function.
These variables are local to the function and are not available outside this
function.
ii). Executable statements are the statements that are required to perform the actual
task.
iii). A return statement is used to return the resultant value of the function to the
calling program.

Example: function that is used to find the sum of two numbers.

This function is named as Sum. It takes two integer arguments a, b, and


returns an integer value. There is a local integer variable s that temporarily
holds the sum of two input arguments a & b. Finally the return statement will
send back the value of s to the calling function.

UNIT-IV C PROGRAMMING (I BSC) 9


Function Call
A function call establishes the link between the called function and the calling
function. Function call is a statement that transfers the control from calling function
to the called function.
A function can be called by specifying its name followed by a list of actual
parameters enclosed in parenthesis.
General syntax of function call is as follows.
Variable = function_name( argument list);
Example:
void main()
{
int y;
y=sum( a,b);
----
}

When the compiler encounters a function call, the values of actual parameters
are copied to the formal parameters and the control is transferred from the calling
function to the called function.

UNIT-IV C PROGRAMMING (I BSC) 10


Function Prototype (Function Declaration)

All functions in C program must be declared, before they are invoked. The
declaration of a function before using it, is called as a function prototype.

The general format of function prototype is as follows:

return_type function_name (type1, type2, ....);

OR
return_type function_name( type1 Arg1, type2 Arg2, ....);
Function declaration consists of four parts:

• return-type
• function name
• Parameter list
• Terminating semicolon

Example: a function that is used to add two integer numbers and return their sum
can have a typical prototype as

int sum(int, int);


OR
int sum( int a, int b);
The argument types in the function declaration must match the types of
arguments in function definition, in number and order. The arguments names need
not be same in the function declaration and the function definition.

Formal And Actual Parameters


Parameters used in function prototype (declaration) and function header
during its definition are called as formal parameters or dummy arguments. The
formal parameters will receive their values from the calling function during the
function call.
Parameters used in function call statement are known as actual parameters.
Actual parameter represents the values that are passed to the function during the
function call. Actual parameters can be variable names, constants or expression.

Following points are considered while defining the formal and actual parameters.
• The number of formal parameters should be equal to the number of actual
arguments.

UNIT-IV C PROGRAMMING (I BSC) 11


• The data types as well as the order of creation of formal parameters and actual
arguments should be same.
• The formal parameters and actual arguments can have same or different
names.
• The formal parameter must be always a variable whereas the actual parameter
can be variable, constant or expression.

Return Statement
The return statement is used to send back values from the called function to
the calling function. A function can return none or at most one value per call. The
general form of return statement is,
return;
Or
return (expression);
The first return statement does not return any value to the calling function. It
is used to exit from the function and return the control to the point from where it is
called. The second statement returns a single value of the expression to the calling
function.

Global And Local Variables


➢ Variables declared inside a block or functions are referred to as local variables.
The scope of the local variable is confined only to the function or the block in
which it has been defined.
➢ Variables declared outside the main or any other function are referred to as global
variables. If the global variables are declared in the beginning of the program,
then they are available throughout the program and in every block of the program.
However if the global variables are declared after one or more functions then
they are not available to the functions defined above them but are available to all
the functions that are defined below them.
Example: Program to find the sum of two natural numbers.

UNIT-IV C PROGRAMMING (I BSC) 12


Calling Function and Called Function
Calling function is a function which transfers the control from it to another
function.
Called function is a function which receives the call and arguments from another
function

Category Of User Defined Functions


Depending on whether arguments are present or not and whether a value is
returned or not, functions are classified into:
1. Function with no arguments and no return values.
2. Function with no arguments and one return value.
3. Function with arguments and no return value
4. Function with arguments and returns a value.
5. Function that returns multiple values.

UNIT-IV C PROGRAMMING (I BSC) 13


Function With No Arguments And No Return Value
In this type of function there is no exchange of data between the calling and
called function. The called function does not receive any arguments from the
calling function. Called functions do not return any value back to the calling
function
• The return type of these functions is “void”.
• The keyword “return” can be omitted from the body of the function as it does not
return any value.

Example:
#include<stdio.h>
void main()

{
void sum ( ); //Function Prototype
printf(“Finding Sum:”);
sum( ); //Function Call
}

void sum ( )
{
int a, b,s; // Local Variable
printf(“Enter two numbers:”);
scanf(“%d %d”, &a, &b);
s = a+b;
printf(“Sum of two numbers =%d”,s);
}

In the above example the calling function “main()” calls the function “sum()”.

UNIT-IV C PROGRAMMING (I BSC) 14


Function With No Arguments But Returns A Value
In this category of functions the called function will not receive any
arguments from the calling function but returns a value back to the calling function.

Example:
#include<stdio.h>
void main()
{
int s1;
int sum ( ); //Function Prototype

s1=sum( ); //Function Call

printf(“Sum of two numbers = %d”, s1);


}

int sum ( )
{
int a,b.s;
printf(“Enter two numbers:”);
scanf(“%d %d”, &a, &b);
s = a+b;
return(s);
}

Function With Arguments And No Return Value


In this category of functions the called function will receive arguments or
values from the calling function but will not return any value back to the calling
function. Since the function does not return any value, the return type of this function
is always void and the keyword return can be omitted from the body of the function.

UNIT-IV C PROGRAMMING (I BSC) 15


When calling these type of functions the actual arguments must match in number,
type and order with the formal parameters. During the call the actual arguments
value will be copied to the formal arguments.
Example:
#include<stdio.h>
void main()
{
int a, b, s1;
void sum (int, int); //Function Prototype
printf(“Enter two numbers:”);
scanf(“%d %d”, &a, &b);
sum(a, b); //Function Call

void sum ( int a, int b)


{
int s; //Local Variable
s = a + b;
printf(“Sum of two numbers = %d”, s);
}

Function With Arguments And A Return Value


In this category the called function receives the arguments or values from the
calling function and returns the computed result to the calling function.
• Since these functions return value to the calling function, the return type cannot
be void.

UNIT-IV C PROGRAMMING (I BSC) 16


• The return type should be the data type of the value being returned to the calling
function.
• There must be a return statement in the body of these functions to return the
resulting value to the calling function.
When calling, the actual arguments must match in number type and order
with the formal parameters.

Example:
#include<stdio.h>
void main()
{
int a, b, s1;
int sum (int, int); //Function Prototype
printf(“Enter two numbers:”);
scanf(“%d %d”, &a, &b);
s1 = sum(a, b); //Function Call

printf(“Sum of two numbers = %d”, s1);


}
int sum ( int a, int b)
{
int s; Local Variable
s = a + b;
return (s);
}

Nesting Of Functions

C permits nesting of functions. main() can call function1( ), which calls


function2(), which calls function3( ),..... and so on.
UNIT-IV C PROGRAMMING (I BSC) 17
main( )
{
-------
--------
function1( );
--------
}
function1( )
{
------
function2( );
--------
}
function3( )
{
------
------
}
Recursion
A function that calls itself directly again and again until some specified
condition is satisfied, is called as recursive function
A recursive function contains a terminating condition that is used to stop the
recursion.
Example: Program to find the factorial of a number using recursion.
#include<stdio.h>
int FACT ( int);
void main()
{ int n , fact;
printf(“Enter a number:”);
scanf(“%d”, &n);
fact = FACT(n);
printf(“The factorial of %d is %d”, n, fact);
}
int FACT( int n)
{ if(n == 1)
return (1); Recursive Function
else
return ( n * FACT (n-1));
}
UNIT-IV C PROGRAMMING (I BSC) 18
Chapter-3 User Defined Data Types

STRUCTURE
Structure is a collection of logically related data items of same or different
data types.
Structure is a user defined data type.
Advantages Of Structure
• Structures helps to organize complex data in a more meaningful way because
each variable can represent one piece of information and array can store same
type information.
• Structure is a convenient tool for handling a group of logically related data
items as accessing and manipulating structure members is easy and time saving.

Defining A Structure
Structure is defined with a keyword struct, followed by the name of the
structure.
The general format of a structure definition:
struct tag_name
{
data-type member1;
data-type member2;
___
___
data-type Membern;
};
● Tag_name is the name of the structure.
● The Members refers to the data elements of the structure. The list of all
structure members is called as a template. The template informs the compiler
about the amount of memory to reserve for each of structure variable.
● Structure members should be grouped together in a flower bracket.
● a semicolon is used to terminate the structure definition.
Example: A structure to hold students information
struct student
{ int regno;
char name[15];
float fees;
};

UNIT-IV C PROGRAMMING (I BSC) 19


Declaring A Structure Variable
The definition of the structure does not create any memory space in which
values can be stored, it is achieved by declaring the structure.
Syntax of structure declaration:
struct Tag_name Variable-list;
The declaration starts with a keyword struct followed by the tag name given
to the structure during its definition. This is followed by the list of variable names
separated by comma and finally a terminating semicolon.
Example:
struct student S1, S2;

This declaration creates two structure variables S1, and S2 of type student.

• It is also possible to combine the structure definition and declaration in one


statement
struct student
{ int regno;
char name[15];
float fees;
} S1, S2;
• The structure declaration can also be done without using the tag name as follows.
struct
{ int regno;
char name[15]; It is not recommended
float fees;
} S1, S2;

Rules to be followed while defining a structure:


1. The structure definition must begin with a keyword struct.
2. Each member is declared independently with its name and data type.
3. The members are enclosed in a flower bracket.
4. The definition is terminated with a semicolon.

ACCESSING STRUCTURE MEMBERS


The members of the structure can be accessed using member operator. The
member operator is also known as ‘dot operator’ or ‘period operator’ ( . )
Syntax to access members of the structure:
UNIT-IV C PROGRAMMING (I BSC) 20
structure_variable_name . member_name
The member operator establishes a link between the member and the structure
variable.

Example: if a structure to hold student information is defined as,


struct student
{ int regno;
char name[15];
float fees;
} S1, S2;
To refer the members regno and name we can use the member operator in the
following manner.
S1.regno
S2.name
For example: The values can be given using scanf as,
scanf(“%s”, S1.name);
scanf(“%d”, &S1.regno);

Structure Members Initialization


Structures can be initialized at compile time by assigning a set of values to
each member of the structure variable during its declaration. The values must be
separated by a comma and enclosed in a flower bracket.
Example:
struct student S1 = {101,”Gopal”, 26000 };
struct student S2 = { 102, “Ravi”, 45000 };
• Can combine the definition, declaration and initialization in a single statement
struct student
{
int regno;
char name[20];
float fees;
} S1 = {101, “Suman”, 43000};

UNIT-IV C PROGRAMMING (I BSC) 21


Rules for initializing a structure:
1. Individual members of the structure cannot be initialized inside the structure
template.
2. The order of values enclosed in braces must match the order of members in the
structure definition.
3. Partial initialization of members is possible. This is done by initializing the first
few members and leaving the remaining blank.
4. The un-initialized members should be only at the end of the list.
5. Un-initialized members are assigned the default values, zero in case of integer
and float, ‘\0’ in case of characters and string.

Copying And Comparing Structure Variables


• Two variables of the same structure type can be copied the same way as
ordinary variables. If person1 and person2 belong to the same structure, then
the following statement is valid:
person1 = person2;
person2 = person1;
• It does not permit any logical operations on structure variables.
person1 == person2;
person1 != person2; //Is not permitted.
• Structure variables can be compared by comparing members individually.
Example:
struct Book
{ char title[20];
int pages;
float price;
};
void main()
{
int i;
struct Book B1 = { “Let Us C”, 550, 220.00};
struct Book B2 = {“Let Us C”, 700, 275.00 };
struct Book B3 = B1;
if ( (B1.pages = = B3.pages) && (B1.price == B3.price) )
printf(“ B1 and B3 are same \n”);
else
printf(“B1 and B3 are different \n”);
}

UNIT-IV C PROGRAMMING (I BSC) 22


Arrays Of Structures
An array is defined with structure as its data type is called as array of structure.
Here each element of the array is structure. Array of structures are used whenever
the same structure is to be applied to a group of people, items or applications.
Example 1: To maintain the details of all students in a college,
struct student S1[100];
defines an array called S1, that contains 100 elements.
Example 2:
struct Marks
{ int m1;
Int m2;
Int m3;
};
Marks student[3] = { { 45, 68, 77 }, { 64, 38, 46 }, {57, 36, 71} };

This declares the student as an array of three elements student[0], student[1], and
student [2] and initializes their members as follows:

Table of Records
student[0].m1 = 45; m1 m2 m3
student[0].m2 =68;
Student[0]
.......
Student[1]
.......
Student[2]
student[2].m3 = 71;

Arrays Within Structures: C permits the use of arrays as structure members. We


can use single-dimensional or multidimensional arrays of type int or float or char
Example
struct Marks
{ int number;
char name[20];
float subject[3];
} student[2];

Here, the member subject contains three elements subject[0], subject[1] and
subject[2]. These elements can be accessed using appropriate subscripts.

UNIT-IV C PROGRAMMING (I BSC) 23


Student[1].subject[2];
Would refer to the marks obtained in the third subject by the second student.
Example program:

#include <stdio.h>
struct student
{
char sname[20];
int marks[3];
}s1;

void main()
{
printf("\nEnter the Name of Student : ");
gets(s1.sname);

printf("\nEnter the Marks in Subject 1 : ");


scanf("%d",&s1.marks[0]);
printf("\nEnter the Marks in Subject 2 : ");
scanf("%d",&s1.marks[1]);
printf("\nEnter the Marks in Subject 3 : ");
scanf("%d",&s1.marks[2]);

printf("\n ---- Student Details -------- ");


printf("\n Name of Student : %s",s1.sname);
printf("\n Marks in Subject 1 : %d",s1.marks[0]);
printf("\n Marks in Subject 2 : %d",s1.marks[1]);
printf("\n Marks in Subject 3 : %d",s1.marks[2]);
}

Structures Within Structures (Nested Structures)


A structure within a structure is called nested structure or embedded structure.
A nested structure is embedded within another structure as its members. There are
two ways of defining a embedded structure.
1. A structure may be completely defined within the other structure.
For example:
struct student
{

UNIT-IV C PROGRAMMING (I BSC) 24


int regno;
char name[20];
struct date
{ int day;
int month;
int year;
} dob;
};

2. There may be separate structures. The embedded structure must be


defined first and used as a member of the outer structure. For example,
struct date
{ int day;
int month;
int year;
};

struct student
{ int regno;
char name[20];
struct date dob;
};
Note: The embedded structure ’date’ (in case 2) must be defined before the outer
structure ‘Student’.

Structures And Functions


A structure variable can also be passed to and returned from a function as
parameters.
When the structure is passed as an actual parameter, any changes to the
structure members will not be effected to the members in the calling function.

For example:
struct Book
{ char title[20];
float price;
int pages;
};
struct Book Update (struct book); /* Function Prototype */
UNIT-IV C PROGRAMMING (I BSC) 25
void main()
{ struct Bok B1={ “Let Us C”, 220.00, 550 };
printf(“The details of book B1 before reprinting\n”);
printf(“Name : %s Price: %.2f Pages: %d\n”,B1.title, B1.price, B1.pages);
B1 = Update(B1); /* Function Call – Passing structure B1 as parameter */
printf(“\nThe details of book B1 after reprinting\n”);
printf(“Name : %s Price: %.2f Pages: %d\n”,B1.title, B1.price,B1.pages);
}

struct Book Update( struct Book B) /* Function Definition */


{ B.price = B.price + B.price*0.1;
B.pages = 700;
return (B);
}

DIFFERENCE BETWEEN STRUCTURE AND AN ARRAY

Structure Array

Structure is a collection of related elements An array is a collection of related


of same or different data types. elements of same data type.

Structures uses dot operator to access its Array uses index or subscript to access
members. its elements.

In structure there is no such thing as one Array can be one dimensional or multi
dimensional or multi dimensional dimensional.

Nested structures are possible. Nested array is not possible.

Two structure variables can be assigned to Assigning one array variable to another
simultaneously copy the contents of will not copy the contents of one array
individual members within the structures. onto another.

Structures are user-defined data types. Array behaves like a built in data type.

UNIT-IV C PROGRAMMING (I BSC) 26


UNIONS
Union is a mutually exclusive collection of elements of which only one should
be used at any given instance of time.
The difference between structures and unions is in terms of storage. In
structures each member has its own storage location; whereas all the members of a
union use the same location. So it can handle only one member at a time.
Union definition
General form of Union definition:
union tag_name
{ data_type member1;
data_type member2;
......
data_type membern;
};
Here
• union is a keyword
• Tag_name is the name of union
• member1, member2, ..., membern are individual members of the union.

Example:
union Item
{
int m;
float p;
char c;
};

Syntax for declaring the union variable :


union Tag_Name Variable_list;

Where variable list is a list of any valid identifier that are separated by comma.
Example: union Item purchased;

Here a variable of type union having a name ‘purchased’ is created. Union


contains three member of different data type; however only one can exists at a time.
The compiler will allocate a piece of memory that is large enough to hold the largest
variable in the union.

UNIT-IV C PROGRAMMING (I BSC) 27


To access the union member, we can use the same syntax that we use for structure
members.
i.e.,purchased.m
purchased.c
Example: Program to illustrate the unions
union item
{ int m;
float x;
};

void main()
{ union item a;
a.m = 100;
printf (“m = %d\n”, a.m); OUTPUT:
a.x = 315.27; m = 100
printf ( “x = %.2f\n”, a.x);
x = 315.27
a.m = 215;
Now m = 215
printf(“Now m = %d\n”, a.m);
}

UNIT-IV C PROGRAMMING (I BSC) 28


Difference Between Structures And Unions

STRUCTURE UNION

Structure is a collection of related items of A union is a mutually exclusive collection of


different data types. elements of which only one should be used at
any given instance of time.
General form of structure definitions General form of union definitions
struct Tag_name union Tag_name
{ {
data-type Member1; data-type Member1;
data-type Member2; data-type Member2;
...... ......
}; };
Variable declaration is of the form: Variable declaration is of the form:
struct Tag_name variabl-list; union Tag_name variabl-list;
Size of the structure variable is equal to the Size of the union variable is equal to the largest
total number f bytes occupied by all the member size in the union.
members.
All the members can be assigned values at At a given instance, only one member can be
a given instant. assigned a value.
Occupies a large amount of memory Efficient usage of memory.
depending on the structure size.

UNIT-IV C PROGRAMMING (I BSC) 29

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy