Structures in C++

There are various types of data type such as int, char float etc.

For example:


int  i;      here variable i can store only data of integer type
char c;   here variable c can store only data of character type
float  f; here variable f can store only data of floting-point type

Variable of each data type can store only single type of data.

But,  if we want to store different  type of data in a single variable then we use structure variable.

“structure” is user defined data type that allows to store data items of different data type.

  Defining a Structure

We can create a structure, by using the struct keyword.

The struct keyword defines a user defined new data type that can hold more than one member of different data type.

Format of structure is as follows –

In a C programming Structures are used to represent a record.

Suppose you want to store the information of  a school student such as : −

  • Name
  • Class
  • Section
  • Roll Number

Example: 

Here s1 and s2 are the structure variable.

Another way of creating a structure variable is:

Example: Write a program to store and print the following information such as name, roll number, class and section of the student using structure.

Output

Example: Write a program to store and print the following information such as name, roll number, class and section of 2 students using structure.

Output

Categories C++