Docsity

C Programming for Engineers Arrays, Study Guides, Projects, Research of C programming

Partial preview of the text

Download C Programming for Engineers Arrays and more Study Guides, Projects, Research C programming in PDF only on Docsity!

C Programming for

Engineers

Arrays

ICEN 360– Spring 2017

Prof. Dola Saha

Compiling your own code

Linking with Math Library

Ø gcc – o object_filename c_file.c – lm § - l link to the library § - lm is specific for math Ø Run the object file § ./object_filename

Array

Ø Arrays are data structures consisting of related data

items of the same type.

Ø A group of contiguous memory locations that all have the

same type.

Ø To refer to a particular location or element in the array § Array’s name § Position number of the particular element in the array

Array indexing

Ø The first element in every array is the zeroth element.

Ø An array name, like other identifiers, can contain only

letters, digits and underscores and cannot begin with

a digit.

Ø The position number within square brackets is called

an index or subscript.

Ø An index must be an integer or an integer expression

§ array_name[x], array_name[x+y], etc. Ø For example, if a = 5 and b = 6 , then the statement o c[a + b] += 2 ; adds 2 to array element c[11].

Array in memory

Ø Array occupies contiguous space in memory Ø The following definition reserves 12 elements for integer array c, which has indices in the range 0-11. o int c[ 12 ]; Ø The definition o int b[ 100 ]; double x[ 27 ]; reserves 100 elements for integer array b and 27 elements for double array x. Ø Like any other variables, uninitialized array elements contain garbage values.

Use of size_t

Ø Notice that the variable i is declared to be of type size_t, which according to the C standard represents an unsigned integral type. Ø This type is recommended for any variable that represents an array’s size or an array’s indices. Ø Type size_t is defined in header <stddef.h>, which is often included by other headers (such as <stdio.h>). Ø [Note: If you attempt to compile Fig. 6.3 and receive errors, simply include <stddef.h> in your program.]

Initializing with initializer list

Output

Initializing without array size

Ø If the array size is omitted from a definition with an

initializer list, the number of elements in the array will be the number of elements in the initializer list. Ø For example, o int n[] = { 1 , 2 , 3 , 4 , 5 }; would create a five-element array initialized with the indicated values.

Initializing to even list

Output

Adding elements of an array

Classwork Assignment

Ø Initialize an array of size with an initializer list and find the maximum element.

Using Arrays to Summarize Poll (2)

Histogram with Array elements (1)