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

Chapter 8

Uploaded by

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

Chapter 8

Uploaded by

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

PPS (3110003)

CHAPTER 8
Structure

Q.1 Distinguish between Structure and Union. (PPS_WIN2019)(CPU_WIN_2019)


(CPU_WIN_2017) (CPU_WIN_2015) (CPU_WIN_2014) (CPU_SUM_2015,19)

Q.2 What is structure? How to access the elements of structure? How to calculate size of
structure? Explain with example. (PPS_WIN_18) (CPU_WIN_2014)
Structure is a group of variables of different data types represented by a single name.
Structure members are accessed using dot [.] operator.
(.) is called as “Structure member Operator”.
Use this Operator in between “Structure name” & “member name”
EXAMPLE
#include<stdio.h>

struct Point
{
int x, y;
};

CKPCET, SURAT 1
PPS (3110003)

int main()
{
struct Point p1 = {0, 1};

// Accessing members of point p1


p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);

return 0;
}
Output:
x = 20, y = 1
Size of structure is calculated by Using sizeof Operator
#include<stdio.h>

struct stud {
int roll;
char name[10];
int marks;
};

int main() {
int size;
struct stud s;

size = sizeof(s);
printf("nSize of Structure : %d", size);

return(0);
}

Explanation :
Structure is Collection of elements of the Different data Types.
Size of the Structure Can be Evaluated using “sizeof Operator”
size = sizeof(s);
Formula for Calculating Size of Structure :
Size of Structure 'S' = sizeof(roll) + sizeof(name) + sizeof(mark)
= 2 + 10 + 2
= 14 //Size depends on your computer

CKPCET, SURAT 2
PPS (3110003)

Q.3 Define a structure data type called time_struct containing three member’s integer hours,
minutes, second. Develop a program that would assign values to individual member and
display the time in following format : HH:MM:SS (PPS_WIN_18)
#include <stdio.h>
struct time_struct
{
int hour;
int minute;
int second;
}t;
int main(void)
{
printf("\n Enter Hour : ");
scanf("%d",&t.hour);
printf("\n Enter Minute: ");
scanf("%d",&t.minute);
printf("\n Enter Second : ");
scanf("%d",&t.second);
printf("\n Time %d:%d:%d",t.hour%24,t.minute%60,t.second%60);
return 0;
}
Output
Enter Hour : 10
Enter Minute: 20
Enter Second : 30
Time 10:20:30
Q.4 Distinguish between “structure” and “array”. Discuss the meaning and purpose of
following: (I) struct keyword (II) typedef keyword (III) sizeof operator. (CPU_WIN_2016)
?(CPU_WIN_2013)

CKPCET, SURAT 3
PPS (3110003)

Difference Between Array and Structure

Array Structure

Structure is the collection of


1 Array is collection of homogeneous data.
heterogeneous data.

Structure elements are access using.


2 Array data are access using index.
operator.

3 Array allocates static memory. Structures allocate dynamic memory.

Array element access takes less time than Structure elements takes more time than
4
structures. Array.
struct’ keyword is used to create a structure. Following is an example.
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
typedef is used to define new data type names to make a program more readable to the programmer.
For example:
main() | main()
{ | {
int money; | typedef int Pounds;
money = 2; | Pounds money = 2
} | }
sizeof() : Returns the size of a memory location.

CKPCET, SURAT 4
PPS (3110003)

Q.5 Define a structure called cricket that will describe the following information: a. Player
name b. Team name c. Batting average(CPU_WIN_2016)
#include<stdio.h>
#include<conio.h>
struct cricket
{
char pname[20];
char tname[20];
float bavg;
};
int main()
{
struct cricket s[5],t;
int i,j,n=5;
float p;
clrscr();

printf("\nEnter data of %d players",n);


for(i=0;i<n;i++)
{
printf("\nEnter PName TName BAvg for player-%d = ",i+1);
scanf("%s %s %f",s[i].pname,s[i].tname,&p);
s[i].bavg=p;
}

for(i=1;i<=n-1;i++)
{
for(j=1;j<=n-i;j++)
{

CKPCET, SURAT 5
PPS (3110003)

if(strcmp(s[j-1].tname,s[j].tname)>0)
{
t=s[j-1];
s[j-1]=s[j];
s[j]=t;
}
}
}
printf("\nAfter teamwise sorting... Player list is ");
for(i=0;i<n;i++)
{
printf("\n%-20s %-20s %.2f",s[i].pname,s[i].tname,s[i].bavg);
}
getch();
return 0;
}
OUTPUT
Sachin India 98
Rahul India 45
Jonty Australia 89
Imran Pakistan 75
Shen Australia 29

Q. 6 What is structure ? Explain nested structure and array of structure with example.
(CPU_SUM_2014,18)

Structure is a user-defined datatype in C language which allows us to combine data of different


