Bilgisayar Mhendislii Blm
Computer Programming
Arrays
GIT Computer Engineering Department
Declaring Arrays
Array: uses consecutive area in memory
Can be referenced as a group
Bilgisayar Mhendislii Blm
Simple memory types: single memory cell Group of related data items: adjacent memory cells
Array elements: each data item
Can be accessed individually
Ex:
double x[8];
Name of the array is x There are eight elements (memory cells) Each element is double
GIT Computer Engineering Department
Declaring Arrays
Ex: double x[8]; Each element can be accessed individually Ex: x[0], x[1],, x[7]
Bilgisayar Mhendislii Blm
x[5] is a subscripted variable 5 is a array subscript
Any integer From 0 to 7 !!!
printf(%.2f, x[0]); x[3] = 12.20; sum = sum +x[5]; x[2] = 13 + x[0]; x[7] = pow(x[1],x[4]); scanf(%lf, &x[0]);
GIT Computer Engineering Department
Example: Student Records
#define NUM_STUDENTS 50 int id[NUM_STUDENTS]; double gpa[NUM_STUDENTS];
Bilgisayar Mhendislii Blm
Parallel arrays
id[i] and gpa[i] are related
First students ID is in id[0] First students GPA is in gpa[0]
GIT Computer Engineering Department
Example: Grading Program
#define NUM_QUEST 10 #define NUM_CLASS_DAYS 5 typedef enum {monday, tuesday, wednesday, thursday, friday} class_days_t; char ansers[NUM_QUEST]; Int score[NUM_CLASS_DAYS];
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Declaring Arrays
Bilgisayar Mhendislii Blm
More than one array can be declared at once double bolts[20], needle, pins[10]; An array can be initialized in declaration int primes[5] = {2, 3, 5, 7, 11}; int primes[] = {2, 3, 5, 7, 11}; Syntax: element_type array_name[size]; element_type array_name[size] = {initialization list};
GIT Computer Engineering Department
Array Subscripts
Subscript specifies array elements
Any expression if type int Must be between 0 to size-1
Bilgisayar Mhendislii Blm
Syntax array_name[subscript] EX:
i = 5; x[i-2] = x[i]-2; x[2*i] = x[i--]; i = (int)x[(int)x[3+1]];
GIT Computer Engineering Department
Using for loops to access arrays
int square[20], i; for (i = 0; i < 20; i++) square[i] = i * i;
Bilgisayar Mhendislii Blm
Processing elements of an array in sequence Ex: Array of squares
Ex: Sum of scores
sum_score = 0; for(today = monday; today <= friday; ++today) scanf(%d, &score[today]); for(today = monday; today <= friday; ++today) sum_score += score[today];
GIT Computer Engineering Department
Program to Print a Table of Differences
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Array Elements as Function Arguments
Bilgisayar Mhendislii Blm
Array elements can be arguments to functions
As other variables Input argument printf(%d, a[1]); Output argument scanf(%d, &a[1]); Input/output argument void do_it(double arg1, double *arg2_p , double *arg3_p); do_it(p, &r, &s); do_it(x[0], &x[1], &x[2]);
GIT Computer Engineering Department
Data Area for Calling Module and do_it
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Array Arguments
Passing whole arrays to functions
Array as a actual parameter
Bilgisayar Mhendislii Blm
array name without subscript in the argument list
Formal parameter is the address of the first array element
Use subscript to access arrays elements Work on the original array not on a copy!...
Ex: Fill an array with the same value void fill_array(int list[], int n, int in_value); fill_array(x, 5, 1)
GIT Computer Engineering Department
Data Areas for fill_array (x, 5, 1);
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Function fill_array
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Array Arguments
Bilgisayar Mhendislii Blm
You can use *list instead of list[] in a formal parameter list Pass an array as a argument int list[]; means parameter is an array int *list; is correct as well
Array argument: passing the address of the first element But, it does not shot that the argument is an array! You should remember that it is array not output parameter
What if the array is only input parameter
Use the const qualifier You can not modify const parameters
Ex: Finding max element in an array
You do not need to modify array elements It is safer to use const qualifier
GIT Computer Engineering Department
Find the Largest Element
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Returning Array Result
Bilgisayar Mhendislii Blm
You can not return an array as a functions return value You should define it as a output parameter
Ex: Adding two arrays
void add_arrays(const double ar1[], const double ar2, doube arrsum[], int n); add_arrays(x, y, x_plus_y, 5);
GIT Computer Engineering Department
Data Areas for add_arrays(x, y, x_plus_y, 5);
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Function to Add Two Arrays
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Partially Filled Arrays
Array is not completely used
Bilgisayar Mhendislii Blm
Some part is reserved for later use Need to reuse the same array for other purpose later
Need to remember the actual number of elements in the array
Declared size should be larger than actual size!.. Ex: Fill an array until a sentinel value is entered
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Driver for Testing fill_to_sentinel
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Stacks
Remember stack?..
Bilgisayar Mhendislii Blm
Only top element can be accessed Operations Push Pop Array as a stack What should be parameters to push and pop
GIT Computer Engineering Department
Stacks
Remember stack?..
Only top element can be accessed Operations Push Pop Array as a stack
Bilgisayar Mhendislii Blm
What should be parameters to push and pop void push(char stack[], char item, int *top, int max_size); char pop(char stack[], int *top); push(s, 2, &s_top, STACK_SIZE); c = pop(s, &s_top);
GIT Computer Engineering Department
Functions push and pop
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Searching an Array
Searching: Locating a particular value Sorting: Ordering the elements
Bilgisayar Mhendislii Blm
Two important problems in processing arrays
Searching: Linear search
Test each elements in the array one by one Until the array is exhausted or the target is found
GIT Computer Engineering Department
Linear Search Algorithm
Bilgisayar Mhendislii Blm
1. Assume the target has not been found 2. Start with the initial array element 3. Repeat while the target is not found and there are more array elements 4. if the current element matches the target 5. set a flag to indicate that target found else 6. Advance to the next array element 7. If the target was found 8. return the target index as the search result else return -1 as the search result
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Sorting an Array
Sorting is quite useful
Bilgisayar Mhendislii Blm
Many operations implemented more efficiently if the data is sorted Output is more understandable if the information is sorted
Selection sort:
Not very efficient but simple Locate the smallest element and move it to location 0 Locate the smallest element in the remaining array starting with location 1 and move it to location 1 Locate the smallest element in the remaining array starting with location 2 and move it to location 2 Continue like this until location n-2
GIT Computer Engineering Department
Selection Sort Algorithm
Bilgisayar Mhendislii Blm
1. for each value of fill from 0 to n-2 2. find index of the smallest element in the unsorted subarray list[fill] through list[n-1] 3. if fill is not the position of the smallest element 4. exchange the smallest element with the one at the position fill
GIT Computer Engineering Department
Trace of Selection Sort
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Multidimensional Arrays
Tables of data Matrices Tic-tac-toe board char tictac[3][3];
Bilgisayar Mhendislii Blm
Array with two or more dimensions
GIT Computer Engineering Department
Multidimensional Arrays
Bilgisayar Mhendislii Blm
Syntax: element-type aname[size1][size2][sizen]; Parameter to a function element-type aname[][size2][sizen] Ex: double table[NROWS][NCOLS]; int tt[7][5][6]; void process_matix(double table[][NCOLS], int nrows); void process_t(int tt[][5][6], int nrows);
GIT Computer Engineering Department
Check Whether Tic-tac-toe Board Is Filled
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Initialization of Multidimensional Arrays
Initialize like one dimensional arrays
Use group of values as rows EX: char tictac[3][3] = {{ , , },{ , , },{ , , }};
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Arrays with Several Dimentions
Bilgisayar Mhendislii Blm
Three dimensional array for enrollment data int enroll[MAXCRS][5][4];
courses: 0 to MAXCRS-1 campuses: 0 to 4 years: 0 to 3
GIT Computer Engineering Department
Three-Dimensional Array enroll
Bilgisayar Mhendislii Blm
Find and display the total number of students in each course Find and display the number of students at each campus
GIT Computer Engineering Department
Case Study: Hospital Revenue
Input: revenue transactions (in a file)
Unit number, quarter, revenue amount
Bilgisayar Mhendislii Blm
Track revenue by unit and by quarter
Output: a table as following
GIT Computer Engineering Department
Case Study: Hospital Revenue
New types
quarter_t unit_t
Bilgisayar Mhendislii Blm
{fall, winter, spring, summer} {emerg, medic, oncol, ortho, psych}
Problem constants
NUM_UNITS NUM_QUARTERS 5 4
Problem inputs
Transaction file double revenue[NUM_UNITS][NUM_QUARTERS]
Problem outputs
double unit_totals[NUM_UNITS] double quarter_totals[NUM_QUARTERS]
GIT Computer Engineering Department
Case Study: Hospital Revenue
Algorithm:
Bilgisayar Mhendislii Blm
1. Scan revenue data, posting by unit and quarter, returning a value to show successor failure of the data scan 2. It the data scan proceeded without error 3. compute unit totals 4. compute quarterly totals 5. Display revenue table and row and column sums
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department
Bilgisayar Mhendislii Blm
GIT Computer Engineering Department