arrays and strings lecture 30. summary of previous lecture in the previous lecture we have covered ...

Post on 19-Jan-2016

221 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Arrays and Strings

Lecture 30

Summary of Previous Lecture In the previous lecture we have covered

Functions Prototypes Variable Scope

Pointers Introduction to pointers Pointers and function parameters

Today’s Topics

ArraysDeclarationInitializationInput/OutputPassing arrays to functions

Today’s Topics Character Strings

Representation Declaration Index of a char in a stringString operations Common mistakes

Summary

Array An array is a way of lining up objects in

rows and columns so they are easier to count or multiply.

The rows run from left to right.

Array Row: Left to right.

This array has 3 rows

Array The columns run from top to bottom. This

array has four columns.

Array Column:

Arrays in C Program A group of contiguous memory locations used

to store a series of related values.

The array name is a pointer to the first element

All values have the same type

Individual elements of an array are accessed via an integer index: array[index]

Referencing Array Elements Element indices start at 0: array[0] is the first

element We can reference array elements by using the array’s

subscript. The first element has a subscript of 0. The last element in an array of length n has a subscript of n-1.

When we write a program, we refer to an individual array element using indexing. To index a subscript, use the array name and the subscript in a pair of square brackets:anyArray[12];

Array Example

Declaring an Array To declare an array, we need to specify its

data type, the array’s identifier and the size:type arrayName [arraySize];

The arraySize is constant Before using an array we must declare and

initialize it!

Declaration Examples

Initialization at Array Definition Arrays may be initialized with a list of

suitable values We can initialize fixed-length array

elements when we define an array. If we initialize fewer values than the length

of the array, C assigns zeroes to the remaining elements.

Array Initialization Examples

Arrays and Loops Since we can refer to individual array elements

using numbered indexes, it is very common for programmers to use for loops when processing arrays.

from Figure 8-5 in Forouzan & Gilberg, p. 462

Accessing Elements To access an array’s element, we need to provide an

integer value to identify the index we want to access. We can do this using a constant:scores[0];

We can also use a variable:for(i = 0; i < 9; i++){

scoresSum += scores[i];}

Inputting Values using a for Loop

Once we know the length of an array, we can input values using a for loop:

arrayLength = 9;

for (j = 0; j < arrayLength; j++){

scanf(“%d”, &scores[j]);}//end for

Assigning Values to Individual Elements

We can assign any value that reduces to an array’s data type:scores[5] = 42;scores[3] = 5 + 13;scores[8] = x + y;scores[0] = pow(7, 2);

Example: MonthlyRainfall

Problem: using Rainfall Table• input month• output mean rainfall for that month

month mean rainfall (in mm)0 301 402 453 954 1305 2206 2107 1858 1359 80

10 4011 45

Rainfall Table

#include <stdio.h>

int main(){ int month; int table[12] = { 30, 40, 45, 95, 130, 220, 210, 185, 135, 80, 40, 45 }; printf("Enter month: "); scanf("%d", &month); printf("Average rainfall: %d mm.\n", table[month-1]); return 0;} rainfall1.c

Example… : MonthlyRainfall (v.1)

#include <stdio.h>

int main(){ int month; int table[12] = { 30, 40, 45, 95, 130, 220, 210, 185, 135, 80, 40, 45 }; printf("Enter month: "); scanf("%d", &month); printf("Average rainfall: %d mm.\n", table[month-1]); return 0;} rainfall1.c

Example (cont.): MonthlyRainfall (v.1)

#include <stdio.h>#define NMONTHS 12

/* Store and print rainfall */

