UMBC CS 201, Fall 06
UMBC CMSC 201
Fall '06

CSEE | 201 | 201 F'06 | lectures | news | help

Defining, declaring and using structures

The code

/************************************** ** File: struct1.c ** Author: Dennis L. Frey ** Date: 1/20/00 ** Section: N/A ** E-mail: frey@cs.umbc.edu ** ** Defining, declaring and using ** structures and typedefs *****************************************/ #include <stdio.h> #define SIZE 25 /* Structure definition */ typedef struct student { char name[SIZE] ; char major[SIZE] ; double gpa ; } STUDENT; int main() { STUDENT student1, student2, temp ; /* input data for student1 */ printf ("Input student name: "); scanf ("%s", student1.name); printf ("Input student major: "); scanf ("%s", student1.major); printf ("Input student gpa: "); scanf ("%lf", &student1.gpa); /* input data for student2 */ printf ("Input student name: "); scanf ("%s", student2.name); printf ("Input student major: "); scanf ("%s", student2.major); printf ("Input student gpa: "); scanf ("%lf", &student2.gpa); printf("\n\n"); /* print student1 data */ printf ("student1 name = %s\n", student1.name); printf ("student1 major = %s\n", student1.major); printf ("student1 gpa = %5.2f\n", student1.gpa); /* print student 2 data */ printf ("student2 name = %s\n", student2.name); printf ("student2 major = %s\n", student2.major); printf ("student2 gpa = %5.2f\n", student2.gpa); /* Swap records using assignment */ temp = student1 ; student1 = student2 ; student2 = temp ; /* print student1 data */ printf ("student1 name = %s\n", student1.name); printf ("student1 major = %s\n", student1.major); printf ("student1 gpa = %5.2f\n", student1.gpa); /* print student2 data */ printf ("student2 name = %s\n", student2.name); printf ("student2 major = %s\n", student2.major); printf ("student2 gpa = %5.2f\n", student2.gpa); return 0; }

The data file

linux1[102] % cat data Roadrunner Engineering 3.8 Coyote Engineering 1.2

The output

linux1[103] % a.out < data Input student name: Input student major: Input student gpa: Input student name: Input student major: Input student gpa: student1 name = Roadrunner student1 major = Engineering student1 gpa = 3.80 student2 name = Coyote student2 major = Engineering student2 gpa = 1.20 student1 name = Coyote student1 major = Engineering student1 gpa = 1.20 student2 name = Roadrunner student2 major = Engineering student2 gpa = 3.80 linux1[104] %


CSEE | 201 | 201 F'06 | lectures | news | help

Tuesday, 22-Aug-2006 07:14:10 EDT