• No results found

Structure and Union 1

N/A
N/A
Protected

Academic year: 2022

Share "Structure and Union 1"

Copied!
42
0
0

Loading.... (view fulltext now)

Full text

(1)

Structure and Union

1

(2)

Objective

To understand and be able to use structure

To be able to pass structure to and from function

To understand UNION and be able

to use it

(3)

Strcuture & Union

Structures

⚫ Can store more than one type of data

⚫ To put data together into one type Union

⚫ Similar to structure

⚫ Can store more than one data type

⚫ BUT can only keep one data at a time

(4)

Structure declaration

struct struct-name {

type name_1 ; type name_2 ;

…………

…………

type name_n ;

} struc_var1, struc_var2,struc_var3 ;

(5)

Structure Example

struct address

{ char name[30];

char detail[50];

int age;

char telephone[10];

char sex;

} input1, input2;

struct address input3;

variable names

struct name

(6)

Structure Example 2

struct student { char name[20] ;

double score, grade ; struct student st1,st2; } ;

6

(7)

Structure operator

⚫ member operator (.) to access member data

⚫ Example gets(st1.name) ; st1.score = 45.5 ;

⚫ Data in structure can be used normally

However, structure itself cannot be used for comparison or assignment

st1=5;

st1>st2

(8)

Structure and operator

⚫ Example

if (st1.score >= 80) {

st1.grade = 4.0 ; }

⚫ Structure can’t be used directly if ( st2 > st1 )

printf(“you are great”);

ERROR!!

(9)

Ex1.c

#include <stdio.h>

void main()

{ struct student { char name[20] ;

double score, grade ; struct student st ; } ;

printf(“Input name : ”);

gets(st.name);

printf(“Input score : ”);

scanf(“%lf”,&st.score);

if (st.score >= 50) st.grade = 4.0 ; else st.grade = 1.0;

printf (“name : %s\nscore : %lf\ngrade : %lf\n ” , st.name , st.score , st.grade) ; }

Structure Example

st.score is double

(10)

Ex2.c

#include <stdio.h>

void main {

struct date {

int dd , mm , yy;

} ;

struct date day ;

printf(“Input day :”);

scanf(“%d”,&day.dd);

printf(“Input month :”);

scanf(“%d”,&day.mm);

printf(“Input year :”);

scanf(“%d”,&day.yy);

printf(“day is %d:%d:%d” ,day.dd ,day.mm ,day.yy);

}

Structure Example

Structure Example

(11)

Example

struct test {

int x , y ; } ;

struct test a = {2 , 4} , b;

b.x = -5 ;

b.y = a.y + b.x ; a.x = 2 * a.x ; a = ? , b = ?

a.x = 4

a.y = 4

b.x = -5

b.y = -1

(12)

Example

struct test {

float f ; int i ; } ;

struct test aa = {3.5 , 2} , bb = {2.4 , 1} , cc;

cc.f = aa.i + bb.f ; bb.f += aa.f ;

cc.i = bb.i

aa = ? , bb = ? , cc = ?

(13)

EX 3.c

#include <stdio.h>

main()

{ struct {

char code[4];

char name[21];

float price;

} inv;

strcpy(inv.code, “001”);

strcpy(inv.name, “pencil”);

inv.price = 3.0;

printf(“Product Code: %s\n”, inv.code);

printf(“Product Name: %s\n”, inv.name);

printf(“Product Price: %f\n”, inv.price);

}

No struct name

(14)

LAB

void main()

struct complex{

int real;

int Img;

};

//Get both real / imaginary part of 2 complex numbers // Find the addition of the two number and display

//Find the multiplication of the two number and display e.g. [(a+bi)+(c+di) ]= (a+c)+(b+d)i

(a+bi)*(c+di) = (a*c-b*d)+(a*d+b*d)i

14

(15)

Passing structure to function

⚫ Structure data can be used as function arguments

⚫ Structure is needed to be defined before use

⚫ Structure is often defined after #include (as external

variable)

(16)

#include <stdio.h>

struct complex {

double r;

double c;

} ;

struct complex read (void) {

struct complex t;

printf("Real part : ");

scanf("%lf",&t.r);

printf("Complex part : ");

scanf("%lf",&t.c);

return t;

}

void main() {

struct complex x;

x = read();

}

Define complex structure

Outside main

Return type is

“struct complex”

(17)

typedef

⚫ Instead of calling “struct student” every time you declare a new variable

struct student st;

⚫ Use the keyword “typedef” in front of “struct” to defined a new data type

⚫ After using typedef, the new variable can be declare without

using the word “struct” in front

(18)

#include <stdio.h>

typedef struct {

double r;

double c;

} complex;

