Session 6

222 views
173 views

Published on

C Language Slides

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
222
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Session 6

  1. 1. Structures• A structure is a collection of one or more variables types grouped under a single name for easy manipulation.• The variables in a structure, unlike those in an array, can be of different variable types.• A structure can contain any of Cs data types, including arrays and other structures.• Each variable within a structure is called a member of the structure.
  2. 2. Using a struct• By defining a structure you create a new data type.• Once a struct is defined, you can create variables of the new type. Student stu_variable;
  3. 3. Accessing Structure Members• Structure members are accessed using the structure member operator (.), also called the dot operator, between the structure name and the member name.• Thus variable s1 can be access in following way S1.no=10; S1.name=”AMAR”; S1.per=80;• printf("%d,%s,%f", s1.no, s1.name,s1.per);
  4. 4. #include <stdio.h>struct student{ int id; char *name; float per;};void main(){ struct student st; st.id=1; st.name=“ram”; st.per=90.5;}
  5. 5. Advantage Of Using structure• One major advantage is that you can copy information between structures of the same type with a simple equation statement.• Continuing with the preceding example, the statement S2 = S1; is equivalent to this statement: S2.no=S1.no; S2.name=S1.name; S2.per=S1.per;
  6. 6. Arrays of Structures#include <stdio.h>struct entry{ char fname[20];};
  7. 7. main() { struct entry list[4]; for (i = 0; i < 4; i++) { printf("nEnter first name: "); scanf("%s", list[i].fname); } for (i = 0; i < 4; i++) { printf("Name: %s ", list[i].fname,} }
  8. 8. Pointer To Structurestruct emp{ int empno; char nm[20]; };void main(){ struct emp e1={10,”RAJ”}; struct emp *p; p=&e1; printf(“%d %s ”, e1.empno, e1.nm); printf(“%d %s ”, p->empno, p->nm);}
  9. 9. UNIONS• A union is a variable which may hold members of different sizes and types.• The syntax for declaring a union is similar to that of a structure: union number { int number; double floatnumber; } anumber;
  10. 10. • This defines a union called "number" and a variable of it called "anumber".• Members of the union can be accessed in the following way:• printf("%f",anumber.floatnumber);• When the C compiler is allocating memory for unions it will always reserve enough room for the largest member.

×