150 likes | 267 Views
Array of Structures. Christopher Palma Alberto Martinez Donald Greene. Parts of Program. Included standard library #include < stdio.h > Define a structure to hold entries struct entry { char fname [20]; char lname [20]; char phone[10]; };. Declare an array of structures
E N D
Array of Structures Christopher Palma Alberto Martinez Donald Greene
Parts of Program • Included standard library #include <stdio.h> • Define a structure to hold entries struct entry { char fname[20]; char lname[20]; char phone[10]; };
Declare an array of structures struct entry list[4]; inti; int main(void) { • Loop to input data for four people for (i = 0; i < 4; i++) { printf("\nEnter first name: "); scanf("%s", list[i].fname); printf("Enter last name: "); scanf("%s", list[i].lname); printf("Enter phone in 123-4567 format: "); scanf("%s", list[i].phone); }
/* Print two blank lines. */ printf("\n\n"); • /* Loop to display data. */ for (i = 0; i < 4; i++) { printf("Name: %s %s", list[i].fname, list[i].lname); printf("\t\tPhone: %s\n", list[i].phone); } }
/* Loop to input data for four people. */ • The for repetition statement handles all the details of counter controlled repetition. The program operates as follows, when it’s executed, the control variable i is initialized to 0. The loop continuation condition counter < 4 is checked. Because the initial value is 0, the condition is satisfied, so everything in the for loop statement is executed. After, the counter is incremented +1 and the counter is 1. The loop repeats until the condition is not satisfied, which is the fourth repetition. for (i = 0; i < 4; i++) { printf("\nEnter first name: "); scanf("%s", list[i].fname); printf("Enter last name: "); scanf("%s", list[i].lname); printf("Enter phone in 123-4567 format: "); scanf("%s", list[i].phone); }
For every element in that array there will be a separate fname, lname, and phone #. For example, a regular array will have the same data, meaning fname will be the same always. With structures, fname can be modified and used as many times as the size allows it. Since structure entry, array list is the size of four, we can have four different fnames, lnames, and phone #’s.
When scanf is processed, the counter in the array list is processed for fname, the first counter value being 0, allowing us to input whatever first name of 20 characters into the String identifier %s. The same goes for lname and phone.
The structure member operator which is the “.”, is used to access separate members of structures, also called a dot operator. The structure member operator accesses a structure member via the structure variable name which is list.
Lessons Learned • We learned how develop array for structures using the structure member operator
Reference • http://opengroup.org/onlinepubs/007908799/xsh/stdio.h.html