0% found this document useful (0 votes)
59 views

Chapter 6 - Arrays: Outline

The document discusses various topics related to arrays in C programming. It introduces arrays as structures that store related data items. It describes how to declare, define, initialize and access array elements. It also discusses passing arrays to functions, sorting arrays using bubble sort, and searching arrays using linear and binary search methods. Various examples are provided to illustrate concepts related to one-dimensional and two-dimensional arrays, character arrays, string handling functions and more.

Uploaded by

Anurag Damera
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Chapter 6 - Arrays: Outline

The document discusses various topics related to arrays in C programming. It introduces arrays as structures that store related data items. It describes how to declare, define, initialize and access array elements. It also discusses passing arrays to functions, sorting arrays using bubble sort, and searching arrays using linear and binary search methods. Various examples are provided to illustrate concepts related to one-dimensional and two-dimensional arrays, character arrays, string handling functions and more.

Uploaded by

Anurag Damera
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Chapter 6 - Arrays

Outline
6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays Case Study: Computing Mean, Median and Mode Using Arrays Searching Arrays Multiple-Subscripted Arrays

6.1 Introduction
Arrays
Structures of related data items Static entity same size throughout program Dynamic data structures discussed in Chapter 12

6.2 Arrays
Array To refer to an element, specify
Array name Position number

Name of array (Note that all elements of this array have the same name, c)
c[0] -45 6 0 72

Group of consecutive memory locations c[1] c[2] Same name and type
c[3]

c[4]
c[5] c[6] c[7] c[8] c[9] c[10] c[11]

1543
-89 0 62 -3 1 6453 78

Format:
arrayname[ position number ]
First element at position 0 n element array named c: c[ 0 ], c[ 1 ]...c[ n 1 ]

Position number of the element within array c

6.2 Arrays
Array elements are like normal variables
c[ 0 ] = 3; printf( "%d", c[ 0 ] );
Perform operations in subscript. If x equals 3

c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Array Elements & Indices


Each member of an array is identified by unique index or subscript assigned to it

The dimension of an array is determined by the number of indices needed to uniquely identify each element.

An index is a positive integer enclosed in [ ] placed immediately after the array name.

An index holds integer values starting with zero.

An array with 11 elements will look like -

Defining an Array
An array has some particular characteristics and has to be defined with them. These characteristics include -

which indicates the location of the first member of the array.

a constant evaluating to a +ve value

Defining an Array - I
An array is defined in the same way as a variable is defined except that the array name is followed by one or more expressions, enclosed within square brackets [ ], specifying the array dimension.

Norms with Arrays


All elements of an array are of the same type.

Each element of an array can be used anywhere that a variable is allowed or required.

Each element of an array can be referenced using a variable or an integer expression.

Arrays can have their data types like int, char, float

Array Handling In C

Array Handling In C
An array is treated differently from a variable in C. Two arrays, even if they are of the same type and size cannot be tested for equality.

It is not possible to assign one array directly to another.

Values cannot be assigned to an array on the whole, instead values are assigned to the elements of the array.

Array Initialization
Each element of an Automatic array needs to be initialized separately. In the following example the array elements have been assigned valued using the for loop.

In case of extern and static arrays, the elements are automatically initialized to zero.

Reading Unknown Number Of Elements


Solution Consider-the following case A program is written to calculate the average of given numbers and print it. The total numbers to be input can range from 1 to 50. An array would naturally be considered the best way to store the numbers. But a problem may arise in when fewer numbers than the maximum length of the array is entered.

Strings / Character Arrays


A string can be defined as a character type array, which is terminated by a null character. Each character in a string occupies one byte and the last character of a string is \0 (Backslash zero)

Consider the following example -

Strings / Character Arrays


Output -

The input for the above is of 4 characters and the 5th character is the null character.

The above output is for an input of 5 characters.

String Functions
C supports a wide range of string functions, which are found in the standard header file <string.h> Some of them are listed below -

Two Dimensional Arrays


The simplest and the most commonly used multi - dimensional array is the two - dimensional array. A two-dimensional array can be thought of as an array of two single dimensional arrays.

A two - dimensional array looks like a school time-table consisting of rows and columns.

A two dimensional array is declared as -

Initialization of Multidimensional Arrays

The result of the above assignment will be as follows :

Initialization of Multidimensional Arrays - I

Initialization of Multidimensional Arrays - II


The result of the assignment will be as follows :

A two - dimensional string array is declared in the following manner :

6.3 Declaring Arrays


When declaring arrays, specify
Name Type of array Number of elements arrayType arrayName[ numberOfElements ]; Examples: int c[ 10 ]; float myArray[ 3284 ];

