Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 6 Data Types and Arrays. Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing.

Similar presentations


Presentation on theme: "Unit 6 Data Types and Arrays. Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing."— Presentation transcript:

1 Unit 6 Data Types and Arrays

2 Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing array elements to a function Array parameters Returning an array Stacks Searching an array Sorting an array Multidimensional arrays

3 Figure 7.1 Internal Formats of Type int and Type double

4 Figure 7.2 Program to Print Implementation-Specific Ranges for Positive Numeric Data

5 Integer Types in C Table 7.1

6 Floating-Point Types in C Table 7.2

7 Numerical Inaccuracies Representational error – Round-off error – Caused by coding a real number as a finite number of digits – Magnified through repeated computations Cancellation error – Caused by adding a very large number and a very small number Arithmetic underflow – Caused by multiplying very small numbers Arithmetic overflow – Caused by multiplying very large numbers

8 Implicit Conversion Assume variables: int k=5, m=4, n; double x=1.5, y=2.1, z; Operands of different types – Narrow type converted to wider type before calculation k + x /*Evaluates to 6.5 */ Expression evaluated before assignment z = k / m; /*Evaluates to 1, assigns 1.0 */ n = x * y; /* Evaluates to 3.5, assigns 3. */

9 Explicit Conversion Convert data type using a cast int n1, d1; scan_fraction(&n1, &dl); /*integer division performed. n1=2, d1=4, result=0*/ frac = n1 / d1; /*Use cast to force floating point division. Result = 1.5*/ frac = (double)n1 / (double)n2;

10 ASCII Characters ASCII CodesRepresent 32 through 126Printable characters 48 through 570-9 65 through 90A-Z 97 through 122a-z 0 through 31 and 127Non-printable characters

11 Figure 7.3 Program to Print Part of the Collating Sequence

12 Enumerated Types Used to improve program readability typedef enum {entertainment, rent utilities, food, clothing } expense_t; rent is an enumeration constant with the value 1 Add typedef declarations immediately after preprocessor directives.

13 Figure 7.4 Enumerated Type for Budget Expenses

14 Figure 7.4 Enumerated Type for Budget Expenses (cont’d)

15 1-15 Figure 7.4 Enumerated Type for Budget Expenses (cont’d)

16 Figure 7.5 Accumulating Weekday Hours Worked continued

17 Figure 7.5 Accumulating Weekday Hours Worked (cont’d)

18 Figure 7.6 Six Roots for the Equation f(x) = 0

19 Figure 7.7 Using a Function Parameter

20 Figure 7.8 Change of Sign Implies an Odd Number of Roots

21 Figure 7.9 Three Possibilities That Arise When the Interval [xleft, xright] Is Bisected

22 Figure 7.10 Finding a Function Root Using the Bisection Method

23 Figure 7.10 Finding a Function Root Using the Bisection Method (cont’d)

24

25 Figure 7.11 Sample Run of Bisection Program with Trace Code Included

26 Figure 8.1 The Eight Elements of Array x

27 Parallel Arrays #define NUM_STUDENTS 50 int id[NUM_STUDENTS]; double gpa[NUM_STUDENTS];

28 Array of Characters #define NUM_QUEST 10 char answer[NUM_QUEST]; answer[0] = 'T'; answer[1] = 'F'; answer[2] = 'F'

29 Accessing an Array with an Enumerated Constant #define NUM_CLASS_DAYS 5 typedef enum {monday, tuesday, wednesday, thursday, friday} class_days_t; int score[NUM_CLASS_DAYS]; score[monday] = 9; score[Tuesday] = 7;

30 Figure 8.2 Arrays answer and score

31 Array Initialization When initializing array in its declaration, omit the size. int prime_lt_100[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};

32 Processing an Array Using a Loop Use a counter-controlled loop #define SIZE 11 int square[SIZE], i; for (i= 0; i < SIZE; ++i) square[i] = i * i;

33 Figure 8.3 Program to Print a Table of Differences

34 Figure 8.3 Program to Print a Table of Differences (cont’d)

35 Array Elements as Function Arguments Array elements can be used as input or output arguments. Consider the function with the prototype: void do_it (double arg_1, double *arg2_p, double *arg3_p); Pass array x elements as arguments: do_it(x[0], &x[1], &x[2]); input argument output arguments

36 Figure 8.4 Data Area for Calling Module and Function do_it

