Document Details

HaleNeodymium

Uploaded by HaleNeodymium

Wilfrid Laurier University

Tags

arrays data structures C programming computer science

Summary

This document provides lecture notes on arrays and array operations using the C programming language. It covers topics such as array syntax, data structures, and array traversal by index, making it useful for students learning about computer science concepts. The notes detail the way arrays can be used to store multiple pieces of similar data within a structure.

Full Transcript

Lecture 6 Arrays 1. Array and operations in C 2. Array operations by pointers 1 1. Array and operations The concepts of data structures – A data structure defines how a collection of certain types of data values are represented, organized, stored, and op...

Lecture 6 Arrays 1. Array and operations in C 2. Array operations by pointers 1 1. Array and operations The concepts of data structures – A data structure defines how a collection of certain types of data values are represented, organized, stored, and operated in programs and computers. – In (algorithms) programs, (abstract) data structures are used to represent a collection of data items of certain types together with a set of operations that can be performed on the data items. The simplest data structure is a list of variables – The list of local variables of a function are instanced in contiguous memory space in call stack when the function is called. – The list of global variables are instanced in contiguous memory space in the data region. 2 How to represent a large number of data items? Using a list of variables is doable when the number of data items to be represented is fixed and small. Using a list of variables is not doable when the number of data items is large. Array is a solution to solve this problem for the case when the data items are of the same data type. – Classify data items into groups, a group contains data items of the same type – Use array to represent data items of the group. 3 Concepts of arrays 1. An array is a collection of data values (elements) of the same data type. 2. Array elements are organized in linear order and stored in contiguous memory locations one after another. 3. The linear relation of array elements is determined by the adjacency of elements in memory. These allow us to access any array element directly by its ordering position (index) in memory. 4 Array syntax 1. Array declaration syntax: data_type array_name[length]; data_type -- data type of array elements array_name -- the name (identifier) of array length -- total number of array elements Tell compiler to allocate sizeof(data_type)*length bytes contiguous memory cells (memory block) for the array. 2. Array elements: array_name … array_name[length-1] 3. Array element at index i : array_name[i], for i = 0, …, length-1. – Random accessing array element: given index i, set or get value by array_name[i] – Traversal array by index: for (int i = 0; i