Lec 07 Multi-Dimensional Arrays Intro To Structures

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

EEE 11

Lec 07 Multi-Dimensional Arrays Intro to Structures

Review
int myarray1[] = {2, 1, 15, 20}; int iVar = 3; int myarray2[] = {25, 30, 40, 70}; What is sizeof(myarray1)? Which of the expressions are valid/safe and what do they do?
myarray1[1]++; myarray1 = myarray2; myarray2[0] = iVar; myarray2[iVar] = myarray2[myarray1[0]]; scanf(%d, &(myarray1[3])); int myarray3[iVar];

Review
int myarray1[] = {2, 1, 15, 20}; int iVar = 3; int myarray2[] = {25, 30, 40, 70}; What is sizeof(myarray1)? sizeof(int)*4 = 4*4 = 16 Which of the expressions are valid/safe and what do they do?
myarray1[1]++; myarray1 = myarray2; /* Invalid */ myarray2[0] = iVar; myarray2[iVar] = myarray2[myarray1[0]]; scanf(%d, &(myarray1[3])); int myarray3[iVar]; /* Invalid */

Review
How do you declare a function parameter that is an array of int?
void func( <what should be here?>, int iSize) { while (iSize > 0) { /* myarray is an integer array */ printf("%d\n", myarray[--iSize]); } }

Review
int myarray1[] = {2, 1, 15, 20, -1};

What is being passed to func() for each of the expressions?


func(myarray1[0]); func(myarray1); func(myarray1[5]);

Sample 07-01
Implement the following functions int get_sum(int numbers[ ], int count)
Returns the sum of the numbers in the array

float get_average(int numbers[ ], int count)


Returns the average value of the numbers in the array

Demonstrate modularity

Sample 07-02
Demo: functions can modify array contents void myreset(int numbers[ ], int count)
set all elements in numbers to 0

void myabsval(int numbers[ ], int count)


set all elements in numbers to its absolute value

Review
char myarray[10] = {a, b, c, '\0'};

What is sizeof(myarray)? What is myarray[1]? What is strlen(myarray)? How do I access c? Is the code below valid?
char tmp[10]=abc;

Review
char myarray[10] = {a, b, c, '\0'};

What is sizeof(myarray)? 10 What is myarray[1]? 'b' What is strlen(myarray)? 3 How do I access c? myarray[2] Is the code below valid? Yes
char tmp[10]=abc;

Sample 07-03
Implement using arrays: int mystrlen(char input[ ]);
Same as strlen(); Displays the number of characters in the string

Demo:
fgets( ) char arrays with '\0' inserted in the middle

Sample 07-04
Implement using arrays: void mytoupper(char input[ ]);
Capitalizes all characters in the string

Sample 07-05
Implement using arrays: int mystrcmp(char str1[ ], char str2 [ ])
Same as strcmp; compares two strings

Implement a program that asks the user to guess a secret code (e.g. eee11)
Give hints like higher, lower

Multidimensional Arrays

Multidimensional Array

Can be thought of as an array of Arrays Can be used to represent data like:


Matrix List of words like: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

EEE11

Multidimensional Array Declaration

Data type

Column size

int matrix[2][5] = { {1, 2, 3, 4, 5} , {6, 7, 8, 9, 10}};


Name Row size

EEE11

Optional Parts of a Multidimensional Array Declaration


Warnings appear if there are no internal braces, but it will still work

int matrix[ ][5] = { {1, 2, 3, 4, 5} , {6, 7, 8, 9, 10}};


Row size: (leftmost size) Only if there is initial value. The compiler automatically allocates enough memory to accommodate the initial values

EEE11

Visualization - Multidim Arrays


1d Array:
int aArray1d[5];
A collection of five (5) integers

Visualization Multidim Arrays


2d Array:
int aArray2d[2][5];
A collection of two (2) 5-integer array (10 integers in all)

Visualization Multidim Arrays


int aArray2d[2][5];
0 0 1 1 2 3 4

aArray2d[1][3]

Accessing the Elements of a Multidimensional Array

Suppose we want to print the numbers in matrix[][]:


int matrix[2][5] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10} }; int i; int j; for(i=0; i<2; i++) { for(j=0; j<5; j++) printf("%d ", matrix[i][j]); /* (matrix[i])[j] */ printf("\n");

EEE11

List - 2D Array of char


Recall that a string is a 1D-array of char 2D-array of char can be thought of as a collection of several 1D-array of char Example: {'d', 'e', 'f', '\0' } }; /* alpha[0] ==> {'a', 'b', 'c', '\0'} ==> abc alpha[1] ==> {'d', 'e', 'f', '\0'} ==> def */

