You are on page 1of 35

MVIT UNIT-IV T106 COMPUTER PROGRAMMING

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. 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)


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. Differentiate: Structure and Union. ( Jan 2011)

7. 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.

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.

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

10.Give syntax for Structure declaration.


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

11.Write short notes on self referential structures.

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.

13. Give the applicability of union in programming. (MAY 2017)

 Union is a derived data type


 Used to conserve memory.
 Same memory shared by two or more variables.
 Variables that share memory location differ in data types.

14.Compare structure and union. (MAY-2016, MAY-2014, JAN-2013, JAN 2011, JAN 2010)

15.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;

16. 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.

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;

17. Define Union? (JAN 2014)


Unions are same as structures except that they differ in storage. Unions have members of
different data types. All the members of a union share the same storage area within the memory. At any
time only one value can be stored.
union exam
{
introll_no;
char name[15];
int mark1,mark2,mark3;
};

18. 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;

19. 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.

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

data type data member2;


.......
.......

5
MVIT UNIT-IV T106 COMPUTER PROGRAMMING

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

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


struct book_bank
{
char bname[50]; char author[50]; int pages;
float price;
}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.

22. 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.

23. 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.

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

25. 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.

26. 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};

27. 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;
}

28. 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

29. 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)

30. 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.

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

32. 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.

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.

39. 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

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 address-of operator (&) gives the address of its operand.

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.

37. 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) ;
}

38. 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.

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;
};

Example 2: struct name _details


{
char name [20];
int day;
char month[10];
int year;
float salary;
};

 Declaring a structure variable:

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);

 Accessing structure members:


 We can access and assign values to the members of a structure in a number of ways. As mentioned
earlier the members themselves are not variables. They should be linked to the structure variables in
order to make them meaningful members.
 Members in a structure are accessed using the Period Operator ‘.’. Period Operator establishes a link
between member and variable name. Structure members are accessed by using a variable name
with period operator ‘.’ and member name. Period Operator is also known as member operator
or dot operator.
The syntax for accessing structure members is

structure_variable.member_name;

Members of a structure vary in type and size.

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];

Example Program: Printing Student Details

OUTPUT:
Enter the number of students 2
12
Enter id_no, name, address, age 143
raja
MVIT UNIT-IV T106 COMPUTER PROGRAMMING

#include< stdio.h >


#include<conio.h>
main ()
{
struct info
{
int id_no;
char name [20];
char address[20];
int age;
}
struct info std [100];
int i,n;
printf(“Enter the number of students”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“ Enter id_no, name, address, age\n”);
scanf(%d%s%s%d”, &std[i].id_no, std[i].name, std[i].address, &std[i].age);
}
printf(“\n Id Number And Name of the students ”);
for(i=0;i<n;i++)
printf(“%d%s \n”, std[i].id_no, std[i].name);
getch();
}

STRUCTURE WITHIN STRUCTURE WITH EXAMPLE PROGRAM


[ Univ. Ques. Jan 2016, May 2015, Jan 2015, May 2013]
STRUCTURE WITHIN STRUCTURES (NESTED STRUCTURES)
 Structure within structure is used to access the structure member placed within another structure.
 Let us consider the following structure defined to store information about the salary of employees.
Example:
struct salary
{
char name;
char department;
int basic_pay;
int dearness_allowance;

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

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

STRUCTURES AND FUNCTIONS (Univ. Ques. May 2014, May 2013).


 C supports the passing of structure values as arguments to functions. There are three methods by
which the values of structure can be transferred from one function to another.
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 we 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;

15
MVIT UNIT-IV T106 COMPUTER PROGRAMMING

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.

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:

16
MVIT UNIT-IV T106 COMPUTER PROGRAMMING

Enter Employee No. and Name : 101


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

SELF-REFERENTIAL STRUCTURES (Pointers and Structure)

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

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.

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.

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”);
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”);

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

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.

EXAMPLE PROGRAM FOR TYPEDEF:


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

#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.

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.

UNIONS (AU- APR/MAY2014)


 INTRODUCTION

 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

/* Program to display total memory


size occupied by union */
#include <stdio.h>

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;
}

 INITIALIZING THE UNION


We can initialize the union in various ways. For example

 ACCESSING UNION MEMBERS


To access any member of a union, the member access operator (.) is used. would The union
keyword to define variables of union type.

Following is the example to explain usage of union:

#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

APPLICATIONS FOR UNION


 Use the same memory in different ways.
 Creating flexible structure that can hold different types of data.

DIFFERENCE BETWEEN STRUCTURES AND UNION [ Jan-2013 ]

 It is a user defined data type. A structure is a collection of variables of different type.


 It contains data members and each is accessed by the structure variable.
 Each data object in a structure is a member or field.
 A union is an object similar to a structure except that union, one block is used by all the member of the
union but in case of structure, each member has their own memory space. All of union members start
at the same location in memory.
 A union variable can represent the value of only one of its members at a time.
 The size of the union is equal to the size of the largest member of the union where as size of the
structure is the sum of the size of all members of the structure.
Defining Structure:
struct book
{
char name;
int pages;
float price;
};

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.

EXAMPLE PROGRAM TO ILLUSTRATE STRUCTURE AND UNION DIFFERENCE:

#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.

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:

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.

 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

27
MVIT UNIT-IV T106 COMPUTER PROGRAMMING

 INITIALIZING POINTER VARIABLE


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’.

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.

 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

Enter the number 3:30


Enter the number 4:40
Enter the number 5:50

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

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.

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);


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

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

30
MVIT UNIT-IV T106 COMPUTER PROGRAMMING

‘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)

POINTER AND STRUCTURE (Univ.QP.Jan 2014)


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

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

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();
}

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

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

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, May 2019)
3. Give the applicability of union in programming. (MAY 2017)
4. Compare structure and union. (MAY-2016, MAY-2014, JAN-2013, JAN 2011, JAN 2010,May 2019)
5. Give an example where a structure data type may be required.

34
MVIT UNIT-IV T106 COMPUTER PROGRAMMING

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


7. Define Union? (JAN 2014)
8. Write about nested structure?(JAN-2014)
9. What is the use of structure in C. (NOV 2011)
10. Write the syntax for declaration and initialization of structures. (JAN 2011)
11. What is a structure variable? (MAY 2013)
12. Define array of pointers. (MAY 2013)
13. What is bit field and write its rule?
14. Write a program using pointer to determine the length of a character strings?
15. What is a null pointer?
16. Explain Enumerated data type.
17. What are Structures? State how Structure Members are accessed?(Nov 2018)
18. Write a program to calculate the sum of digits using Pointers.(Nov-2018)

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

You might also like