Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction We will study how to broaden the modeling facilities of C by defining our own data types that represent structured collections of data pertaining.

Similar presentations


Presentation on theme: "Introduction We will study how to broaden the modeling facilities of C by defining our own data types that represent structured collections of data pertaining."— Presentation transcript:

1 Introduction We will study how to broaden the modeling facilities of C by defining our own data types that represent structured collections of data pertaining to particular objects. Unlike an array, a structure can have individual components that contain data of different types.

2 Data Structure A single variable of a composite type designed for planets can store a planet’s name, diameter, number of moon, the number of years to complete one solar orbit, and the number of hours to make one rotation on its axis. Each of these data items is stored in a separate component of the structure and can be referenced by using the component name.

3 Structures (User-defined data types)
DATA STRUCTURE- TYPE DEFINITION POINTER TO A STRUCTURE C FUNCTIONS AND STRUCTURE

4 User-Defined Structure Types
A database is a collection of information stored in a computer’s memory or in a disk file. A database is subdivided into records, which normally contain information regarding specific data objects. the structure of the record is determined by the structure of the object’s data type.

5 Structure Type Definition
Before a structure data object can be created or saved, the format of its components must be defined. Although C provides several ways to define structures, we will explore just one approach-defining a new data type for each category of structured objects.

6 C Data Structure So far, we could not mix a type char and a type int within a single data type. However, sometimes we need to mix different data types. How can we do this? With the use of C Structure A collection of data elements of different types HOW to define a C structure?

7 Data Structure - Type Definition
typedef: type definition Allows the user to define another names for a C data type. Declaration: typedef exsiting_data_type New_name_for_the_same_data_type; e.g. typedef int integer;

8 General Synatx: struct structure_name{ data_type member1;
. data_type memberN; }; struct: C keyword data_type: data type for each element member: variable name structure_name: structure name

9 Example: As part of a project for our local observatory, we are developing a database of the planets in our solar system. For each planet, we need to represent information like the following: Name: Jupiter Diameter:142,800 km Moon:16 Orbit time:11.9 yr Rotation time:9.925 hr We can define a structure type planet_t to use in declaring a variable in which to store this information. There must be five components in the structure type, one for each data item. we must specify the name of each component and the type of information stored in each component. we choose the name in the same way we choose all identifiers: The names describe the nature of the information represented. The contents of each component determine the appropriate data type. for example, the planet’s name should be stored in a component that is array of characters.

10 Creating a new type structure allows us to aggregate variables of different types under one logical name. The structure type planet_t has five distinct components. # define STRSIZ 10 struct planet_t { char name [STRSIZ]; int moon; double diameter; double orbi_time; double rotation_time; };

11 Creating a new type The declaration of new types usually happens before the main program, just after the preprocessor directives so that the new types are known in all the functions of the program. Inside a function though, it is necessary, as for the other usual types to declare variables.

12 Sample Structure Definition
We create a new data type here called struct planet_t. planet_t has 5 members of different type. These members are: name [STRSIZ]; moon; diameter; orbi_time; rotation_time; Any variable of type planet_t will have the same members. HOW TO DECLARE VARIABLES OF TYPE STRUCTURE Same way that we declare any other variable of other data types.

13 Example! /* USE OF STRUCTURES */
#include <stdio.h> /* Declare and initialize a structure */ struct MyRecord{ char MyFirstName[20]; char MyLastName[30]; char MyEmployeeNumber[10]; char MySIN[9]; char MyTelNumber[12]; int MyAge; double MySalary; }; main( ){ struct MyRecord VAR1; struct MyRecord VAR2; int VAR3; } NOTE: Name of the structure that we defined here is struct MyRecord.

14 HOW TO ACCESS MEMBERS OF A STRUCTURE
Member of operator OR dot operator Specify the name of the structure followed by a dot followed by the name of the member. e.g. VAR1.MyAge VAR1.MySalary

15 Program! Employee’s Last Name Employee Number Employee’s S.I.N
Employee’s Tel. Number Employee’s Age Employee’s Salary AnnualSalary Calculate Approx. TAX, TaxRate 0.20