void pr(complex s,double i,double j) {

printf("%lf %lf\n",s.r,s.c);

printf("%lf %lf\n",i,j);

}

complex add(complex a,complex b){

complex t;

t.r=a.r+b.r;

t.c=a.c+b.c;

return t;

}

void main() {

complex x;

printf("Real part : ");

scanf("%lf",&x.r);

printf("Complex part : ");

scanf("%lf",&x.c);

pr(x,x.r,x.c);

complex a={5.2,4.3},b={1,3.5}

x=add(a,b);

printf(“%.2f+%.2fi”,x.r,x.c);

}

Defined new type of data using typedef

Function can use the whole

structure data or

some parts of the

structure data

(19)

Array of structure

⚫ Structure is normally created for reused with number of data

⚫ Example: student can be declared as array of structure struct student Cst[21];

⚫ To access data member

Structure[index].MemberData

Ex. strcpy(Cst[15].name,”Chun”); Cst[15].score = 40.5;

(20)

name san

score 78.5 grade 3.5

Cst[20]

Cst[0].name == “soma”

Cst[0].score == 78.5 Cst[0].grade == 3.5

Cst[1].name == “dang”

Cst[1].score == 57 Cst[1].grade == 1.5

Cst[20].name == “san”

Cst[20].score == 83.5 Cst[20].grade == 4

name samorn

score 78.5 grade 3.5

Cst[2]

name dang

score 57 grade 1.5

Cst[1]

name soma

score 78.5 grade 3.5

Cst[0]

(21)

FFlush

⚫ Remaining data, such as newline, may still exists in the keyboard(stdin).

fflush(stdin) is used to clear those extra characters for gets or scanf(“%s”) command to use to get string properly

21

(22)

Ex 4.c

#include <stdio.h>

void main(){

struct st {

char name[30] ;

double score , grade ; } ;

struct st Cst[21];

int i;

for( i=0 ; i<21 ; i++ )

{ printf(“Input name [%2d] : ” , i+1);

gets(Cst[i].name); fflush(stdin);

printf(“Input score : ”);

scanf(“%lf”, &Cst[i].score);

printf(“Input grade : ”);

scanf(“%lf”, &Cst[i].grade); fflush(stdin);

} }

Example: fflush(stdin)

(23)

main(){

struct std {

char name[40];

char birth[12];

};

struct std sci_std = {“AAA BBB”,”3 July 75”};

struct std math_std, eng_std;

strcpy(math_std.name, sci_std.name);

strcpy(math_std.birth, sci_std.birth);

strcpy(eng_std.name, math_std.name);

strcpy(end_std.birth, math_std.birth);

clrscr();

Example of

(24)

printf(“Science student :\n”);

printf(“ Name: %s Birth: %s \n”,sci_std,name,sci_std.birth);

printf(“Math student “\n”);

printf(“ Name: %s Birth: %s \n”,math_std.name,math_std.birth);

printf(“English student :\n”);

printf(“ Name: %s Birth: %s \n”,eng_std.name,eng_std.birth);

}

Result

Science student :

Name: AAA BBB Birth: 3 July 75 Math student :

Name: AAA BBB Birth: 3 July 75 English student :

Name: AAA BBB Birth: 3 July 75

(25)

Ex 6.c Storing data using structure inputting from keyboard

#include<stdio.h>