Declaring multiple arrays of same type


Format similar to regular variables Example: int b[ 100 ], x[ 27 ];
20

6.4 Examples Using Arrays


Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough initializers, rightmost elements become

int n[ 5 ] = { 0 }

All elements 0
If too many a syntax error is produced syntax error C arrays have no bounds checking

If size omitted, initializers determine it


int n[ ] = { 1, 2, 3, 4, 5 };
5 initializers, therefore 5 element array
21

6.4 Examples Using Arrays


Character arrays
String first is really a static array of characters Character arrays can be initialized using string literals
char string1[] = "first"; It is equivalent to

Null character '\0' terminates strings string1 actually has 6 elements


char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };

Can access individual characters string1[ 3 ] is character s Array name is address of array, so & not needed for

scanf

scanf( "%s", string2 );

Reads characters until whitespace encountered Can write beyond end of array, be careful
22

1 2 3 4 5 6

/* Fig. 6.10: fig06_10.c Treating character arrays as strings */ #include <stdio.h>

1. Initialize strings
int main() {

7
8 9 10 11 12 13 14 15 16 17 18 19 20 21 }

char string1[ 20 ], string2[] = "string literal";


int i;

2. Print strings

2.1 Define loop


printf(" Enter a string: "); scanf( "%s", string1 ); printf( "string1 is: %s\nstring2: is %s\n" "string1 with spaces between characters is:\n", string1, string2 ); for ( i = 0; string1[ i ] != '\0'; i++ ) printf( "%c ", string1[ i ] );

2.2 Print characters individually 2.3 Input string 3. Print string

printf( "\n" ); return 0; string: Hello there is: Hello is: string literal with spaces between characters is: o

Enter a string1 string2 string1 H e l l

Output Program 2000 Prentice Hall, Inc. 23


All rights reserved.

6.5 Passing Arrays to Functions


Passing arrays
To pass an array argument to a function, specify the name

of the array without any brackets


int myArray[ 24 ]; myFunction( myArray, 24 );

Array size usually passed to function


Arrays passed call-by-reference Name of array is address of first element Function knows where the array is stored Modifies original memory locations

Passing array elements


Passed by call-by-value Pass subscripted name (i.e., myArray[ 3 ]) to function
24

6.5 Passing Arrays to Functions


Function prototype
void modifyArray( int b[], int arraySize );
Parameter names optional in prototype int b[] could be written int [] int arraySize could be simply int

25

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

/* Fig. 6.13: fig06_13.c Passing arrays and individual array elements to functions */ #include <stdio.h> #define SIZE 5

1. Function definitions
void modifyArray( int [], int ); void modifyElement( int ); /* appears strange */

int main() { int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; printf( "Effects of passing entire array call " "by reference:\n\nThe values of the " "original array are:\n" ); for ( i = 0; i <= SIZE - 1; i++ ) printf( "%3d", a[ i ] );

2. Pass array to a function 2.1 Pass array element to a function Entire arrays passed3. Print call-byreference, and can be modified

printf( "\n" ); modifyArray( a, SIZE ); /* passed call by reference */ printf( "The values of the modified array are:\n" ); for ( i = 0; i <= SIZE - 1; i++ ) printf( "%3d", a[ i ] );

Array elements passed call-byvalue, and cannot be modified

printf( "\n\n\nEffects of passing array element call " "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] ); modifyElement( a[ 3 ] ); printf( "The value of a[ 3 ] is %d\n", a[ 3 ] ); return 0; }

2000 Prentice Hall, Inc.


All rights reserved. 26

33 34 void modifyArray( int b[], int size ) 35 { 36 37 38 39 40 } 41 42 void modifyElement( int e ) 43 { 44 45 } Effects of passing entire array call by reference: The values of 0 1 2 3 The values of 0 2 4 6 the original array are: 4 the modified array are: 8 printf( "Value in modifyElement is %d\n", e *= 2 ); for ( j = 0; j <= size - 1; j++ ) b[ j ] *= 2; int j;

3.1 Function definitions

Program Output

Effects of passing array element call by value:

The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6

2000 Prentice Hall, Inc.


All rights reserved. 27

6.6 Sorting Arrays


Sorting data
Important computing application Virtually every organization must sort some data

Bubble sort (sinking sort)


Several passes through the array Successive pairs of elements are compared If increasing order (or identical ), no change If decreasing order, elements exchanged Repeat

Example:

original: 3 4 2 6 7 pass 1: 3 2 4 6 7 pass 2: 2 3 4 6 7 Small elements "bubble" to the top


28

6.8 Searching Arrays: Linear Search and Binary Search


Search an array for a key value Linear search
Simple Compare each element of array with key value Useful for small and unsorted arrays

29

6.8 Searching Arrays: Linear Search and Binary Search


Binary search
For sorted arrays Compares middle element with key If equal, match found If key < middle, looks in first half of array If key > middle, looks in last half 5 Repeat Very fast; at most n steps, where 2n > number of

elements
30 element array takes at most 5 steps
25 > 30 so at most 5 steps
30

6.9 Multiple-Subscripted Arrays


Multiple subscripted arrays
Tables with rows and columns (m by n array)
Row 0 Row 1 Row 2

Like matrices: specify row, then column

Column 0 Column 1 Column 2 Column 3

a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ] a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ] Column subscript Array name Row subscript

