unit - iv C prog ppt
unit - iv C prog ppt
unit - iv C prog ppt
Structure Definition:
Structure is a user defined data type. It is a
struct student
{
char name[40]; // Student name
int age; // Student age
unsigned long mobile; // Student mobile
number
}s1;
Declaration after structure definition
The other way to declare structure variable
struct student
{
char name[40]; //Student name
int age; // Student name int age;
unsigned long mobile; // Student mobile number
};
struct student s1; // Declare student variable s1
Accessing Structure fields:
Since structure is a complex data type, we cannot
Method 1
struct studentDetails std={"Mike",21,{15,10,1990}};OR
members as we require.
Syntax for declaring array within structure is
void main ()
{
struct date
{
int dd;
int mm;
int yy;
};
struct student
{
char name [20];
struct date dob;
}
struct student s1;
printf (“enter student name\n”);
scanf (“%s”, s1.name);
printf (“enter date of birth\n”);
scanf (“%d %d %d”, &s1.dob.dd,
&s1.dob.mm, &s1.dob.yy);
printf(“name=%s\t DOB=%d/%d/%d\
n”,s1.name,s1.dob.dd,
s1.dob.mm,s1.dob.yy);
}
Comparison of structure variables
Comparison
In C programming language, a structure is a
collection of different datatype variables,
which are grouped together under a single
name.
Declaration and initialization of structures
The general form of a structure declaration is as
follows −
datatype member1;
struct tagname{
datatype member2;
datatype member n;
};
Here,
struct is a keyword.
make up structure.
For example,
struct book
{ int pages;
char author [30];
float price;
};
Structure variables
There are three methods of declaring
struct book{
int pages;
char author[30];
float price; }
b = {100, “balu”, 325.75};
Second method
struct book{
int pages;
char author[30];
float price; };
struct book
b = {100, “balu”, 325.75};
Third method by using a member
operator
struct book{
int pages;
char author[30];
float price; } ;
struct book b;
b. pages = 100;
strcpy (b.author, “balu”);
b.price = 325.75;
Unions
# include <stdio.h>
void main ()
{
union student
{
int id;
char name [20];
};
union student s1;
printf (“enter student id\n”);
scanf (“ID=%d”, &s1.id);
printf(“Student id:%d\n”,s1.id);
printf (“enter student name\n”);
scanf (“Name=%s”, s1.name);
printf (“Student name = %s\n”,s1.name);
}
Output:
enter student id 10
ID=10
enter student name Liah
Name=Liah
10