types together. Structure helps to construct a complex data type which is more meaningful. It is
somewhat similar to an Array, but an array holds data of similar type only. But structure on the
other hand, can store data of any type, which is practical more useful.

CKPCET, SURAT 6
PPS (3110003)

Defining a structure

struct keyword is used to define a structure. struct defines a new data type which is a collection of
primary and derived datatypes.

Syntax:

struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];

Array of Structure

We can also declare an array of structure variables. in which each element of the array will
represent a structure variable.

Syntax for array within structure

struct struct-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
----------
datatype varN;
};

struct struct-name obj;

Example : struct employee emp[5];

The below program defines an array emp of size 5. Each element of the array emp is of type
Employee.

#include<stdio.h>

struct Employee
{
char ename[10];
int sal;
};

struct Employee emp[5];

CKPCET, SURAT 7
PPS (3110003)

int i, j;
void ask()
{
for(i = 0; i < 3; i++)
{
printf("\nEnter %dst Employee record:\n", i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}
printf("\nDisplaying Employee record:\n");
for(i = 0; i < 3; i++)
{
printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
}
}
void main()
{
ask();
}

Nested Structures

Nesting of structures, is also permitted in C language. Nested structures means, that one structure
has another stucture as member variable.

Syntax for structure within structure or nested structure

struct structure1
{
----------
----------
};

struct structure2
{
----------
----------
struct structure1 obj;
};

Example:

struct Student

CKPCET, SURAT 8
PPS (3110003)

{
char[30] name;
int age;
/* here Address is a structure */
struct Address
{
char[50] locality;
char[50] city;
int pincode;
}addr;
};

Q. 7 Which type of problem can be solved by structure? Explain it with C program.


(CPU_SUM_2016)
C has built in primitive and derrived data types. Still not all real world problems can be solved
using those types. You need custom data type for different situations.
For example, if you need to store 100 student record that consist of name, age and mobile number.
To code that you will create 3 array variables each of size 100 i.e. name[100], age[100],
mobile[100]. For three fields in student record it say seem feasible to you. But, think how
cumbersome it would be to manage student record with more than 10 fields, in separate variables
for single student.
To overcome this we need a user defined data type. In this tutorial I am going to explain how easily
we will deal with these situations using structures in C programming language.
To declare or define a structure, we use struct keyword. It is a reserved word in the C compiler.
You must only use it for structure or its object declaration or definition.
Syntax to define a structure
struct structure_name
{
member1_declaration;
member2_declaration;
...
...
memberN_declaration;
};
Here, structure_name is name of our custom type. memberN_declaration is structure member i.e.
variable declaration that structure will have.
Example program to demonstrate declare, define and access structure members

CKPCET, SURAT 9
PPS (3110003)

Store Information and Display it Using Structure


#include <stdio.h>
struct student {
char name[50];
int roll;
float marks;
} s;

int main() {
printf("Enter information:\n");
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);

printf("Enter roll number: ");


scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f\n", s.marks);
return 0;
}
Output:
Enter information:
Enter name: Jack
Enter roll number: 23
Enter marks: 34.5
Displaying Information:

CKPCET, SURAT 10
PPS (3110003)

Name: Jack
Roll number: 23
Marks: 34.5

Q. 8 What is a structure? Give example. (CPU_SUM_2017)

We use structures to store data of different types. For example, you are a student. Your name is a
string and your phone number and roll_no are integers. So, here name, address and phone number
are those different types of data. Here, structure comes in picture.

Defining a Structure

The syntax for structure is:

struct structure_name

data-type member-1;

data-type member-2;

data-type member-3;

data-type member-4;

};

In our case, let's name the structure as 'student'. The members of the structure in our case are name,
roll_no and phone_number.

#include <stdio.h>

#include <string.h>

int main()

struct student

CKPCET, SURAT 11
PPS (3110003)

int roll_no;

char name[30];

int phone_number;

};

struct student p1 = {1,"Brown",123443};

struct student p2, p3;

p2.roll_no = 2;

strcpy(p2.name,"Sam");

p2.phone_number = 1234567822;

p3.roll_no = 3;

strcpy(p3.name,"Addy");

p3.phone_number = 1234567844;

printf("First Student\n");

printf("roll_no : %d\n", p1.roll_no);

printf("name : %s\n", p1.name);

printf("phone_number : %d\n", p1.phone_number);

printf("Second Student\n");

printf("roll_no : %d\n", p2.roll_no);

printf("name : %s\n", p2.name);

printf("phone_number : %d\n", p2.phone_number);

printf("Third Student\n");

printf("roll_no : %d\n", p3.roll_no);

printf("name : %s\n", p3.name);

CKPCET, SURAT 12
PPS (3110003)

printf("phone_number : %d\n", p3.phone_number);

return 0;