31

6.9 Multiple-Subscripted Arrays


1 2 4

Initialization
Initializers grouped by row in braces
1 3

int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
0 4

If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

Referencing elements
Specify row, then column printf( "%d", b[ 0 ][ 1 ] );

32

Session 7

What is a Pointer?
A pointer is a variable, which contains the address of a memory location of another variable.
If one variable contains the address of another variable, the first variable is said to point to the second variable.

A pointer provides an indirect method of accessing the value of


a data item.

Pointers can point to variables of other fundamental data types like int, char, or double or data aggregates like arrays or structures.

What are Pointers used for?


Pointers are used in situations when passing actual values is difficult or not desired. Some of the situations where pointers can be used are -

To return more than one value from a function. To pass arrays and strings more conveniently from one function to another.

To manipulate arrays easily by moving pointers to them instead of moving the arrays itself.

To allocate memory and access it (Direct Memory Allocation).

To create complex data structures, such as linked lists.

Pointer Variables
If a variable is to be used as a pointer, it must be declared. A pointer declaration consists of a base type, a *, and a variable name.

General declaration syntax is : -

For Example:

Pointer Operators
There are 2 special operators which are used with pointers :

The second operator unary operator and it of &. It the memory address The & operator is a * is the complement returns is a unary operator andthe operand.value contained in the memory location pointed to by of returns the the pointer variables value.

Assigning Values To Pointers


Values can be assigned to pointers through the & operator. The assignment statement will be -

Here the address of var is stored in the variable ptr_var.

It is also possible to assign values to pointers through another pointer variable pointing to a data item of the same data type.

Assigning Values To Pointers - I


Variables can be assigned values through their pointers as well.

The above declaration will assign 10 to the variable var if ptr_var points to var.

Pointer Arithmetic
Addition and subtraction are the only operations that can be performed on pointers.
Take a look at the following example :

Let var be an integer type variable having the value 500 and stored at the address 1000.

Then ptr_var has the value 1000 stored in it. Since integers are 2 bytes long, after the expression ptr_var++; ptr_var will have the value as 1002 and not 1001.

Some More Examples

Each time a pointer is incremented, it points to the memory location of the next element of its base type.

Each time it is decremented it points to the location of the previous element.

All other pointers will increase or decrease depending on the length of the data type they are pointing to.

Pointer Comparisons
Two pointers can be compared in a relational expression provided both the pointers are pointing to variables of the same type. Consider that ptr_a and ptr_b are 2 pointer variables, which point to data elements a and b. In this case the following comparisons are possible:

Pointers as Function Arguments


When pointers are passed to a function: The program routine can access the variables that lie within the scope of the function.

The address of the data item is passed and thus the function can freely access the contents of that address from within the function

Pointers as Function Arguments - I


The function as well as the calling routine recognizes any change made to the contents of the address.

In this way, function arguments permit data-items to be altered in the calling routine and the function.

When the arguments are pointers or arrays, a call by reference is made to the function as opposed to a call by value for the variable arguments.

Function Definition
indicates that the arguments ptr_str points to type char and ptr_int points to type int.

The function can be invoked by the statement,

where pstr is declared as a pointer and the address of the variable var is passed.

Function Definition - I
Assigning a value through,

in the function can now assign values to the variable var in the calling routine, enabling a two way transfer to and from the function.

Pointers and Single Dimensional Arrays


The address of an array element can be expressed in two ways : By writing the actual array element preceded by the ampersand sign.

By writing an expression in which the subscript is added to the array name.

The following program shows the relationship between array elements and their addresses.

Pointers and Single Dimensional Arrays

Pointers and Multi Dimensional Arrays


A two-dimensional array can be defined as a pointer to a group of contiguous one-dimensional arrays.

A two-dimensional array declaration can be written as :

instead of

Pointers & Strings


Using strings as pointers can be explained with the help of the

Allocating Memory
The following example uses a two-dimensional array to record marks of 5 students for 10 subjects.

It uses pointers and malloc() function, to assign memory.

You might also like