Structures demo program with int and char array
A program using structure with two different type of variables int and char[] grouped in one structure.
Learning Objectives
- Understanding the basic concept of a structure type by using a simple example.
Source Code
|
Run Output
Code Understanding
struct Person //structure definition start with the struct keyword followed by name of structure
{ //Strructure is a data-structure where members are enclosed in curly braces.
int age; //This is to store the integer value of age
char name[50]; //This is to store char array which will contain the name.
}; //The semicolon is always suffixed to an structure definition.
Person P1,P2;
This instruction declares two data structure objects/instances that will have the structure like the person which means we can store two age and two name, one in P1 and another in P2 which are independent of each other.
P1.age=21;P2.age=23;
Here we are initialising the age variable of two structure instances. We follow the . notation to connect the structure instance name to its variable name like P1.age or P2.age.
cout<<“Give Name 1 : “; cin.getline(P1.name,50);
Here we are collecting the name for first instance P1.
cout<<“Give Name 2 : “; cin.getline(P2.name,50);
Here we are collecting the name for second instance P2.
cout<<P1.name<<” “<<P1.age<<endl; cout<<P2.name<<” “<<P2.age<<endl;
Name and age is being printed by using the instance.variable format.
Notes
- None of the variable in the structure can be initialised while defining a struct{ }; syntax. This is because structure doesn’t take memory space. Memory space is actually reserved when structure instance is created like Person P1, P2;
- The char array defined in structure can not be initialised after instance creation. This is because the structure arrays simply pointing to memory locations. So we can not write things like –
P1.name=”Laila”; The way can do otherwise in normal programming.
Suggested Filename(s): strudemo.cpp
sunmitra| Created: 18-Jan-2018 | Updated: 18-Jan-2018|