0% found this document useful (0 votes)
30 views30 pages

PC Unit Iv Notes

This document discusses structures in C programming. It begins by introducing structures and their components like structure definition, declaration, nested structures, self-referential structures, and pointers to structures. It then provides examples of important two mark questions related to structures, including defining structures, declaring and initializing structures, nested structures, unions, differences between structures and arrays, and more. It ends by listing some sample programs involving structures.

Uploaded by

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

PC Unit Iv Notes

This document discusses structures in C programming. It begins by introducing structures and their components like structure definition, declaration, nested structures, self-referential structures, and pointers to structures. It then provides examples of important two mark questions related to structures, including defining structures, declaring and initializing structures, nested structures, unions, differences between structures and arrays, and more. It ends by listing some sample programs involving structures.

Uploaded by

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

Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

UNIT IV

4.1: STRUCTURE INTRODUCTION

4.2: STRUCTURE DEFINITION

4.3: STRUCTURE DECLARATION

4.4: STRUCTURE WITHIN STRUCTURE

4.5: SELF-REFERENTIAL STRUCTURE

4.6: POINTERS-DEFINITION

4.7: POINTERS INITIALIZATION

4.8: POINTERS ARITHMETIC

4.9: POINTERS AND ARRAYS

4.10: POINTER TO FUNCTION

4.11: POINTER AND STRUCTURE

4.12:SIMPLE PROGRAMS

1
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

Important two marks

1. Define Structure in C. ( APR/MAY 2015)


C supports a constructed data type known as structures, a mechanism for packing
data of different types. A structure is a convenient tool for handling a group of logically
related data items. This is known as Structure.

2. Write the rules for declaring a structure.


• A structure must end with a semicolon.
• Usually a structure appears at the top of a program.
• Each element of structure must be terminated.
• The structure variable must be accessed by using dot (.) operator

3. Write the rules for initializing structure.


• The individual data members of structure cannot be initialized.
• The structure variables can be initialized at compile time only.
• The order of data members in a structure must match the order of values in enclosed
brackets.
• We can initialize only some of the data members of the structure.
• The uninitialized data members can be initialized by default with zero for int and float ‘\0’
for character and strings.

4. What is mean by nested structure?


It is otherwise known as structure within structure, i.e., a structure appear within another
structure. This is called nested structure.

5. Define Union in C. (Nov/Dec 2015,May-2019)


Union is also derived data types like as structure. All the members of union use the same
location, although a union may contain many members of different types. The keyword union
is used to declare union.

6. Write the features of Structure. (Jan. 2011)


The values of a structure variable can be assigned to another structure variable of the same
type using the assignment operator. It is not necessary to copy the structure elements.

7. How does a structure differ from an array? ( Jan 2010)


Arrays Structures
1. An array is a collection of 1. Structure can have elements of
related data elements of same different types
type.
2. An array is a derived data type 2. A structure is a programmer-
defined data type
3. Any array behaves like a built-in 3. But in the case of structure, first we
data types. All we have to do is to have to design and declare a data
declare an array variable and use structure before the variable of that
it. type are declared and used.

8. Give syntax for Structure declaration.


struct structure_name
{
Structure_member 1;
Structure_member 2;
…….
Structure_member n;
}; v1,v2,…,vn;

9. Write short notes on self referential structures.


2
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

Self referential structures are those structures that contain a reference to data of its
same type. That is it contains the pointer to the data that is of same type of as that of the
structure.
struct node
{
int val;
struct node *next;
};
Here the structure node will contain two types of data- an integer val and next that is a
pointer
to a node.

10. What is a pointer? List out the advantages of using pointer. (JAN-2016, MAY-
2015, MAY-2014,JAN-2013,MAY-2012, JAN 2010,May-2019)
A pointer is a special type of variable which holds the address or location of another
variable. It is declared in the same fashion like other variables but it is always denoted by ‘*’
operator.
Example:
int a, *p;
a=5;
Advantages: P=&a;
1. For accessing a variable that is defined outside the function.
2. For efficient handling of data tables.
3. For reducing the size and complexity of programs.
4. For increasing the execution speed.
5. For saving the storage space by using the pointer arrays for character stings.

11. Give an example where a structure data type may be required.


A Structure is a collection of one or more variables possibly of different data types
grouped together under a single name for convenient handling.
struct books
{
char book_name[50];
int pages;
float price;
}b1;

12. What is a user – defined data type? (MAY-2014)


C supports the features “typedef” that allows users to define the identifier which
would represent an existing data type. This defined data type can then be used to declare
variables:
Syntax:
typedef int numbers;
eg: numbers num1,num2;

In this example, num1 and num2 are declared as int variables.


The main advantage of user defined data type is that it increases the program’s readability.

Enumerated type:
This is also a user defined data type. “Enum” is the keyword and “identifier” is the user
defined data type that is used to declare the variables. It can have any value enclosed within
the curly braces.
Syntax:
enum identifier {value1,value2, value 3,…}
For example:
enum day {January,February,March,April,..};

3
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

enum day month_st,month_end;

13. Write about nested structure?(JAN-2014)

