Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structures Pepper Much content credited to Dr. Robert Siegfried and to Dietel C How to Program.

Similar presentations


Presentation on theme: "Structures Pepper Much content credited to Dr. Robert Siegfried and to Dietel C How to Program."— Presentation transcript:

1 Structures Pepper Much content credited to Dr. Robert Siegfried and to Dietel C How to Program

2 What is a Structure A structure is a manufactured data type consisting of related parts A structure will be created in contiguous memory In C, a structure is created on the stack Visualize with Excel: a structure would contain the column headings, and a single row would be contained in a structure variable. As close to a class definition as C gets

3 Defining A Structure - The Type A structure containing the rate of pay and hours worked might look like this: struct worker { intrate; inthours; intgross; } ; struct worker is now a new data type STRUCTURE TAG

4 Defining A Structure (continued) Alternatively, we can write: struct worker { int rate, hours, gross; } ;

5 Declaring A Structure - Make a var We can give the structure a name and then declare variables as structures of this type very easily: struct workerstuff { int rate, hours, gross; } ; … int main(void) { struct workerstuffworker; // create a variable of type workerstuff Structure Variable

6 Declaring A Structure - Make a var Alternately, make the variable along with structure definition. This creates both worker and manager Workerstuff is optional struct workerstuff { int rate, hours, gross; } worker, manager; Structure Variables

7 Using A Structure Variable Access parts with dot To use a field within the structure, you must specify both the structure and the field with a period “.” in between: scanf("%d",&worker.rate); scanf("%d",&worker.hours); worker.gross = worker.rate * worker.hours;

8 A simple payroll program #include /* * a simple structure for payroll */ struct workerstuff { char name[20]; float rate; float hours; float gross; };

9 /* * payroll.c - A simple payroll program */ int main(void) { struct workerstuff worker; printf("What is the worker\'s rate per " "hour?\t"); scanf("%f", &worker.rate); printf("How many hours did the worker work " "last week?\t"); scanf("%f", &worker.hours);

10 printf("What is the worker\'s name?\t"); scanf("%s", &worker.name); printf("%s worked for out %3.1f hours at $" "%4.2f per hour.\n", worker.name, worker.hours, worker.rate); return(0); }

11 New Payroll -Array of a Structure Array of a structure like any other Remember the data type is “struct tag” #include /* # of tax brackets*/ #define NumBrackets5 struct brackettype { float minsalary, taxrate; };

12 /* The prototypes */ voidgetbrackets(struct brackettype brackets[]); voidgetinput(float *hours, float *rate); floatgetgross(float hours, float rate); floatgettax(float gross, struct brackettype brackets[]); voidwritecheck(float gross, float tax, float net, float rate, float hours); intcalcagain(void); Parameter of Array of a structure type

13 /* * A payroll program that allows the user to * enter the tax brackets */ int main(void) { floathours, rate; floatgross, tax, net; struct brackettypebrackets[NumBrackets]; intagain; /* * Get the tax brackets before processing any * payroll records */ getbrackets(brackets); Variable of Array of a structure type

14 do { /* * Get the inputs, calculate the * gross */ getinput(&hours, &rate); gross = getgross(hours, rate); /* * Calculate the tax and subtract it * to get the net */ tax = gettax(gross, brackets); net = gross - tax;

15 /* * Write the paycheck */ writecheck(gross, tax, net, rate, hours); /* * Does the user want to process another * record? */ again = calcagain(); } while (again); /* If not, quit */ return(0); }

16 /* * getbrackets() - Input the tax brackets * We need the minimum gross for the tax * bracket, and the tax rate itself */ void getbrackets(struct brackettype brackets[]) { int i; for (i = 0; i < NumBrackets; i++) { printf("What is the maximum income for" " bracket #%d?\t", i+1 ); scanf("%f", &brackets[i].minsalary);

17 printf("What is the tax rate for bracket" " #%d?\t", i+1); scanf("%f", &brackets[i].taxrate); brackets[i].taxrate = brackets[i].taxrate/100; } printf("\n\n\n"); }

18 /* * gettax() - Calculate the tax for the * employee using the tax brackets */ float gettax(float gross, struct brackettype brackets[]) { int i; /* * If the employee doesn't make enough for the * lowest bracket the tax is zero */ if (gross < brackets[0].minsalary) return(0.0);

19 /* * Find the appropriate bracket for the * employee */ for (i = 1; i < NumBrackets; i++) { if (gross < brackets[i].minsalary) return(brackets[i-1].taxrate*gross); } /* The employee is in the highest bracket */ return(brackets[NumBrackets-1].taxrate*gross); }

20 Structures Containing Arrays A structure can have an array as a field within it. Examples of this include character strings. A Dean’s List program could use this to include the grades that comprised our students’ g.p.a.

21 Reminder typedef There are times when it is useful to define one's own data types. You can do this with the typedef statement. Syntax: typedefDataType DataTypeName; Examples typedef intIntegerType; typedef int*IntPtr; Remember that a struct’s datatype is two words: “struct tag”

22 Structure Typedef – 2 methods 1: Typedef the struct tag : struct examrec{char first[namelen]; intexam[numexams];}; typedef struct examrec Exam 2: Typedef the entire struct definition (no tag): typedefstruct{ charfirst[namelen]; intexam[numexams]; } Exam; Variable Creation with either method: Exam anExam;

23 Example: Find a Student’s Exam Average Find a student’s exam average, given the scores on 4 exams. Initial algorithm: 1.Find the student’s exam scores 2.Calculate the student’s average 3.Print the scores and average

24 Pointer to a structure-> If we are working with a pointer to a structure and we wish to reference one of the fields, we can write: *(myStructPtr.myField) or myStructPtr -> myField This second form is consider far better form.

25 avggrade.c #include #definenamelen15 #definenumexams4 typedefstruct{ charfirstname[namelen], lastname[namelen]; intexam[numexams]; } examrec; voidreadstudent(examrec *student); floatfindaverage(examrec student); voidwritestudent(examrec student, float average);

26 /* * AvgGrade() -Averages the grades on n exams */ intmain(void) { examrecstudent; floataverage; /* Read the students name and test scores */ readstudent(&student); /* Find the average */ average = findaverage(student); /* Print the results */ writestudent(student, average); return(0); }

27 /* * ReadStudent() -Read the input about the *student */ voidreadstudent( examrec *student) { inti; printf("First name\t?"); scanf("%s", student -> firstname); printf("Last name\t?"); scanf("%s", (*student).lastname ); for (i = 0; i < numexams; i++){ printf("Enter grade for exam #%d\t?", i+1); scanf("%d", &(student->exam[i])); } SAME ACCESS Pass by Ref

28 /* * FindAverage() -Returns the average of n *exam scores */ floatfindaverage( examrec student) { inti, sum = 0; for (i = 0; i < numexams; i++) sum += student.exam[i]; return((float) sum/numexams); } Pass by Value, no ptr

29 /* * WriteStudent() -Print the data about the *student including the *average */ voidwritestudent(examrec student, float average) { inti; printf("%s %s scored :\n", student.firstname, student.lastname); for (i = 0; i < numexams; i++) printf("%d\t", student.exam[i]); printf("\n\twhich resulted in an average of" "%3.1f\n", average); }

30 Pass Structure by Ref or Value Note: By Val when passing a function an array inside a struct? If definition: struct z {char x[10];}; then a copy of x array is passed – by value If definition: struct z {char * x;}; then address of x is passed – by ref

31 Union Same definition syntax as structure but holds only one of the values. Used when memory is tight or for casting union number { int x; int * p;}; will hold one piece of data that you can access as either the name x, (considered an int) or as the name p, (considered a pointer).

32 ENUM Define constant words mapped to numbers for hard coded lists quickly declare a range of constant values Definition: enum days { SUN, MON, TUE, WED, THUR, FRI, SAT}; Declaration: enum days day; (day should only take on one of the 7 values) Same as #define SUN 0; Use: day = SUN;

33 Tutorials http://www.tutorialspoint.com/cprogramming/c_s tructures.htm http://www.tutorialspoint.com/cprogramming/c_s tructures.htm http://denniskubes.com/2012/08/20/is-c-pass-by- value-or-reference/ http://denniskubes.com/2012/08/20/is-c-pass-by- value-or-reference/ http://www.programiz.com/c-programming/c- enumeration http://www.programiz.com/c-programming/c- enumeration


Download ppt "Structures Pepper Much content credited to Dr. Robert Siegfried and to Dietel C How to Program."

Similar presentations


Ads by Google