Saturday, 6 January 2018

How Structures are initialization with example program

A structure can be initialized in the same way as other data types initialized. Initializing a structure means assigning some constant values to the members. When the user does not explicitly initialize the structure, then C automatically does that. For int and float members, the values are set to zero and char and strings members are set to '\0' by default.



There are two methods to initialized structure members. Here are examples how to initialized structures

Exmaple1:

struct student
{
int no;
char name[30];
float fee;
}s={101,"Ramu",4500};

 Here the structure is initialized at the ending of the structure syntax i.e using structure variable and equal operators and I put the values in parenthesis.

Example2:

struct student
{
int no;
char name[30];
float fee;
};

struct student s={101,"Ramu",4500};
(OR)

void main()
{
 struct student s={101,"Ramu",4500};
.
.
.
.
.
}

Here the structure is initialized after the structure is declared, by using struct keyword followed by structure variable and equal operator by putting values in parenthesis.


One can also initialize structure by reading values while running the program suing C I/O functions. Here is an example how to do this.


struct employee
{
int no;
char name[10];
float sal;
};

void main()
{

struct employee e;
clrscr();

/ ** initializing structure at run time **/

printf("enter employee numbers") ;
scanf(" %d", &e.no);

printf("enter employee name") ;
scanf(" %s", e.name);

printf("enter employee salary") ;
scanf(" %f", &e.sal);

/** Printing structure values **/

 printf("employee numbers = %d", e.no) ;
 printf("employee name = %s", e.name) ;
 printf("employee salary=%f ", e.sal) ;

getch();

}
 

0 comments:

Post a Comment

Advertisement

Find Us On Facebook

C Programming

More

C++ Tutorial

More

Java Tutorial

More

Computer Basics

More

MS Office

More

Database Management

More
Top