37 Figure 8.8 Diagram of a Function That Computes an Array Result

38 Arrays as Parameters Passing an array as a parameter passes the pointer to the array, not a copy. – Function can modify the array. Function prototype that accepts an array: void fill_array (int list[], int n, int, in_value); /* Clearer */ or void fill_array (int *list, int n, int, in_value);

39 Figure 8.5 Function fill_array

40 Passing an Array Argument Because an array argument refers to a memory location, no subscript is required: int x[5]; fill_array(x, 5, 1); /* better */ or fill_array(&x[0], 5, 1);

41 Figure 8.6 Data Areas Before Return from fill_array (x, 5, 1);

42 Preventing Modification To prevent an array from being modified by a function, use the const keyword in the function declaration: int get_min_sub(const double data[], int data_size) {…}

43 Figure 8.7 Function to Find the Largest Element in an Array

44 Figure 8.9 Function to Add Two Arrays

45 Figure 8.10 Function Data Areas for add_arrays(x, y, x_plus_y, 5);

46 Figure 8.11 Diagram of Function fill_to_sentinel

47 Figure 8.12 Function Using a Sentinel- Controlled Loop to Store Input Data in an Array

48 Figure 8.13 Driver for Testing fill_to_sentinel

49 Stack A B C D

50 Figure 8.14 Functions push and pop

51 Figure 8.14 Functions push and pop (cont’d)

52 Array Search Algorithm Assume the target has not been found. Start with the initial array element Repeat while the target is not found and there are more array elements – If the current element matches the target Set a flag to indicate that the target has been found. – Else Advance to the next array element. If the target was found: – Return the target index as the search result. Else – Return -1 as the search result.

53 Array Search Flowchart Set flag to false Set counter to 0 flag = true or counter = # of elements current element = target? increment counter set flag = true flag= true? return -1 return counter N N N Y Y Y

54 Figure 8.15 Function That Searches for a Target Value in an Array

55 Algorithm for Selection Sort For each value of fill from 0 to n-2 – Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n-1] – If fill is not the position of the smallest element (index of min): Exchange the smallest element with the one at position fill.

56 Figure 8.16 Trace of Selection Sort

57 Figure 8.17 Function select_sort

58 Two-dimensional Array Two-dimensional array char tictac[3][3]; Function that accepts a two-dimensional array void make_move(char b[][3], int posx, int posy, char piece) { } or void make_move(char b[3][3], int posx, int posy, char piece) { }

59 Figure 8.18 A Tic-tac-toe Board Stored as Array tictac

60 Figure 8.19 Function to Check Whether Tic-tac-toe Board Is Filled

61 Initializing a Two-dimensional Array char tictac[3][3] = { {' ', ' ', ' '}, {' ', ' ', ' '} }

62 Arrays with Multiple Dimensions ANSI requires C compilers to allow arrays of six dimensions. Two- and three- dimensional arrays are most common int enroll[MAXCRS][5][4]; course campus year

63 Figure 8.20 Three-Dimensional Array enroll

64 Processing a Three-Dimensional Array /* Finds and displays number of students in each course */ for (course = 0; course < MAXCRS; ++course) { crs_sum = 0; printf(“Number of students in course %d is %d\n”, course, crs_sum): } for (campus = 0; campus < 5; ++campus) { for (cls_rank = 0; cls_rank < 4; ++cls_rank) { crs_sum += enroll[course][campus][cls_rank]; }

65 Another Three-Dimensional Array Example /* Finds and displays number of students at each campus */ for (campus = 0; campus < 5; ++course) { campus_sum = 0; printf(“Number of students at campus %d is %d\n”, campus, campus_sum): } for (course = 0; course < MACRS; ++campus) { for (cls_rank = 0; cls_rank < 4; ++cls_rank) { campus_sum += enroll[course][campus][cls_rank]; }

66 Figure 8.21

67 Figure 8.22 Hospital Revenue Summary Main Function

68 Figure 8.23 Function scan_table and Helper Function initialize

69 Figure 8.23 Function scan_table and Helper Function initialize (cont’d)

70

71 Figure 8.24 Function display_table and Helper Functions display_quarter and whole_thousand

72 Figure 8.24 Function display_table and Helper Functions display_quarter and whole_thousands (cont’d)


Download ppt "Unit 6 Data Types and Arrays. Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing."

Similar presentations


Ads by Google