int main(){ int data[NMONTHS]; int month; for ( month=0; month < NMONTHS; month++ ) { scanf("%d", &data[month] ); } ... rainio1.c

Example: IORainfall-1 using LOOP

#include <stdio.h>#define NMONTHS 12

/* Store and print rainfall */

int main(){ int data[NMONTHS]; int month; for ( month=0; month < NMONTHS; month++ ) { scanf("%d", &data[month] ); } ... rainio1.c

Example (cont): IORainfall-1Macro: Defined NMONTHS to be 12. Later in

program NMONTHS will be used

#include <stdio.h>#define NMONTHS 12

/* Store and print rainfall */

int main(){ int data[NMONTHS]; int month; for ( month=0; month < NMONTHS; month++ ) { scanf("%d", &data[month] ); } ... rainio1.c

Example (cont): IORainfall-1

Array

1 2 3 4 5 6 7 8 9 10 11 12

0 1 2 3 4 5 6 7 8 9 10 11

Array index

Values

data

Value at this position can

be accessed through

data [6]

#include <stdio.h>#define NMONTHS 12 ... /* Print from January to December */ for ( month=0; month < NMONTHS; month++ ) { printf( "%d ", data[month] ); } printf("\n");

/* Print from December to January */ for ( month = NMONTHS - 1; month >= 0; month-- ) { printf( "%d ", data[month] ); } printf("\n"); return 0;}

rainio1.c

Example…..: IORainfall-2 (v.1)This will print all contents of the array data

at location month

Print the array in reverse

order

#include <stdio.h>#define NMONTHS 12 ... /* Print from January to December */ for ( month=0; month < NMONTHS; month++ ) { printf( "%d ", data[month] ); } printf("\n");

/* Print from December to January */ for ( month = NMONTHS - 1; month >= 0; month-- ) { printf( "%d ", data[month] ); } printf("\n"); return 0;} rainio1.c

Example…..: IORainfall-2 (v.1)

“Copying” Arrays We cannot directly copy one array to another,

even if they have the same length and share the same data type.

Instead, we can use a for loop to copy values:

for (m = 0; m < 25; m++){

array2[m] = array1[m];}//end for

Swapping Array Elements To swap (or exchange) values, we must use a

temporary variable. A common novice’s mistake is to try to assign elements to one another:

/*The following is a logic error*/numbers[3] = numbers[1];numbers[1] = numbers[3];

/*A correct approach …*/temp = numbers[3];numbers[3] = numbers[1];numbers[1] = temp;

Printing Array Elements To print an array’s contents, we would use

a for loop:for(k = 0; k < 9; k++){

printf(“%d”, scores[k]);}//end for

Range Checking Unlike some other languages, C does not

provide built-in range checking. Thus, it is possible to write code that will produce “out-of-range” errors, with unpredictable results.

Common Error (array length is 9):for(j = 1; j <= 9; j++){

scanf(“%d”, &scores[j]);}//end for

Character Strings

Topics Representation Declaration Index of a char in a string String operations Common mistakes

Representation Recall: Main memory

contiguous array of cellseach cell has an

address

0x1FFF 0x2000 0x2001 0x20020x1FFEetc

ch

Representation (cont) Recall: Variable declaration

sets aside a “box” to contain a value

Example: char ch;

ch = ‘B’;

0x1FFF 0x2000 0x2001 0x20020x1FFEetc

‘B’

Representation (cont)

Example: char name[5];

Specifies numberof cells in the array

String declarationsets aside an array of cellseach cell contains a charaddress of first cell in the array

Representation (cont) String declaration

sets aside an array of cellseach cell contains a charaddress of first cell in the array

Example: char name[5];

0x2000 0x2004

name

is 0x2000

Character Arrays vs Character Strings

A character string is a char array A character string must have the

terminating character (’\0’) The terminating character allows scanf()

and printf() to handle character strings

Character StringsDeclaration 1:

char name[5];

Declaration 2:

#define MAXLENGTH 5

char name[MAXLENGTH];

0x2000 0x2004

name

is 0x2000

String Input/Output#include <stdio.h>

#define MAXLENGTH 15

int main(){ char string1[MAXLENGTH]; char string2[MAXLENGTH];

scanf("%s %s", string1, string2); printf("%s %s\n", string1, string2);

return 0;}

No ampersand (&)!

Character String Declaration

Declaration 1:

char name[5] = “Ann”;

A n n \0

Terminating Character:• Marks the end of string• Special char: ’\0’ • aka NUL (single L)

0x2000 0x2004

name

is 0x2000

Character String Declaration

Declaration 1:

char name[5] = “Ann”;

A n n \0

0x2000 0x2004

name

is 0x2000

Could have defined this as an array:

char name[5] = {’A’,’n’,’n’,’\0’};

Character String Declaration (cont)

Declaration 1:

char name[5] = “Ann”;

Can storeat most 4 letters,because of `\0’

A n n \0

0x2000 0x2004

name

is 0x2000

Character String Declaration (cont)

Declaration 2:

char name[] = “Ann”;

Takes up an extra cell for ‘\0’

A n n \0

0x2000 0x2003

name

is 0x2000

Character String Declaration (cont)

Declaration 3:

char *name = “Ann”;

Result is “undefined”if you try to modify

this string

A n n \0

0x3000 0x3003

0x3000

name

Character String Declaration (cont)

Declaration 4:

char name[];

String with arbitrary length?

No! Will cause an error“array size missing in

`name’”

A Char in a String The size of a character string is fixed Character at position index:

string[index]first character has index 0

char name[8] = “John”;int i = 2;

printf(“Char at index %d is %c.\n”, i, name[i]);

A Char in a String (cont)

output: Char at index 2 is h.

index 0 index 4

J o h n \0

0x3995 0x399C

name

is 0x3995

A Char in a String (cont)

index 2

J o h n \0

0x3995 0x399C

name

is 0x3995

char name[8] = “John”;

name[2] = ‘X’;printf(“Name: %s\n”, name);

X

J o X n \0

0x3995 0x399C

name

is 0x3995

output: Name: JoXn

index 2

char name[8] = “John”;

name[2] = ‘X’;printf(“Name: %s\n”, name);

A Char in a String (cont)

String Operations

#include <string.h> Operations:

Assignment: strcpy()Concatenation: strcat()Comparison: strcmp()Length: strlen()

All rely on and maintain the NUL termination of the strings.

#include <stdio.h>#include <string.h>

#define MAXLENGTH 100

int main(){ char string1[MAXLENGTH]; char string2[MAXLENGTH];

strcpy(string1, “Hello World!”); strcpy(string2, string1);

return 0;}

String Operation: Assignment

string1: <garbage>string2: <garbage>

We have previously discussed underlying array copying function

String Operation: Assignment (cont)

#include <stdio.h>#include <string.h>

#define MAXLENGTH 100

int main(){ char string1[MAXLENGTH]; char string2[MAXLENGTH];

strcpy(string1, “Hello World!”); strcpy(string2, string1);

return 0;}

string1: “Hello World!”string2: <garbage>

String Operation: Assignment#include <stdio.h>#include <string.h>

#define MAXLENGTH 100

int main(){ char string1[MAXLENGTH]; char string2[MAXLENGTH];

strcpy(string1, “Hello World!”); strcpy(string2, string1);

return 0;}

string1: “Hello World!”string2: “Hello World!”

char name1[5] = “Ann”;char name2[5] = “Dave”;

name2 = name1;

Common Mistake 1:

Incompatible types

Example:

Error: “LValue required ...”

Common Mistake 2:

Not enough space

A n n \0

0x2000 0x2003

char name[] = “Ann”;

strcpy(name, “David”);

name

is 0x2000

Common Mistake 2:

Not enough space

D a v i d \0

0x2003

char name[] = “Ann”;

strcpy(name, “David”);

0x2000

name

is 0x2000

char *name1 = “Ann”;char *name2 = “Dave”;

name2 = name1;

Caution 1:

Pointer Assignment

Example:

Caution 1:Pointer Assignment

D a v e \0

0x3990 0x3994

A n n \0

0x2000 0x2003

0x2000

name1

0x3990

name2

char *name1 = “Ann”;char *name2 = “Dave”;

Caution 1:Pointer Assignment

D a v e \0

0x3990 0x3994

A n n \0

0x2000 0x2003

0x2000

name1

0x2000

name2

name2 = name1;

String Operation: Concatenation

char string1[MAXLENGTH];char string2[MAXLENGTH];

strcpy(string1, “Goodbye”);strcpy(string2, “, Cruel ”);

strcat(string1, string2);strcat(string1, string2);strcat(string1, “World!”);

string1: “Goodbye”string2: “, Cruel “

char string1[MAXLENGTH];char string2[MAXLENGTH];

strcpy(string1, “Goodbye”);strcpy(string2, “, Cruel ”);

strcat(string1, string2);strcat(string1, string2);strcat(string1, “World!”);

string1: “Goodbye, Cruel ”string2: “, Cruel ”

String Operation: Concatenation (cont)

string1: “Goodbye, Cruel , Cruel ”string2: “, Cruel ”

String Operation: Concatenation (cont)

char string1[MAXLENGTH];char string2[MAXLENGTH];

strcpy(string1, “Goodbye”);strcpy(string2, “, Cruel ”);

strcat(string1, string2);strcat(string1, string2);strcat(string1, “World!”);

string1: “Goodbye, Cruel , Cruel World!”string2: “, Cruel ”

String Operation: Concatenation (cont)

char string1[MAXLENGTH];char string2[MAXLENGTH];

strcpy(string1, “Goodbye”);strcpy(string2, “, Cruel ”);

strcat(string1, string2);strcat(string1, string2);strcat(string1, “World!”);

Common Mistake:

char name[5];

strcpy(name, “Ann”);strcat(name, “ Smith”);

Not enough space

A n n \0

0x2000 0x2004

name

is 0x2000

Common Mistake:

char name[5];

strcpy(name, “Ann”);strcat(name, “ Smith”);

Not enough space

A n n S m i t

0x2000 0x2004

h \0name

is 0x2000

strcpy(string1, “Apple”);strcpy(string2, “Wax”);

if (strcmp(string1, string2) < 0){ printf(“%s %s\n”, string1, string2);}else{ printf(“%s %s\n”, string2, string1);}

String Operation: Comparison

Returns:

negative if string1 < string2

zero if string1 == string2

positive if string1 > string2

strcpy(string1, “Apple”);strcpy(string2, “Wax”);

if (strcmp(string1, string2) < 0){ printf(“%s %s\n”, string1, string2);}else{ printf(“%s %s\n”, string2, string1);}

String Operation: Comparison (cont)

output: Apple Wax

strcpy(string1, “Apple”);strcpy(string2, “Wax”);

if (string1 < string2){ printf(“%s %s\n”, string1, string2);}else{ printf(“%s %s\n”, string2, string1);}

Common Mistake:

Wrong Comparison

strcpy(string1, “Hi Mum”);strcpy(string2, “Hi Mum”);

if ( strcmp(string1, string2) ){ printf(“%s and %s are the same\n”,

string1, string2);}

Caution 1:

Not a Boolean

Returns zero if the strings are the same.

char string1[100];

strcpy(string1, “Apple”);

printf(“%d\n”, strlen(string1));

output: 5

Number of char-sbefore the `\0’

String Operation: Length

Common Mistake:

char name[5];

strcpy(name, “David”);

Not enough space

Don’t forget the ‘\0’

D a v i d \0

0x3990 0x3994

name

is 0x3990

Summary A string is a contiguous array of chars The string identifier is the address of the

first char in the string Individual chars are accessed using the str[index] notation

There are C library functions for copying, concatenating and comparing strings

top related