char alpha[2][4] = { {'a', 'b', 'c', '\0' },

EEE11

Using Lists
char alpha[2][4] = { {'a', 'b', 'c', '\0' }, {'d', 'e', 'f', '\0' } }; int i; for (i=0; i<2; i++) printf("%s\n", alpha[i]);

EEE11

Using lists
char days[7][10] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; int i; for (i=0; i<7; i++) puts(days[i]); /* printf("%s\n", days[i]); */
EEE11

Using lists
char temp[ ] = testing; char sample[7][10]; int i; for (i=0; i<7; i++) strcpy(sample[i], temp);

EEE11

Sample 07-06

Use a 2D array (list) to implement a simple number to word converter (0-9 only)

EEE11

Sample 07-07

Use a 2D array to store a list of 5 names, and display them.

Modify the code so the content of the list is in all caps

EEE11

3D Arrays
3d Array:
int aArray3d[4][2][5];
A collection of four (4), two(2) 5-integer array (40 integers in all)

2x5 array

Accessing 3D arrays
int aArray3d[4][2][5];
0

1
0 1 2 3 4 0 1

aArray3d[2][1][3]

N-dimensional Array

In practice, programmers avoid using array dimension >2

becomes hard to understand/maintain

EEE11

Multidim Array Parameters


What does func() do?
/* NUM_ROWS and NUM_COLS are constants */ void func (int aMatrix[NUM_ROWS][NUM_COLS]) { int iRows, iCols; for (iRows = 0; iRows < NUM_ROWS; iRows++) { for (iCols = 0; iCols < NUM_COLS; iCols++) aMatrix[iRows][iColumns] = 0; } }

Intro to Structures

So far, we know how to represent


a variable (of basic data types) an ordered set of the same data type (array) student (name, ID #) Credit card

How do we represent the following?


EEE11

31

Structure

Collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling

EEE11

32

Structure for student Info


struct student_info { char name[32]; unsigned long long number; /*why ull?*/ };

EEE11

33

Structure for Student Info


Declaring a new data type Tag is the identifier of the container of the structure

struct student_info {
Variables or Members

char name[32]; ... };


Semicolon

EEE11

Braces as delimiter

34

Structure Mandatory Parts


keyword

struct { };
Semicolon

Braces
EEE11 35

IMPORTANT

Declaration of a structure does NOT create a variable It is just a new data type

EEE11

36

Declaration and Initialization of Structure


Data type Variable name

struct student_info bayani = { Jose Rizal, 189800001 }; /* 1 to 1 correspondence */

EEE11

37

Accessing structure members

We use the DOT operator:


struct student_info bayani = { "Jose Rizal", 189800001 }; printf(%s\n, bayani . name); /* bayani <dot> name = the name member */ /* %llu is for unsigned long long*/ printf("%llu\n",bayani.number);

EEE11

38

Dot operator
/*We can also modify each member*/ snprintf(bayani.name, sizeof(bayani.name), "%s", "Andres Bonifacio"); /*OR*/ strncpy(bayani.name, "Andres Bonifacio", sizeof(bayani.name) - 1);

EEE11

39

Structure members behave like a normal variable


/* unsigned long long variable */ bayani.number = 10; bayani.number++; bayani.number *= 100; scanf(%llu, &(bayani.number)); /* char array variable */ bayani.name[0] = 'a'; bayani.name[1] = '\0';
EEE11 40

sizeof a Structure

sizeof a Structure is just the sum of the sizeof its members

EEE11

41

sizeof Student Info


struct student_info { char }; printf(%d bytes\n, sizeof(struct student_info)); /* 40 bytes */ name[32]; /* 32 bytes */ /* 8 bytes */ unsigned long long number;

EEE11

42

Sample 07-07

Define candidate structure


Name Votes

[80 characters] [integer]

Declare 2 variables, president1, president2


Get 9 votes, asking users to pick which candidate Display winner at the end

EEE11

43

References

Largely from actual coding and sheer curiosity If you are looking for a hard copy:

The C Pogramming Language by K&R Problem Solving and Program Design in C by Hanly Open source codes

EEE11

44

You might also like