16 /* DEMONSTRATES USE OF STRUCTURE*/
/* PROGRAM #113 */ #include <stdio.h> #define TaxRate 0.20 /* Declare structure MyRecord */ struct MyRecord{ char MyFirstName[20]; char MyLastName[30]; char MyEmployeeNumber[10]; char MySIN[9]; char MyTelNumber[12]; int MyAge; double MySalary; }; main( ){ /*Declare variable VAR1, which has data type MyRecord */ struct MyRecord VAR1; double AnnualSalary, ApproxTax; printf("Employee’s First Name: "); gets(VAR1.MyFirstName); printf("Employee’s Last Name: "); gets(VAR1.MyLastName); printf("Employee Number: "); gets(VAR1.MyEmployeeNumber); printf("Employee’s S.I.N: "); gets(VAR1.MySIN); printf("Employee’s Tel. Number: "); gets(VAR1.MyTelNumber); printf("Employee’s Age: "); scanf("%d", &VAR1.MyAge); printf("Employee’s Salary: "); scanf("%lf", &VAR1.MySalary); /* Calculate Approx. TAX */ AnnualSalary=12*VAR1.MySalary; ApproxTax=TaxRate*AnnualSalary; printf("First Name: %s\n", VAR1.MyFirstName); printf("Last Name: %s\n", VAR1.MyLastName); printf("S.I.N: %s\n",VAR1.MySIN); printf("Income: $%lf\n", VAR1.MySalary*12 ); printf("Approx. Tax: $%lf\n", ApproxTax); }

17 NOTE: gets( ) is in <stdio.h>. It reads the entire line of text entered by user.

18 3 ways to define a structure
struct Planet_t{ int moon; float orbit_time; char Name; }; struct Planet_t VAR1; Explanation: We define a data structure called struct planet_t. Then we declare a variable called VAR1 to be of the data type struct planet_t.

19 3 ways to define a structure
int moon; float orbit_time; char Name; } VAR1; Explanation: We define a data structure that does NOT have a name. And immediately we declare a variable called VAR1 to be of that data type.

20 3 ways to define a structure
typedef struct{ int moon; float orbit_time; char Name; } Planet_t; Planet_t VAR1; Explanation: We define a data structure called Planet_t. Then we declare a variable called VAR1 to be of the data type struct Planet_t. NOTE: Please note the difference between methods 1 and 3.

21 typedef The typedef construct provides the possibility to define synonyms to built-in or user-defined data types. For instance, by having typedef int Planet ; defined after the preprocessor directives, I create a new type planet that is exactly like an integer. So I will be able to declare a variable planet x; where x will be in reality an integer. I could also use typedef struct orbit tim; and for now on, we would be able to declare variables with tim only: tim t5; typedef + struct , Quite often we combine the structure definition with the user-defined data type alias associated with it.

22 Placing values in structured variables
1. We can declare and initialize and the same time,The order must reflect the structure definition. 2. We can fill the variables by assignment 3. We can ask the user or read from a file: scanf (“%lf”, & VAR1. orbit_time); fscanf (in, “%s”, VAR1. Name);

23 /* DEMONSTRATES USE OF STRUCTURES */
#include <stdio.h> #define TaxRate 0.20 typedef struct{ char MyFirstName[20]; char MyLastName[30]; char MyEmployeeNumber[10]; char MySIN[9]; char MyTelNumber[12]; int MyAge; double MySalary; } MyRecord; main( ){ MyRecord VAR1, VAR2; double AnnualSalary, ApproxTax; }

24 OUTPUT? /* An example of structures */
#include <stdio.h> #include <string.h> /* the planets structure */ typedef struct { char name [10]; double diameter; int moons; double orbit, rotation; } planets_t; /* the solar systems structure contains a planets type element */ planets_t the_planets[9]; char galaxy [10]; } solar_systems_t; int main(void) { planets_t planet = {"Earth", 1000, 1, 1.0, 24.0}; solar_systems_t solarsystem; printf ("The planet %s has %d moon(s).\n", planet.name, planet.moons); solarsystem.the_planets[9] = planet; strcpy (planet.name, "Jupiter"); planet.diameter = ; planet.moons = 16; planet.orbit = 11.9; planet.rotation = 9.925; printf ("Planet %s has %d moon(s).\n", planet.name, planet.moons); return(0); }