Q. 9 What is structure? Explain with example how to declare a structure and how to initialize
it. (CPU_SUM_2018)(PPS_SUM_19)
Declare a structure
We use struct keyword to declare a structure.
Let us declare a student structure containing three fields i.e. name, roll and marks.
struct student
{
char name[100];
int roll;
float marks;
};
How to initialize a structure variable?
C language supports multiple ways to initialize a structure variable. You can use any of the
initialization method to initialize your structure.
• Initialize using dot operator
• Value initialized structure variable
• Variant of value initialized structure variable
Initialize structure using dot operator
In C, we initialize or access a structure variable either through dot . or arrow -> operator. This is
the most easiest way to initialize or access a structure.
Example:
// Declare structure variable
struct student stu1;

// Initialize structure members


stu1.name = "Pankaj";
stu1.roll = 12;

CKPCET, SURAT 13
PPS (3110003)

stu1.marks = 79.5f;
Value initialized structure variable
The above method is easy and straightforward to initialize a structure variable. However, C
language also supports value initialization for structure variable. Means, you can initialize a
structure to some default value during its variable declaration.
Example:
// Declare and initialize structure variable
struct student stu1 = { "Pankaj", 12, 79.5f };
Invalid initialization:
// Declare and initialize structure variable
struct student stu1 = { 12, "Pankaj", 79.5f };
The above code will throw compilation error. Since the order of member type in structure
is character array, integer finally float. But, we aren't initializing the structure variable in the same
order.
Variant of value initialized structure variable
The above approach may suit all needs. In addition, C language supports flexibility to initialize
structure members in any order. I know this sounds bit confusing. As, just now I said C will throw
error if you try to initialize members in different order of declaration.
This approach is an extension of above. Here, you can specify member name along with the value.
Example:
// Declare and initialize structure variable
struct student stu1 = {
.roll = 12,
.name = "Pankaj",
.marks = 79.5f
};

Q. 10 Design structure with following elements : (CPU_SUM_2019)


Name of employ, basic, da, ta , deduction , net_salary
Give the variety of way to access individual elements of structure..
#include <stdio.h>

CKPCET, SURAT 14
PPS (3110003)

/*structure declaration*/
struct employee{
char name[30];
int empId;
float salary;
};

int main()
{
/*declare structure variable*/
struct employee emp;

/*read employee details*/


printf("\nEnter details :\n");
printf("Name ?:"); gets(emp.name);
printf("ID ?:"); scanf("%d",&emp.empId);
printf("Salary ?:"); scanf("%f",&emp.salary);

/*print employee details*/


printf("\nEntered detail is:");
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %f\n",emp.salary);
return 0;
}
Q. 11 Explain with suitable example structure variable and pointer to structure variable.
(PPS_SUM_2019)
pointer is a variable which points to the address of another variable of any data type like int, char,
float etc. Similarly, we can have a pointer to structures, where a pointer variable can point to the
address of a structure variable. Here is how we can declare a pointer to a structure variable.

CKPCET, SURAT 15
PPS (3110003)

struct dog
{
char name[10];
char breed[10];
int age;
char color[10];
};
struct dog spike;
// declaring a pointer to a structure of type struct dog
struct dog *ptr_dog
Example :
#include <stdio.h>
#include <string.h>

struct person {
char first_name[30];
char last_name[15];
int age;
char is_employed;
};

void display_names(struct person *p) {// structure pointer as an argument


// Observe the different notations used to access the structure pointer variables
printf("First name in the structure is : %s \n", p->first_name);
printf("Last name in the structure is : %s \n", (*p).last_name);
}

int main()

CKPCET, SURAT 16
PPS (3110003)

{
struct person structPer;
struct person *structPtr; // declare a structure pointer

// Assign the values to the structure


strcpy(structPer.first_name, "Yashvanth");
strcpy(structPer.last_name, "Kanetkar");
structPer.age = 50;
structPer.is_employed = 'Y';

structPtr = &structPer; // Points to the structure structPer

display_names(structPtr); // Call the function by passing the structure pointer


return 0;
}

MCQ
Q. What amongst the following determines the size of a union? (CPU_WIN_2019)
(a) Biggest member of the union (b) First member of union
(c) Sum of the sizes of all its members (d) Last member of union

Q.Structure can contain elements of the same data type. (CPU_WIN_2016) (CPU_WIN_2014)
(a) true (b) false

Q. Which of the following operator is used to select a member of a structure variable


(CPU_SUM_2017) (CPU_WIN_2016) (CPU_WIN_2014)
(a) .(dot) (b) ,(comma) (c) : (colon) (d) ;(semicolon)

(CPU_SUM_2019)

CKPCET, SURAT 17
PPS (3110003)

Q. Array and Structure can contain elements of _______ and ______ data type respectively.
(a) same, different (b) same, same (c) different, Same (d) different , different

CKPCET, SURAT 18

You might also like