Home » Learn C++ » Initialization of Structure Variables

Initialization of Structure Variables

Initialization of Structure Variables:

The values into a structure variable can be assigned when it is declared. It is called initialization of the structure variable. To initialize a structure variable, data is assigned to the members of the structure. To assign data to the members of the structure, the data items are written in the same order in which these have been defined in the structure. The type of the data must also correspond to the type of the member of the structure.

For example, in the structure “address”, member city is of character type and is the first member. The value that is to be assigned to it must be of character type and is written first. Similarly, the second member is pcode. The value that is to be assigned to it must be of integer type and is written second.

struct address
{
char city [15] ;
int pcode;
}
address tag {“London”, 78500};

Program:

Write a program to define a structure with five members. The first member is student name and the other he marks obtained in subjects. Assign values to the members during their declaration. Add the marks of subjects to calculate total marks and then print these numbers and the total marks of the student.

#include <iostream.h>

#include <conio.h>

main ( )

{

struct rec

{

char name [15];

int s1, s2, s3, s4;

};

rec st01 = {“John”, 91, 92, 89, 98};

int total;

total = st01.s1 + st01.s2 + st01.s3 + st01.s4;

clrscr ( );

cout << “Name of student : ” << st01.name << endl;

cout << “Marks in Subject 1 : ” << st01.s1 << endl;

cout << “Marks in Subject 2 : ” << st01.s2 << endl;

cout << “Marks in Subject 3 : ” << st01.s3 << endl;

cout << “Marks in Subject 4 : ” << st01.s4 << endl;

cout << “Total Marks :” << total;

}

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.