Nesting of structures are nothing but structure within another structure (i.e., a
structure can contain one or more structures embers).
A structure may be defined and/or declared inside another structure.
struct employee
{
int empno;
char name[15];
struct dob
{
int date ,
int month,
int year;
} d;
}emp;

14. What is the use of structure in C. (NOV 2011)


1. It is a complex data type declaration that defines a physically grouped list of variables
to be placed under one name in a block of memory, allowing the different variables to
be accessed via a single pointer, or the struct declared name which returns the same
address.
2. For increasing the execution speed.

15. Write the syntax for declaration and initialization of structures. (JAN 2011)
Syntax:
struct structure_name
{
data type data member1;

data type data member2;


.......
.......
data type data member n;
}structure variable={list of values};
Example:
struct student //declaration
{
int rno;
char name[20];
float cgpa;
}s={10,”amirtha”,95}; //initialization

16. What is a structure variable? (MAY 2013)


struct book_bank
{
char bname[50];
char author[50];
int pages;
float price;

4
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

}book1;
The members of a structure themselves are not variables. They do not occupy any
memory until they are associated with the structure variables such as book1. When the
compiler comes across a declaration statement, it reserves memory space for the structure
variables. It is also allowed to combine both the structure definition and variables declaration
in one statement.

17. Define array of pointers. (MAY 2013)


Array of pointers contain collection of address. The address may be the address of
variable or array elements. So far we have studied array of different standard data types such
as array of int, float, and character and so on.
In the same way the C language also supports array of pointers. It is nothing but a collection
of addresses. Here we store addresses of variables for which we have to declare an array as
a pointer.

18. Write a program using pointer to determine the length of a character strings?
main()
{
char *name;
int length;
char *cptr=name;
name=”DEHI”;
printf(“%s\n”,name);
while(cptr!=’\0’)
{
printf(“%c is stored at address %u\n”,*cptr,cptr);

cptr++;
}
length=cptr-name;
printf(“\nlength of the string=%d\n””,length);
}

19. What is a null pointer?


A pointer is said to be null pointer when its right value is 0.
A null pointer can never point to a valid data. For checking a pointer, if it is assigned to
0, then it is a null pointer and is not valid.
Example:
int *a;
int *b;
b=a=0;
Here b and a become null pointers after the integer value of 0 is assigned to them.

20. Explain Enumerated data type.

The enum is a keyword. It is used for declaring enumeration types. The programmer
can create his/her own data type and define what values the variables of these data types can
hold. This enumeration data type helps in reading the program.
Syntax:
enum tag{member1,member2,...........member n};

21. Define a C function to exchange the content of two variables. ( Jan.2009)


