Professional Documents
Culture Documents
Unit – IV
Structures – Arrays and Structures – nested structures – passing structures to functions – user
defined data types– Union Pointers – pointers and arrays – pointers and functions - pointers and
strings - pointers and structures.
1
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
PART-A
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
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
8. What are the advantages of union over structure? ( Jan. 2010) (0R) State the importance of union.(
MAY/JUNE 2016)
All the members use the same memory space to store the values.
Keyword union is used.
Only its first members may be initialized.
Different interpretation for the same memory location is possible.
Conversion of memory is possible.
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.
12.What is a pointer? List out the advantages of using pointer. (JAN-2016, MAY- 2015, MAY-2014,JAN-
2013,MAY-2012, JAN 2010)
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:
3
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
Advantages:
For accessing a variable that is defined outside the function.
For efficient handling of data tables.
For reducing the size and complexity of programs.
For increasing the execution speed.
For saving the storage space by using the pointer arrays for character stings.
14.Compare structure and union. (MAY-2016, MAY-2014, JAN-2013, JAN 2011, JAN 2010)
4
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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,..}; enum day month_st,month_end;
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;
20. Write the syntax for declaration and initialization of structures. (JAN 2011) Syntax:
struct structure_name
{
data type data member1;
5
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
Example:
struct student //declaration
{
int rno;
char name[20]; float cgpa;
}s={10,”amirtha”,95}; //initialization
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.
24. 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);
}
6
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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.
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};
31. 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.
7
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
38. What is difference between library function and user-defined function? (Jun12)
Library functions are the functions which are already written in some standard libraries.
User defined function means the function which are written by the user to perform particular task.
35. What are the operators exclusively used with pointers? ( Jan 2012)
i. *
ii. &
iii. .
iv. ->
36. What are an address operator and indirection operator? (NOV/DEC 2014,2015)
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.
8
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
PART-B
STRUCTURES AND UNIONS
STRUCTURE WITH EXAMPLE PROGRAM. (May 2017, Jan 2014]
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..,
Use of Structures:
Help to organize Complex data in a meaningful way.
Declaring a Structure:-
Structure is declared using the keyword ‘struct’ followed by a ‘tag’ and is enclosed by curly open ‘{’
and close ‘}’ braces. All members of a structure are specified within curly braces { }.
The general form for defining a structure is:
struct tagname
{
data-type member1;size;
data-type member2;size;
…………………………
data-type memberN;size;
};
Here tag refers to the name of the structure. Member1, member2, ---- Member N are elements of a
structure. Structure is terminated with semicolon (;). Initialization is not allowed within a structure.
Example 1:
struct lib_books
{
char title [20];
char author [15];
int pages;
float price;
};
9
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
Structure variable is declared using keyword ‘struct’ followed by structure name and structure
elements name. All structure elements name are separated by commas. Structure variable declaration
is terminated with semicolon (;).
The syntax is
struct tagname variable1, variable2, ... ... variable
m;
Here struct is a keyword. Tag specifies the name of the structure.
For Example, the statement
Struct lib_books, book1, book2, book3; declares book1, book2, book3 as variables of type struct
lib_books.
struct lib_books
{
char title [20];
char author [15];
int pages;
float price;
};
struct lib_books book1, book2, book3;
Defining a structure
Defining a structure means creating a variable to access members of structure. Creating structure
variable allows sufficient memory space to hold all the members of structure.
Syntax:
struct tagname
{
data-type member1;
data-type member2;
……………………
data-type member-n;
}structure variable(s);
structure_variable.member_name;
10
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
STRUCTURE INITIALIZATION
Structure variable can be initialized at compile time. The storage class must be static. Structure
initializer must be enclosed within curly braces. The order of structure and structure member must be
the same.
For example
main ()
{ struct class
{
int weight;
float height;
};
struct class student = {70, 170.82};
--------------
--------------
}
This assigns the value 70 to student.weight and 170.82 to student.height. There is one-to-one
correspondence between the members and their initializing values.
The following statements initialize two structure variables. Here it is essential to use tag name.
main ()
{
struct stud_record
{
int weight;
float height;
}
struct stud_record student1 = {70, 170.82};
struct stud_record student2 = {60, 155.62};
--------------
--------------
}
Example Program:
#include<stdio.h>
#include<conio.h>
struct stud
{ OUTPUT:
char name [20]; Name is Ajay
Register Number is 100
long int regno;
Name is Arun
} s3; Register Number is 101
Name is Ajay
Register Number is100
11
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
void main()
{
struct student s1= {“Ajay”, 100};
struct student s2= {“Arun”, 101};
printf(“\n Name is %s”, s1.name);
printf(“\n Register Number is %d”, s1.regno);
printf(“\n Name is %s”, s2.name);
printf(“\n Register Number is %d”, s2.regno);
s3=s1;
printf(“\n Name is %s”,s3.name);
printf(“\n Register Number is %d”, s3.regno);
getch();
}
ARRAYS OF STRUCTURES WITH EXAMPLE. Nov 2016, May 2016, Jan 2016, May 2015, Jan
2013
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 1:
struct class student [100];
defines an array called student that consists of 100 elements. Each element is defined to be of the type
struct class.
Example 2:
struct information
{
int id_no;
char name [20];
char address[20];
int age;
}
student[100];
OUTPUT:
Enter the number of students 2
12
Enter id_no, name, address, age 143
raja
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
13
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
int house_rent_allownace;
int city_allownace;
}employee;
This structure defines name, department, basicpay and some allowances. We can group all the
items related to allowance together and declare them under a substructure as shown below.
struct emp
{
char name;
char department;
struct salary
{
int dearness_allowance;
int house_rent_allownace;
int city_allownace;
}allowance;
}employee;
This salary structure contains a member named allowance, which itself is structure with three
members. The members contained in the inner structure namely dearness, house_rent ant city can be
referred as
employee.allowance.dearness
employee.allowance.house_rent
employee.allowance.city
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);
14
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
OUTPUT:
15
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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.
#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:
16
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
17
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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
}
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)
{
18
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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.
BIT FIELD
19
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
• 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.
20
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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
#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
21
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
• 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.
A union is a special data type available in C to store different data types in the same memory
location.
We can define a union with many members, but only one member can contain a value at a time.
Unions provide an efficient way of using the same memory location for multi-purpose.
DEFINITION
Defining a union, is very similar as like defining structure but keyword union is used. The
union statement defines a new data type, with more than one member for your program.
Each member definition is a normal variable definition, such as int i; or float f; or any other valid
variable definition.
At the end of the union's definition, before the final semicolon, union variables are declared.
22
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
Example:
union sample
{
int marks;
float avg;
char grade;
};
Now, a variable of sample type can store an integer, a floating-point number, or a string of characters.
This means that a single variable ie. same memory location can be used to store multiple types of
data.
We can use any built-in or user defined data types inside a union based on requirement.
In Union
23
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
#include <string.h>
union student
{
int i;
float f;
char str[20];
};
int main( )
{
union student data;
printf( "Memory size occupied by data : %d\n", sizeof(data)); return 0;
}
#include <stdio.h>
#include <conio.h>
union number
{
int n1; float n2;
}union number x;
void main()
{
clrscr() ;
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 =%d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%d", &x.n2);
printf("Value of n2 = %d\n",x.n2);
24
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
}
Output:
Enter the value of n1:10
Value of n1 =10
Enter the value of n2:20.5
Value of n2 =20.50000
Defining Union
If we define it as union like
union book
{
char name;
int pages;
float price;
};
The compiler allocates a piece of storage that is large enough to store the largest variable types in
union. All three variables will share the same address and 4 bytes of memory is allocated to it.
#include <stdio.h>
#include<conio.h>
union job
{
//defining a union char name[32];
float salary;
int worker_no;
}u;
25
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
struct job1
{
char name[32];
float salary;
int worker_no;
}s;
int main()
{
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
return 0;
}
Output
size of union = 32
size of structure = 40
Explanation:
There is difference in memory allocation between union and structure as suggested in above
example. The amount of memory required to store a structure variables is the sum of memory size of all
members.
But, the memory required to store a union variable is the memory required for largest element of
an union.
Example:
int *a;
float *b;
char *c;
26
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
Explanation
int rno=40;
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.
Output:
Value of a=22
Address of a=4000
value at address 4000=22
27
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
Example:
P=&n; Where ‘p’ contains the address of variable ‘n’.
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};
The base address of the array starts with 0th 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 * /
Output:
Enter the number 1:10
Enter the number 2:20
28
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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;
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; i
nt **c;
b=&a;
c=&b;
Program:
#include<stdio.h>
main()
{
int a=20, int *b;
int **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);
29
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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
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.
POINTER EXPRESSIONS
Pointer variables can be used in expressions. As a user, we can use integer for addition and
subtraction from pointers.
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:
In the above two method, especially ‘call by reference’ is used to achieve the technique of
30
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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.
31
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
IMPORTANT PROGRAMS
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();
32
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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
33
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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;
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
34
MVIT UNIT-IV T106 COMPUTER PROGRAMMING
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 ]
6. Define Structures. With an example, explain structures in detail.(Nov 2018)
7. List out the features of Pointers. Write a C program to multiply two numbers using Pointers.
(Nov 2018)
8. (a) Define Structures with its general form. (3)
(b) Explain how Structures are different from Arrays. Justify using suitable example. (8)
9. Write a program in C using structures to store student details and printing the same for five
students.
35