main() {

int i;

struct std {

char code[5];

char name[30];

int score;

};

struct std sci_std[5];

clrscr();

(26)

printf(“*** Enter 5 data :-\n”);

for(i=0; i<5; i++) {

printf(“Science student no. %d \n”,i);

printf(“ Seat no’(3 digits):”);

scanf(“%s”,sci_std[i].code);

fflush(stdin);

printf(“ Name(25 characters):”);

gets(sci_std[i].name);

printf(“ Score(2 digits):”);

scanf(“%d”,&sci_std[i].score);

fflush(stdin);

}

(27)

printf(“\nHere are all science students we have :\n”);

for(i=0; i<5; i++

{

printf(“Student %d “%4s %-25s %4d\n”, i,sci_std[i]. code, sci_std[i].name,sci_std[i].score);

} }

Result

*** Enter 5 data :- Science student no. 0 Seat no.(3 digits):001

Name(25 characters):AAA AAA

(28)

Score(2 digits):94 Science student no. 1 Seat no.(3 digits):002

Name(25 characters):BBB BBBBBBB Score(2 digits):80

Science student no. 2 Seat no.(3 digits):003

Name (25 characters) : CCCCC CCC Score (2 digits) : 78

Science student no. 3 Seat no. (3 digits) : 004

Name (25 characters) : DDDDD DD Score (2 digits) : 64

Science student no. 4

Seat no. (3 digits) : 005

(29)

Name (25 characters) : EEE EEEEEEEE Score(2 digits) : 88

Here are all science students we have : Student 0 : 001 AAA AAA 94

Student 0 : 002 BBB BBBBBBB 80 Student 0 : 001 CCCC CCC 78

Student 0 : 001 DDDDDD DD 64

Student 0 : 001 EEE EEEEEEEE 88

(30)

typedef struct {

char name[30] ; double score ;

double grade ; } student ;

student Cst[21] ;

New variable type, student

Cst Array is array of data type student

Example

(31)

structure & pointer

⚫ Stucture can be used with pointer

struct student *ptr_st ; or complex *ptr_x ;

⚫ To derefence data of structure can be defined as

(* pointer_name).member or pointer_name->member (*ptr_st).score , ptr_st->score

(*ptr_x).r , ptr_x->r

(32)

a.r = (*pa).r = pa->r = 10.5 a.c = (*pa).c = pa->c = 5.5

typedef struct {

double r;

double c;

} complex;

complex a = {10.5,5.5} ; complex *pa ;

pa = &a ;

r 10.5

c 5.5

pa a

(33)

Example

typedef struct {

int x , y ; } point;

point pointA = {1,4} , *pa;

int a,b;

pa = &pointA;

pa->y = 10;

a = pointA.y * 3;

b = pa->x – pa->y;

a = ? , b = ?

a = 30

b = -9

(34)

Structure within structure

⚫ Structure can be defined as a data type in another structure

struct time { int hour ;

int min ; int sec ; } ; struct sms

{ char sender[20] ; char msg[50] ; struct time t ;

} ;

hour min

sec msg

sender

(35)

Structuer within structure operation

⚫ Use member operator (.) for accessing

Example struct sms m1 ; strcpy(m1.sender,”shy”);

strcpy(m1.msg,”miss you”);

m1.t.hour = 12;

m1.t.min = 10;

m1.t.sec = 5;

(36)

Union

• Union is similar to structure

• Union is made for saving the data storage

• Only one data is stored at a time

• Union declaration is similar to structure

(37)

union {

long lvar;

int ivar;

char cvar;

} uvar;

(38)

Ex 6.c Union Example main()

{

union temp { /* union declaration*/

int number;

float price;

} book;

printf (“size of union template = %d\n”, sizeof (temp) ); /*show union size*/

book.number = 123;

printf (“book.number = %d\n”, book.number) ; book.price = 482.75;

printf (“book.price = %f\n”, book.price) ;

printf (“book.number = %d\n”, book.number) ;

(39)

39

Result

size of union template = 4 (Can hold only max size of var)

book.number = 123 (store number and display)

book.price = 482.75 (price replaces number)

(40)

Enter number of students:4

---Student#1---

Enter Type of ID(1-Number , 2-Full Name , 3-Nick Name):2 Enter student's full name:Cesc Frabegas

Enter (age,gpa):22,1.93

---Student#2---

Enter Type of ID(1-Number , 2-Full Name , 3-Nick Name):3 Enter student's nick name:Rooney

Enter (age,gpa):25,3.95

---Student#3---

Enter Type of ID(1-Number , 2-Full Name , 3-Nick Name):1 Enter student number:777

Enter (age,gpa):24,2.00

---Student#4---

Enter Type of ID(1-Number , 2-Full Name , 3-Nick Name):3 Enter student's nick name:Tevez

Enter (age,gpa):27,3.11 The youngest student:

FullName:Cesc Frabegas Age:22

GPA:1.93

The highest GPA student:

NickName:Rooney Age:25

GPA:3.95

Lab Wk.9 (Structure

& Union)

•Input total number of students and then enter all of their details.

•Each student has only one ID which can be either number(integer), full name (firstname and lastname) or nickname.

•Each student also has age (integer) and GPA(real no.)

•Complete the given source code with additional functions to show all details of

•The youngest student

•The highest GPA student

(41)

Student data type

ID

int idtype int age

float GPA

Number FullName Name

choose

n...#

ID

int idtype int age

float GPA

Number FullName Name

choose

#2 ID

int idtype int age

float GPA

Number FullName Name

choose

#1 id

int idtype int age

float GPA

Number FullName NickName choose

#0 StudentID

(42)

union StudentID {

int number;

char fullname[30];

char nickname[8];

};

typedef struct {

union StudentID id;

int idtype;

int age;

float gpa;

} Student;

void inputStudent(Student s[],int *n);

void showYoungest(Student s[],int n);

void showHighestGPA(Student s[],int n);

void main() {

Student s[20];

int n;

inputStudent(s,&n);

showYoungest(s,n);

showHighestGPA(s,n);

getch();

return 0;

}

References

Related documents