void exchange(int *a, int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
5
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

22. What are Pointers? (Jan 2011, Jan 2013)


A pointer is a variable that store a address of another variable. This is known as
pointer.
Eg. int *a,b=10;
b=&a;
a variable

b=10 value

1008 address

23. Define null pointer.


A pointer is a null pointer when its right value is 0. A null pointer can never point to a
valid data.
Eg. int *a;
int *b;
b=a=0; (these are all null pointer)

24. Give any two features of pointers. ( Jan 2011)


 Pointer reduces the length and complexity of the program
 Pointers are efficient way of handling data associated with arrays.

25. Write the advantages of using Pointers. (or) Uses of pointers. ( Jan 2012)
 Pointers are more compact and efficient code.
 Pointers can be used to achieve clarity and simplicity.
 Pointers are used to pass information between function and its reference point.
 Pointers enable us to access the memory directly.

26. Define Pointer to Pointer.

It is a variable that contains the address of another variable. Similarly another pointer
variable can store the address of this pointer variable. This is known as Pointer to Pointer.

27. Write the output of the following C program. (Jan 2005)


main()
{
int v=3;
int *pv;
pv=&v;
printf(“\n *pv=%d v=%d”, *pv, v);
*pv=5;
printf(“\n\n*pv=%d v=%d”, *pv,v);
}

Output is *pv=3 v=3


*pv=5 v=5
28. What are the operators exclusively used with pointers? ( Jan 2012)
i. *
ii. &
iii. .
iv. ->

29. What are an address operator and indirection operator? (NOV/DEC 2014,2015)

The address-of operator (&) gives the address of its operand.

6
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

The indirection operator (*) accesses a value indirectly, through a pointer. The operand must
be a pointer value. The result of the operation is the value addressed by the operand; that is,
the value at the address to which its operand points.

30. What is the output of the following program? (APR/MAY 2015)


main( )
{

int a=8,b=4,c *p1=&a , *p2=&b;

c=*p1 * p2 - *p1/*p2+9;

printf(“%d”,c);

31.How is pointer arithmetic done.(May/June 2016)


A pointer in C is a variable which is used to store the memory address which is a
numeric value. The arithmetic operations on pointer variable effects the memory address
pointed by pointer.
Example
int* i;
i++;
Note: pointer will be of 2 bytes. And when we increment it, it will increment by 2 bytes
because int is also of 2 bytes.

32. What is bit field and write its rule?


Bit field is used to hold data items. It helps in direct manipulation of string. The size of
bit field may be from 1 to 16 bits in length. The name and size of bit field are defined using
structure.

Rules for bit field


1. First field start with first bit of word.
2. Bit field do not overlap.
3. Sum of length of all fields in structure must not be greater than the size of word.
4. Bit field cannot be arrayed. Number of required bit field are determined using sizeof
operator.

PART – B Questions

1. EXPLAIN ABOUT STRUCTURE WITH EXAMPLE PROGRAM. (May 2017, Jan


2014,May-2019]
DEFINITION
It is a user defined data type. A structure is a collection of variables of different types
grouped together under a single name. By using structures we can make a group of variables,
arrays, pointers and etc..,

DECLARATION OF STRUCTURES
It contains data members and each is accessed by the structure variable. A structure
is declared using the keyword struct followed by a structure name. All the variables of the
structures are declared within the structure.

7
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

Syntax:
struct structure_name
{
structure_element 1;
structure_element 2;
Example:
--------
--------
structure_element n;
};struct structure_name v1,v2,…,vn;

struct student
{
int marks;
float avg;
char grade;
};

The structure definition does not allocate any memory. Structure provides a model of how
the structure is to be in memory and gives details of the member names. Memory is allocated
for the structure when we declare a variable of the structure.

struct student
{
int marks;
float avg;
char grade;
}s; // Declaring Structure Variable

Memory allocation for above structure is


2000 2001 2002 2003

int marks

float avg

avg grade
INITIALIZATION OF STRUCTURES
Initializing a structure means assigning some constants to the members of the structure. The
initializes are enclosed in braces and are separated by commas.
Example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}struct student stud1 = {01, “Rahul”, “IT”, 45000};

ACCESSING THE MEMBERS OF A STRUCTURE


8
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

Array elements are accessed using the Subscript variable, Similarly Structure members
are accessed using dot [.] operator. It is called as “Structure member Operator”. Use this
Operator in between “Structure name” & “member name”

Syntax:

struct_var.member_name;

Example:
stud1.rno = 01;
strcpy(stud1.name, “Kalam”);
stud1.course = “IT”;
stud1.fees = 45000;

Here the dot is an operator which selects a member from a structure.

Selecting a member from a structure pointer happens frequently, it has its own
operator -> which acts as follows. Assume that stud1 is a pointer to a structure of type
student we would refer to the name member as

stud1.rno->name

PROGRAM USING STRUCTURES TO READ AND DISPLAY THE INFORMATION ABOUT A


STUDENT

#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[80];
float fees;
char DOB[80];
};
int main()
{
struct student stud1;
clrscr( );
printf(“\n Enter the roll number : “);
scanf(“%d”, &stud1.rollno);
printf(“\n Enter the name : “);
scanf(“%s”, stud1.name);
printf(“\n Enter the fees : “);
scanf(“%f”, &stud1.fees);
printf(“\n Enter the DOB : “);
scanf(“%s”, stud1.DOB);
printf(“\n ********STUDENT’S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud1.rollno);
printf(“\n NAME. = %s”, stud1.name);
printf(“\n ROLL No. = %f”, stud1.fees);
printf(“\n ROLL No. = %s”, stud1.DOB);
getch( );
}

OUTPUT:
Enter the roll number : 101
Enter the name : rahul
Enter the fees : 45000
Enter the DOB : 11.2.1995
9
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

********STUDENTÆS DETAILS *******


ROLL No. = 101
NAME. = rahul
ROLL No. = 45000.000000
ROLL No. = 11.2.1995
2 DISCUSS ABOUT ARRAYS OF STRUCTURES WITH EXAMPLE. Nov 2016, May
2016, Jan 2016, May 2015, Jan 2013,May-2019)
ARRAYS OF STRUCTURES
An array of structures is the same way as we declare an array of built-in data type.
The array of structures can be used when common structure definition is need for the process
of information.

Syntax
struct struct_name struct_var[index];

Example
struct student stud[30];

Now, to assign values to the ith student of the class, we will write,
stud[i].r_no = 09;
stud[i].name = “RAM”;
stud[i].course = “CSE”;
stud[i].fees = 60000;

/*program to read and display information of all the students in the class*/(May-
2019)
#include<stdio.h>
#include<conio.h>
struct studentinfo
{
int roll;
char name[20];
int age;
};
void main()
{
struct studentinfo s[100];
clrscr();
int n,i;
printf("\nHow many students information do you want to enter?");
scanf("%d",&n);
printf("Enter Student Information:");
for(i=1;i<=n;i++)
{
printf("\nEnter Roll no.:");
scanf("%d",&s[i].roll);
printf("\nEnter the name of the student:");
scanf("%s",&s[i].name);
printf("\nEnter the age of the student:");
scanf("%d",&s[i].age);
}
printf("\n\nInformation of all studenst:");
for(i=1;i<=n;i++)
{
printf("\nRoll no.:%d",s[i].roll);
printf("\nName:%s",s[i].name);
10
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

printf("\nAge of student:%d\n\n",s[i].age);
}
getch( );
}

C permits the use of arrays as structure members. We have already used arrays of
characters inside a structure. Similarly, we can use single-dimensional or multidimensional
arrays of type int or float. For example, the following structure declaration is valid:
struct marks
{
int number;
float subject[3];
} student[2];

Here the member structure subject contains three elements, subject[0], subject[1],
subject[2]. These elements can be accessed using appropriate subscripts. For example, the
name, student[1].subject[2];

would refer to the marks obtained in the third subject by the second student.

Example: ARRAYS WITHIN A STRUCTURE

11
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

Univ. Ques. May 2014


main()
{
struct marks
{
int sub[3];
int total;
};
struct marks student[3] = {45,67,81,0,75,53,69,0,57,36,71,0};
struct marks total;
int i,j;

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


{
for(j = 0; j <= 2; j++)
{
student[i].total += student[i].sub[j];
total.sub[j] += student[i].sub[j];
}
total.total += student[i].total;
}
printf("STUDENT TOTAL\n\n");
for(i = 0; i <= 2; i++)
printf("Student[%d] %d\n", i+1, student[i].total);

printf("\nSUBJECT TOTAL\n\n");
for(j = 0; j <= 2; j++)
printf("Subject-%d %d\n", j+1, total.sub[j]);

printf("\nGrand Total = %d\n", total.total);

}
Output:
STUDENT TOTAL
Student[1] 193
Student[2] 197
Student[3] 164

SUBJECT TOTAL
Subject-1 177
Subject-2 156
Subject-3 221

Grand Total = 554

3. EXPLAIN ABOUT STRUCTURE WITHIN STRUCTURE WITH EXAMPLE PROGRAM.

[ Univ. Ques. Jan 2016, May 2015, Jan 2015, May 2013]

NESTED STRUCTURES
A structure can be placed within another structure. That is, a structure may contain
another structure as its member. Such a structure that contains another structure as its
member is called a nested structure.

12
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

Example:
/*Program to read and display the information of student using nested
Structure*/
#include<stdio.h>
#include<conio.h>
struct DOB
{
int day;
int month;
int year;
};

struct student
{
int roll_no;
char name[100];
float fees;
struct DOB date;
};

int main( )
{

struct student stud;


clrscr( );
printf(“\n Enter the roll number : “);
scanf(“%d”, &stud.roll_no);
printf(“\n Enter the name : “);
scanf(“%s”, stud.name);
printf(“\n Enter the fees : “);
scanf(“%f”, &stud.fees);
printf(“\n Enter the DOB : “);
scanf(“%d %d %d”, &stud.date.day,&stud.date.month,&stud.date.year);
printf(“\n ********STUDENT’S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud.roll_no);
printf(“\n NAME. = %s”, stud.name);
printf(“\n FEES. = %f”, stud.fees);
printf(“\n DOB = %d - %d - %d”, stud.date.day, stud.date.month,stud.date.year);
getch( );
}

OUTPUT:

Enter the roll number : 101


Enter the name : rahul
Enter the fees : 45000
Enter the DOB : 11.2.1995

********STUDENTÆS DETAILS *******


ROLL No. = 101
NAME. = rahul
ROLL No. = 45000.000000
ROLL No. = 11.2.1995

4. STRUCTURE AND FUNCTIONS


Univ. Ques. May 2014, May 2013

13
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

Similar to arrays and pointers a structure can also be passed to a function. There are
three ways of passing a structure to a function.
They are;

1. Passing a structure member to functions.


2. Passing the address of member to functions.
3. Passing entire structure to functions.

1. PASSING A STRUCTURE MEMBER OF FUNCTIONS

 This method is used to pass each member of the structure as an actual argument
of the function call statement.

 When you pass a member of a structure to a function as an argument, you are


actually passing the value of that member to the function.

 The arguments are then treated independently as ordinary variables.

 For example;

struct employee
{
int empno;
char empname[20];
float salary;
} emp;

 The member of the structure can be passed to the function employ() as

 employ(emp.empno)
 employ(emp.empname)
 employ(emp.salary);

 Where employ(emp.empno) passes the integer value of empno to the function


employ().

 Employ(emp.empname[1]) passes the character value empname to the function


employ().
 Similarly employ(emp.salary) passes the float value of salary to the function employ().

 This method is the most common method and becomes inefficient when the structure
is large.

2. PASSING THE ADDRESS OF MEMBER TO FUNCTIONS

 The member of a structure can also be passed to function by passing the address
of the members.

 In this, a method the address location of the members is passed to the called
function, hence the address operator (&) is used before the structure name.

 The member of the structure can be passed to a function employ() as

employ(&emp.empno); // passes the address of integer value of empno


to the function employ().
employ(&emp.salary);

employ(&emp.empname); // note that the address operator is not


used since
the variable empname is a string.
14
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

3. PASSING ENTIRE STRUCTURE TO FUNCTIONS

In this method, the entire structure is passed as an argument to the function, since
the function is working on a copy of the structures, any changes made to the structure
members within the function are not reflected in the original structure. Therefore, it is
necessary for the function to return the entire structure back to the calling function.
Example: /* Function struct.c */

#include<stdio.h>
void employ(struct employee emp);
struct employee
{
int empno;
char empname[20];
};
main()
{
struct employee emp1;
printf(“\nEnter Employee No. and Name : “);
scanf(“%d%s”,&emp1.empno,emp1.empname);
employ(emp1);
}
void employ(struct employee emp)
{
printf(“\nThe Employee No. is : %d”, emp.empno);
printf(“\nThe Employee Name is : %s”, emp.empname);
}

OUTPUT:

Enter Employee No. and Name : 101 David


The Employee No. is : 101
The Employee Name is : David

Example: STRUCTURES AS FUNCTION PARAMETERS


/* Passing a copy of the entire structure */
struct stores
{
char name[20];
float price;
int quantity;
};
struct stores update (struct stores product, float p, int q);
float mul (struct stores stock);
main()
{
float p_increment, value;
int q_increment;

struct stores item = {"XYZ", 25.75, 12};

printf("\nInput increment values:");


printf(" price increment and quantity increment\n");
scanf("%f %d", &p_increment, &q_increment);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
item = update(item, p_increment, q_increment);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

15
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

printf("Updated values of item\n\n");


printf("Name : %s\n",item.name);
printf("Price : %f\n",item.price);
printf("Quantity : %d\n",item.quantity);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
value = mul(item);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
printf("\nValue of the item = %f\n", value);
}
struct stores update(struct stores product, float p, int q)
{
product.price += p;
product.quantity += q;
return(product);
}
float mul(struct stores stock)
{
return(stock.price * stock.quantity);
}
Output:
Input increment values: price increment and quantity increment
10 12
Updated values of item
Name : XYZ
Price : 35.750000
Quantity : 24
Value of the item = 858.000000

5. SELF-REFERENTIAL STRUCTURES(Pointers and Structure)

Self referential structures are those structures that contain a reference to data of its
same type. That is, a self referential structure in addition to other data contains a pointer to
a data that is of the same type as that of the structure. For example, consider the structure
node given below.

struct node
{
int item;
struct node *next;
};

Here the structure node will contain two types of data- an integer item and next that is a
pointer to a node. Self-referential structure is the foundation of other data structures. They
are most commonly used in linked list data structure implementation

Example:
#include <stdio.h>
#include<conio.h>
struct stud
{
int roll;
char name[30];
int age;
struct stud *next; // self reference
structure
}
16
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

void main()
{
struct stud n1, n2, n3;
struct stud *p;
clrscr( );
printf("Enter the details of students");
scanf ("%d %s %d", &n1.roll, n1.name, &n1.age);
scanf ("%d %s %d", &n2.roll, n2.name, &n2.age);
scanf ("%d %s %d", &n3.roll, n3.name, &n3.age);
n1.next = &n2; //assigning address of the structure
n2.next = &n3;
n3.next = NULL;
p = &n1; /* point to 1stelement */
printf(“\n The students details are:”);
while (p != NULL)
{
printf ("\n %d %s %d", p->roll, p->name, p->age);
p = p->next;
}
getch( );
}
OUTPUT:
Enter the details of students
101 ram 19
102 raj 19
103 rahul 18
The students details are:
101 ram 19
102 raj 19
103 rahul 18
15
Explanation:
The list consists of three nodes n1, n2 and n3 by declaring struct stud n1, n2, n3. To create
the links between nodes, we write n1.next = &n2; n2.next = &n3; By pointing the address
of the first element, and while loop we can traverse through the nodes and display the
student details.

6. SIZE OF STRUCTURES
We normally use structures, unions and arrays to create variables of large sizes. The
actual size of these variables in terms of bytes may change from machine to machine. We
may use the unary operator sizeof to tell us the size of a structure (or any variable). The
expression
sizeof(struct x)
we evaluate the number of bytes required to hold all the members of the structure x. If y is a
simple structure variable of type struct x, then the expression
sizeof(y)
would also give the same answer. However, if y is an array variable of type struct x, then
sizeof(y)
would give the total number of bytes the array y requires.
This kind of information would be useful to determine the number of records in a
database. For example, the expression
sizeof(y)/sizeof(x)
would give the number of elements in the array y.
17
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

7. BIT FIELD

 Bit field is used to hold data items. It helps in direct manipulation of string.
 The size of bit field may be from 1 to 16 bits in Length.
 The name and size of bit field are defined using structure.

General Form struct tag_name


{
data-type member1;size;
data-type member2;size;
……………………………………………
……………………………………………
data-type memberN;size;
};
Description data type - may be int or unsigned int or signed int.
Size - is the number of bits used for specified name.
Member and size - are separated by semi colon.

Rules for Bit Field

First field start with first bit of word.


Bit Field do not overlap.
Sum of length of all fields in structure must not be greater than the size of word.
Bit field cannot be arrayed. Number of required bit field are determined using sizeof operator.

Example: C Program to demonstrate Bit field


#include<stdio.h>
#include conio.h>

#define FAIL 0
#define PASS 1
#define A 1
#define B 2
#define C 3
main()
{
Struct std
{
Int rno;
unsigned result : 1;
unsigned grade : 2;
};
struct std s;
s.rno=9207;
s.result=PASS;
s.grade=A;
clrscr();
printf(“Roll Number....%d\n”, s.rno”);
printf(“Results.....%d\n”, s.result”);
printf(“Grade....%d\n”, s.grade”);
s.rno=9207;
s.result=PASS;
s.grade=B;
printf(“Roll Number....%d\n”, s.rno”);

18
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

printf(“Results.....%d\n”, s.result”);
printf(“Grade....%d\n”, s.grade”);
s.rno=9207;
s.result=PASS;
s.grade=C;
printf(“Roll Number....%d\n”, s.rno”);
printf(“Results.....%d\n”, s.result”);
printf(“Grade....%d\n”, s.grade”);
}
Output:
Roll Number...9207
Results............1
Grade..............1
Roll Number...9382
Results............1
Grade..............1
Roll Number...9556
Results............1
Grade..............3

8. USER –DEFINED DATA TYPES

TYPEDEF

C provides a capability that enables the programmer to assign an alternate name


to a data-type. This is done with a statement known as typedef.

Syntax: typedef type dataname;


Description typedef - keyword.
type – data-type
dataname – specifies the user defined name for that type.
Example: typedef int weeks;
(Here weeks is the another name for int)

EXAMPLE PROGRAM FOR TYPEDEF:

Example: C Program to create user defined data type weeks on int data type
and used it in the program.

19
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

#include<stdio.h>
#define D 7
void main
{
typedef int weeks;
weeks wk;
printf(“Enter weeks: ”);
scanf(“%d”, &wk);
printf(“Number of days = %d”, wk*D);
}

Output:
Enter weeks: 4
Number of days = 28

ENUMERATED DATA TYPE:


 The enumerated data type is a user-defined data type.
 An enumeration is a set of named integer constants represented by identifier that
specifies all the legal values a variable of that type may have.
 Enumerated data type is declared using the enum keyword.

Syntax: enum tag{ member1, member2, …...member n };

Example: enum months{ January, February, march……December};

 enum is the key word,


 tag is the name that identifies enumeration having the
Description composition in the format.
 member1, member2, …...member n are the individual
identifiers (known as enumeration constants) that may
be assigned to the variables of this type.

9. POINTERS May 2016, May 2014, Jan 2013


INTRODUCTION
The Pointer is a variable that store the address of the another variable. Pointers can be
used to access and manipulate data stored in the memory. This is known as Pointers.

It is a derived data type in C language.


Syntax:
data_type *Pointer_varaible;

Example:
int *a;
float *b;

20
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

char *c;

Explanation
int rno=40;

rno Variable

40 Value

2005 Address

Let as assume that the system has assign the address location as 2005 for a variable ‘sno’.

FEATURES OF POINTERS
 Pointers are efficient in handling data.
 Pointers are used for saving memory space.
 Pointers reduce the length and complexity of the program.
 The execution time is faster.
ADVANTAGES OF POINTERS
 Pointers are more compact and efficient code.
 Pointers can be used to achieve clarity and simplicity.
 Pointers are used to pass information between function and its reference point.
 Pointers enable us to access the memory directly.

ACCESSING VARIABLE THROUGH POINTERS (2 Mark)


Once the pointer is declared and assigned to the address of another variable, the
variable can be accessed through its pointers. This is done by using another unary operator *
(asterisk), usually known as the indirection operator or dereferencing operator.
Example:
int *a;
b=25;
a=&x;
Here, ‘a’ is a pointer variable that store address of ‘b’ variable.
Program:

#include<stdio.h>
#include<conio.h>
main ( )
{
int a=22, int *a;
clrscr();
a=&a;
printf ("\n Value of a=%d", *a);
printf ("\n Address of a=%u", &a);
printf ("\n Value at address %u=%d", &a, *(&a));
}

Output:
Value of a=22
Address of a=4000
value at address 4000=22

INITIALIZING POINTER VARIABLE

21
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

The process of assigning the address of a variable to a pointer variable is known as


initialization. The ampersand (*) is an address operator, which is used to access the address
of a variable and assign it to a pointer to initialize it.
Example:
P=&n;
Where ‘p’ contains the address of variable ‘n’.

10. POINTERS AND ARRAYS Jan 2016, May 2013,14

When users declare an array the consecutive memory locations are located to the
array of elements. The elements of an array can be efficiently accessed by using pointers.
Example:
int a[5]={10,20,30,40,50};

Here, ‘a’ has 5 elements.

a[0] a[1] a[2] a[3] a[4] array

10 20 30 40 50 value

2000 2002 2004 2006 2008 address

 The base address of the array starts with 0 th element of the array. The array is in
integer type.
 The integer will have 2 bytes.
 The address of the next address element is incremented by 2.
Program:

/* Program to add the sum of number using pointer * / (AU-MAY/JUNE 2014)

#include<stdio.h>
main( )
{
int i,total,a[5],*c;
for(i=0;i<5;i++)
{
printf("\nEnter the number %d:”,i+1);
scanf("%d",&a[i]);
}
c=a;
for(i=0;i<5;i++)
{
total=total+*c;
c=c+1;
}
printf("\n Total=%d",total);
}

Output:
Enter the number 1:10
Enter the number 2:20
Enter the number 3:30
Enter the number 4:40
Enter the number 5:50

22
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

Total=150

NULL POINTER
A Pointer is said to be a null pointer when its right value is 0.
Example:

int *a;
int *b;
b=a=0;

11. POINTERS TO POINTERS


In general, pointer is a variable that contains the address of another variable.
Similarly, another pointer variable can store the address of this pointer variable. This is a
pointer to pointer variable.

Pictorial Representation

Note:

 ‘p1′ is the address of ‘p2′ ie 5000


 ‘*p1′ is the value held by ‘p2′ ie 8000
 ‘**p1′ is the value at 8000 ie ‘c’

Example:
int a=20;
int *b;
int **c;
b=&a;
c=&b;
Program:
#include<stdio.h>
main()
{
int a=20, int *b;
int **c;

23
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

b=&a;
c=&b;
printf(“Value of a is %d\n”,a);
printf(“Value of a is %d\n”,*(&a));
printf(“Value of a is %d\n”,*b);
printf(“Value of a is %d\n”,**c);
printf(“Value of b and address of a=%u\n”,b);
printf(“Address of a is %u”,&a);
printf(“Address of b is %u”,&b);
printf(“Address of a is %u”,*c);
printf(“Address of b is %u”,&b);
printf(“Address of b is %u”,c);
printf(“Address of c is %u”,&c);
getch();
}
Output:
Value of a is 20
Value of a is 20
Value of a is 20
Value of a is 20
Value of b and address of a=2005
Address of a is 2005
Address of b is 2005
Address of a is 2005
Address of b is 2005
Address of b is 2005
Address of c is 2005

POINTERS AND STRINGS


A character pointer is a pointer to the character. It can be declared as

Syntax:
char *pointer_character;

A character pointer can also be used to access character arrays and string constants,
in the same way as accessing numeric arrays using their respective pointer variable.

12. POINTER EXPRESSIONS

Pointer variables can be used in expressions. As a user, we can use integer for addition and
subtraction from pointers.

Here, the pointers are preceded by the * symbol (Indirection Operator).

Example:

(i) c=*a+*b; it can be written as c=(*a)+(*b);


(ii) s=20*-*a/*b; it can be written as s=(20*(-(*a)))/(*b);
(iii)*p=*a**b; it can be written as *p=(*a)**b;
(iv)*a=*a+15; it can be written as (*a)+=15;

Another Example:

*++c; it is interpreted as *(++c);


24
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

*c++; it is interpreted as *(c++);


d=*(c++); it is equivalent to d=*c; c=c+1;

13. POINTERS AND FUNCTIONS


The Pointer can be used as an argument in functions. The arguments (or) parameters to the
function are passed in two ways. They are given below.

(i) Call by value.


(ii) Call by reference.

In the above two method, especially ‘call by reference’ is used to achieve the technique of
‘Pointers and Functions’

POINTERS AND FUNCTION ARGUMENTS

 The calling function sends the addresses of the variables and the called function must
declare those incoming arguments as pointers.
 In order to modify the variables sent by the caller, the called function must
dereference the pointers that were passed to it.
 Thus, passing pointers to a function avoid the overhead of copying data from one
function to another.
 This Process is otherwise called as Call by reference.

Program ( APR/MAY 2015,MAY/JUNE 2014)

#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main( )
{
int x,y;
clrscr();
printf("Enter the values of a & b\n");
scanf("%d%d",&a,&b);
swap(&a,&b);
printf("A=%d \n B=%d",a,b);
getch( );
}
void swap(int *px,int *py)
{
int pz;
pz=*px;
*px=*py;
*py=pz;
}

14. POINTER AND STRUCTURE


Univ. Ques. Jan 2014

Pointer which point structure in the same way as used with the other variable are
called Structure pointers.

25
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

General Form struct tag


{
member1;
member2;
………………
………………
membern;
};
struct tag*ptrvar;
Description tag - name to structure.
ptrvar - pointer variable.
() - Members of structure are accessed using the Arrow Operator.

Example: struct book_list


{
char book_name;
int pages;
float price;
};
struct book_list*ptr;

Example:
Program to declare pointer to structure and display the contents of the
structure
#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
char name[25];
char author[25];
int pages;
};
struct book b1={“Computer Programming”, “Kamthane”, 479};
struct book 8ptr;
ptr=&b1;
clrscr();
printf{“\n %s by %s of %d pages”, b1.name, b1.author, b1.pages};
printf{“\n %s by %s of %d pages”, ptr->name, ptr->author, ptr->pages};
}
OUTPUT:
Computer Programming by Kamthane of 479 pages

Computer Programming by Kamthane of 479 pages

26
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

Important program

1. Write a C program that gets and displays the report of n students with their personal
and academic details using structures. (, Jan
2010,May/June 2016)

#include<stdio.h>
#include<conio.h>
struct student
{
int rollno,mark1,mark2,mark3,total;
char name[25],grade;
float avg;
}s[50];

main()
{
int i,n;
clrscr();
printf("\nEnter number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter roll number:");
scanf("%d",&s[i].rollno);
printf("Enter name:");
scanf("%s",s[i].name);
printf("Enter mark 1:");
scanf("%d",&s[i].mark1);
printf("Enter mark 2:");
scanf("%d",&s[i].mark2);
printf("Enter mark 3:");
scanf("%d",&s[i].mark3);
s[i].total=s[i].mark1 + s[i].mark2 + s[i].mark3;
s[i].avg=s[i].total/3;
if(s[i].avg>=75)
{
s[i].grade='S';
}
else if((s[i].avg<75)&&(s[i].avg>=60))
{
s[i].grade='A';
}
else if((s[i].avg<60)&&(s[i].avg>=50))
{
s[i].grade='B';
}
else
{
s[i].grade='C';
}
}
printf("Students details\n");
printf("Roll no Name Mark1 Mark2 Mark3 Total Avg Grade\n");
for(i=0;i<n;i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \t %f \t %c \n",
s[i].rollno,s[i].name,s[i].mark1,s[i].mark2,s[i].mark3,s[i].total,s[i].avg,s[i].grade);
}
getch();
}
27
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

OUTPUT
Enter the number of student: 2
Enter roll number: 1
Enter name: Ram
Enter mark1: 50
Enter mark2: 60
Enter mark3: 80
Enter roll number: 2
Enter name: Lakshman
Enter mark1: 98
Enter mark2: 86
Enter mark3: 95

Roll no Name Mark1 Mark2 Mark3 Total Avg Grade


1 Ram 50 60 80 190 63.000000 A
2 Laksh 98 86 95 279 93.000000 S

2. Write a C program to accept records of 20 states using arrays of structures. The


structure should contain name of the state and no. of Engineering College, medical
colleges, management colleges, science colleges, calculate and display the total colleges
in each state and the state which is having no. of colleges.
(Jan 2012) & (May/June 2010)

#include<stdio.h>
#include<conio.h>
strcut state
{
char sname[15];
int nec,nmc,nmgc,nsc,total;
}s[20];

main()
{
int i,highest=0;
char shigh[15];
clrscr();

for(i=1;i<=20;i++)
{
printf(“Enter state name:”);
scanf(“%s”,s[i].sname);
printf(“Enter no. Of Engg.colleges:”);
scanf(“%d”,&s[i].nec);
printf(“Enter no. Of medical colleges:”);
scanf(“%d”,&s[i].nmc);
printf(“Enter no. Of Management colleges:”);
scanf(“%d”,&s[i].nmgc);
printf(“Enter no. Of science colleges:”);
scanf(“%d”,&s[i].nsc);
}
printf(“Total colleges in each state\n”);
for(i=1;i<=20;i++)
{
s[i].total=s[i].nec+s[i].nmc+s[i].nmgc+s[i].nsc;
printf(“\n%s,%d”,s[i].sname,s[i].total);
if(s[i].total>highest)
{
highest=s[i].total;
28
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

strcpy(shigh,s[i].sname);
}
}
printf(“\nThe state which is having highest no. Of colleges\n”);
printf(“State Name:%s\n”,shigh);
printf(“Total no. Of colleges:%d\n”,highest);
}

UNIVERSITY QUESTIONS

Part –A
1. What is a self-referential structure? Give example. (JAN-2016)
2. What is a pointer? List out the advantages of using pointer. (JAN-2016, MAY-2015, MAY-
2014,JAN-2013,MAY-2012, JAN 2010)
3. Give an example where a structure data type may be required.

4. What is a user – defined data type? (MAY-2014)


5. Write about nested structure?(JAN-2014)
6. What is the use of structure in C. (NOV 2011)
7. Write the syntax for declaration and initialization of structures. (JAN 2011)
8. What is a structure variable? (MAY 2013)
9. Define array of pointers. (MAY 2013)
10. What is bit field and write its rule?
11. Write a program using pointer to determine the length of a character strings?
12. What is a null pointer?
13. Explain Enumerated data type.

Part –B

1.Write the syntax of structure declaration in C Program give an example .Distinguish


between structure and union [May -2017 ]
2.Write a c program to find the addition and subtraction 3x3 matrices [May-2017]
3. Define a data structure for a student record which contains name,age and marks
Develop program to read data for 10 students in a class and list then rank-wise [Nov-
2016,Apr/May-2016,Apr/may-2014]
4.Explain in detail about [Jan-2016]
a)Nested structure
b)Array of structure with an example program for each.
5.Explain in detail about [Jan-2016 ]
a)Pointer to an array [ May-2013]
b)array of pointer with an example program for each
6.Elucidate the concept of nested structure with an example program [May-2015,May-
2013]
7.Write a C program to swap two numbers using pointers [May-2015]
8.Write a C Program to print mark sheet of n students using structures [May-2015]
9.Write a C Program using pointer to read two matrices and print their product.[Jan-
2016 ]
10.Explain structure and function with example program. [ Apr/may -2014]

29
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C

11.What is pointer ? How to declare a pointer variable ? [ Apr/may -2014]


12. Compare arrays with structure ? [ Jan-2014 ]
13.Describe the rules for initializing structure . [ Jan-2014 ]
14.Describe about array of pointer. [ Jan-2014 ]
15.Write a program to illustrate the use of structure pointers . [ Jan-2014 ]

30

You might also like