25 Structures and functions
When a structured variable is passed as an input to a function, all of its component values are copied into the components of the function's corresponding formal parameters. Unlike arrays that require pointers to be passed to functions, structures can be passed by value. Of course you can use pointers also if you need multiple results, like we have seen before.

26 C FUNCTIONS AND STRUCTURE
C functions can be declared to be of a structure type, i.e., C functions can return variables of type structure. MyRecord GetEmployeeInfo(void); C functions can also use structures as their arguments. void ShowEmployeeInfo(MyRecord VAR1);

27 /*DEMONSTRATES USE OF FUNCTIONS */
/* PROGRAM # 116 */ #include <stdio.h> #define TaxRate 0.20 typedef struct{ char MyFirstName[20]; char MyLastName[30]; char MyEmployeeNumber[10]; char MySIN[9]; char MyTelNumber[12]; int MyAge; double MySalary; }MyRecord; /*Declare functions */ MyRecord GetEmployeeInfo(void); void ShowEmployeeInfo(MyRecord VAR1); /* MAIN STARTS HERE */ main( ){ MyRecord Employee1; /*Call the function to get the employees information and display it */ Employee1= GetEmployeeInfo( ); ShowEmployeeInfo(Employee1); }

28 /* To get the employee information */
MyRecord GetEmployeeInfo(void){ MyRecord VAR1; printf("Employee's First Name: "); gets(VAR1.MyFirstName); printf("Employee's Last Name: "); gets(VAR1.MyLastName); printf("Employee Number: "); gets(VAR1.MyEmployeeNumber); printf("Employee's S.I.N: "); gets(VAR1.MySIN); printf("Employee's Tel. Number: "); gets(VAR1.MyTelNumber); printf("Employee's Age: "); scanf("%d", &VAR1.MyAge); printf("Employee's Salary: "); scanf("%lf", &VAR1.MySalary); return(VAR1); } /* To show the employee information */ void ShowEmployeeInfo(MyRecord VAR1){ double AnnualSalary, ApproxTax; AnnualSalary=12*VAR1.MySalary; ApproxTax=TaxRate*AnnualSalary; printf("First Name: %s\n", VAR1.MyFirstName); printf("Last Name: %s\n", VAR1.MyLastName); printf("S.I.N: %s\n",VAR1.MySIN); printf("Income: $%lf\n", VAR1.MySalary*12 ); printf("Approx. Tax: $%lf\n", ApproxTax);

29 How to declare arrays of structure?
/* PROGRAM # 117 */ /* DEMONSTRATES USE OF ARRAYS OF STRUCTURES */ #include <stdio.h> #define TaxRate 0.20 #define NumberOfEmployees 2 /*Define structure */ typedef struct{ char MyFirstName[20]; char MyLastName[30]; char MyEmployeeNumber[10]; char MySIN[9]; char MyTelNumber[12]; int MyAge; double MySalary; }MyRecord; /*Define functions to get employee's information and display it*/ MyRecord GetEmployeeInfo(void); void ShowEmployeeInfo(MyRecord VAR1); main( ){ /*Declare an array of structures */ MyRecord Employee[NumberOfEmployees]; int i; /*For loop to input the data */ for(i=0; i< NumberOfEmployees; i++){ Employee[i]= GetEmployeeInfo( ); ShowEmployeeInfo(Employee[i]); }

30 /* To get the employee information */
MyRecord GetEmployeeInfo(void){ MyRecord VAR1; printf("Employee's First Name: "); gets(VAR1.MyFirstName); printf("Employee's Last Name: "); gets(VAR1.MyLastName); printf("Employee Number: "); gets(VAR1.MyEmployeeNumber); printf("Employee's S.I.N: "); gets(VAR1.MySIN); printf("Employee's Tel. Number: "); gets(VAR1.MyTelNumber); printf("Employee's Age: "); scanf("%d", &VAR1.MyAge); printf("Employee's Salary: "); scanf("%lf", &VAR1.MySalary); return(VAR1); }/* To show the employee information */ void ShowEmployeeInfo(MyRecord VAR1){ double AnnualSalary, ApproxTax; /* Calculate Approx. TAX */ AnnualSalary=12*VAR1.MySalary; ApproxTax=TaxRate*AnnualSalary; printf("\nFirst Name: %s\n", VAR1.MyFirstName); printf("Last Name: %s\n", VAR1.MyLastName); printf("S.I.N: %s\n",VAR1.MySIN); printf("Income: $%lf\n", VAR1.MySalary*12 ); printf("Approx. Tax: $%lf\n", ApproxTax); }

31 Q?HOMEWORK!!! /* COMPLEX NUMBERS WITH THE USE OF STRUCTURES */

32

33 USE OF MALLOC( ) To create a array of integers: int array_size; /* declare a pointer of the same type as array */ int *List; scanf(“%d”, &array_size); /* allocate ( array_size X sizeof(int) ) bytes of memory */ /* for the array. */ List= (int *) malloc ( array_size x sizeof(int) ); If we knew the size of the array before we execute the program, we could have simply used the following statement: int List(array_size); NOTE: sizeof( ) operator Determine how much memory is needed for a data type.

34 USE MALLOC( ) TO CREATE A DYNAMIC ARRAY
Declare a pointer of the same type as your array Declare a variable for the size of the array Ask the user for the size of the array Allocate ( array_size X sizeof(data_type) ) bytes of available memory for the array Returns the address of the first byte to the pointer variable List. If the requested bytes are not available, NULL is assigned to List. Don’t forget to type cast the returning pointer.

35 Main difference between malloc( ) and calloc( )
calloc( ) automatically initializes the created array to For integers: to ZERO For characters: to NULL malloc( ) does not do automatic initialization.

36 Q? write a complete program which initializes part of an array of integer grades at the time of its declaration with 6 values and then calls a function to find, return, and print the highest grade.

37 Structures and functions
When a structured variable is passed as an input to a function, all of its component values are copied into the components of the function's corresponding formal parameters. Unlike arrays that require pointers to be passed to functions, structures can be passed by value. Of course you can use pointers also if you need multiple results, like we have seen before.

38 Structures and functions
Let's have a function that prints out a report on the element. void print_element (ele e)‏ { printf ("Name: %s\n", e.name); printf ("Symbol: %s\n", e.symbol); printf ("Weight: %.1lf\n", e.atom_weight); printf ("Atomic Number: %d\n", e.atom_number); } In the main it would be called like print_element (e1);

39 Structures and functions
Let's have a function that compares two elements by comparing the two atomic numbers. It returns true if they are identical. int compare_elements (ele e1, ele e2)‏ { int equal; equal = e1.atom_number == e2.atom_number; return (equal); } In the main it would be called like compare_elements (e1, e[4]);

40 Structures and functions
Let's have a function that fills a structure from the keyboard and then returns it back to the main. ele read_element (void)‏ { ele e; printf ("Enter the name, symbol, atomic weight and atomic number separated by spaces: "); scanf ("%s%s%lf%d",e.name, e.symbol, &e.atom_weight, &e.atom_number); return (e); } In the main it would be called like e1 = read_element( );

41 Structures, functions, and pointers
Let's have a function that does exactly the same thing as the previous one except that it will read two elements and use a pointer parameter for the extra "fake result." ele read_element (ele* eptr) Before going further we need to understand the order of pointer operations. If a pointer variable of type ele is called eptr then to fill its atomic number component, for example, we would be tempted to use scanf (“%d”, &*eptr.atom_number); (notice that eptr is a pointer, the element itself is *eptr). That would be a mistake, however, as we will see on the next slide.


Download ppt "Introduction We will study how to broaden the modeling facilities of C by defining our own data types that represent structured collections of data pertaining."

Similar presentations


Ads by Google