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

lecture10

The document provides an introduction to arrays as data structures in C programming, explaining their definition, initialization, and usage. It covers various examples, including defining arrays, initializing them with values, and using loops to manipulate array elements. Additionally, it discusses the importance of bounds checking and provides practical applications such as summarizing survey results and graphing data with histograms.

Uploaded by

tunayazici0608
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

lecture10

The document provides an introduction to arrays as data structures in C programming, explaining their definition, initialization, and usage. It covers various examples, including defining arrays, initializing them with values, and using loops to manipulate array elements. Additionally, it discusses the importance of bounds checking and provides practical applications such as summarizing survey results and graphing data with histograms.

Uploaded by

tunayazici0608
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Arrays Introduction

Array Examples
Character Arrays

CENG 101- Algorithms and Programming I, 2023-2024, Fall


Assist. Prof. Dr. Osman GÖKALP

Contains materials from:


P. Deitel, H. Deitel, ‘’C How to Program with an Introduction to C++’’, 8th edition, Pearson
1
Lecture 10.0

Quick Review

2
Fill in the blanks with appropriate words
➢ When arguments are passed by ______, a copy of the argument’s value is made and passed to the called
function. Changes to the copy do not affect an original variable’s value in the caller.
value
➢ To use rand() function, we should import <_____.h> header.
stdlib
➢ We use ______ function to set a seed for the random number generation.
srand
➢ To randomize without entering a seed each time, use a statement like _______.
srand(time(NULL))
➢ A ________ function is a function that calls itself either directly or indirectly through another function.
recursive
➢ A ________ is the condition to stop the recursion.
base case

3
What is the
output?

4
Lecture 10.1

Arrays Introduction

5
6.1 Introduction

• This chapter serves as an introduction to data structures.


• Arrays are data structures consisting of related data items of the same type.
• Arrays and structures are “static” entities in that they remain the same size
throughout program execution.

© 2016 Pearson Education, Ltd. All rights reserved. 6


6.2 Arrays

• An array is a group of contiguous memory locations that all have the


same type.
• To refer to a particular location or element in the array, we specify the
array’s name and the position number of the particular element in
the array.
• Figure 6.1 shows an integer array called c, containing 12 elements.
• Any one of these elements may be referred to by giving the array’s
name followed by the position number of the particular element in
square brackets ([]).

© 2016 Pearson Education, Ltd. All rights reserved. 7


© 2016 Pearson Education, Ltd. All rights reserved. 8
6.2 Arrays (Cont.)

• 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.

© 2016 Pearson Education, Ltd. All rights reserved. 9


6.2 Arrays (Cont.)

• An index must be an integer or an integer expression.


• For example, if a = 5 and b = 6, then the statement
• c[a + b] += 2;
• adds 2 to array element c[11].
• An indexed array name is an lvalue—it can be used on the left side of
an assignment.

© 2016 Pearson Education, Ltd. All rights reserved. 10


6.2 Arrays (Cont.)

• Let’s examine array c (Fig. 6.1) more closely.


• The array’s name is c.
• Its 12 elements are referred to as c[0], c[1], c[2], …, c[10] and c[11].
• The value stored in c[0] is –45, the value of c[1] is 6, c[2] is 0, c[7] is 62
and c[11] is 78.
• To print the sum of the values contained in the first three elements of array c,
we’d write
• printf("%d", c[0] + c[1] + c[2]);
• To divide the value of element 7 of array c by 2 and assign the result to the
variable x, write
• x = c[7] / 2;

© 2016 Pearson Education, Ltd. All rights reserved. 11


6.2 Arrays (Cont.)

• The brackets used to enclose the index of an array are actually


considered to be an operator in C.
• They have the same level of precedence as the function call operator
(i.e., the parentheses that are placed after a function name to call
that function).
• Figure 6.2 shows the precedence and associativity of the operators
introduced to this point in the text.

© 2016 Pearson Education, Ltd. All rights reserved. 12


© 2016 Pearson Education, Ltd. All rights reserved. 13
6.3 Defining Arrays

• Arrays occupy space in memory.


• You specify the type of each element and the number of elements
each array requires so that the computer may reserve the appropriate
amount of memory.
• The following definition reserves 12 elements for integer array c,
which has indices in the range 0-11.
• int c[12];

© 2016 Pearson Education, Ltd. All rights reserved. 14


6.3 Defining Arrays (Cont.)

• The definition
• int b[100], x[27];
reserves 100 elements for integer array b and 27 elements for integer
array x.
• These arrays have indices in the ranges 0–99 and 0–26, respectively.
• Arrays may contain other data types.
• Character strings and their similarity to arrays are discussed in
Chapter 8. The relationship between pointers and arrays is discussed
in Chapter 7.

© 2016 Pearson Education, Ltd. All rights reserved. 15


Lecture 10.2

Array Examples

16
6.4 Array Examples

6.4.1 Defining an Array and Using a Loop to Set the Array’s Element
Values
• Like any other variables, uninitialized array elements contain garbage
values.
• Figure 6.3 uses for statements to initialize the elements of a five
integer array n to zeros and print the array in tabular format.
• The first printf statement displays the column heads for the two
columns printed in the subsequent for statement.

© 2016 Pearson Education, Ltd. All rights reserved. 17


© 2016 Pearson Education, Ltd. All rights reserved. 18
© 2016 Pearson Education, Ltd. All rights reserved. 19
6.4 Array Examples (Cont.)

• 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.]

© 2016 Pearson Education, Ltd. All rights reserved. 20


6.4 Array Examples (Cont.)

Initializing an Array in a Definition with an Initializer List


• The elements of an array can also be initialized when the array is
defined by following the definition with an equal sign and braces, {},
containing a comma-separated list of array initializers.
• Figure 6.4 initializes an integer array with five values and prints the
array in tabular format.

© 2016 Pearson Education, Ltd. All rights reserved. 21


© 2016 Pearson Education, Ltd. All rights reserved. 22
© 2016 Pearson Education, Ltd. All rights reserved. 23
6.4 Array Examples (Cont.)

• If there are fewer initializers than elements in the array, the remaining
elements are initialized to zero.
• For example, the elements of the array n in Fig. 6.3 could have been
initialized to zero as follows:
// initializes entire array to zeros
int n[10] = {0};
• This explicitly initializes the first element to zero and initializes the
remaining nine elements to zero because there are fewer initializers
than there are elements in the array.

© 2016 Pearson Education, Ltd. All rights reserved. 24


6.4 Array Examples (Cont.)

• It’s important to remember that arrays are not automatically


initialized to zero.
• You must at least initialize the first element to zero for the remaining
elements to be automatically zeroed.

© 2016 Pearson Education, Ltd. All rights reserved. 25


© 2016 Pearson Education, Ltd. All rights reserved. 26
6.4 Array Examples (Cont.)

• The array definition


• int n[5] = {32, 27, 64, 18, 95, 14};
causes a syntax error because there are six initializers and only five
array elements.

© 2016 Pearson Education, Ltd. All rights reserved. 27


© 2016 Pearson Education, Ltd. All rights reserved. 28
6.4 Array Examples (Cont.)

• 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,
• int n[] = {1, 2, 3, 4, 5};
would create a five-element array initialized with the indicated values.

© 2016 Pearson Education, Ltd. All rights reserved. 29


6.4 Array Examples (Cont.)

Specifying an Array’s Size with a Symbolic Constant and Initializing


Array Elements with Calculations
• Figure 6.5 initializes the elements of a 10-element array s to the
values 2, 4, 6, …, 20 and prints the array in tabular format.
• The values are generated by multiplying the loop counter by 2 and
adding 2.

© 2016 Pearson Education, Ltd. All rights reserved. 30


© 2016 Pearson Education, Ltd. All rights reserved. 31
© 2016 Pearson Education, Ltd. All rights reserved. 32
6.4 Array Examples (Cont.)

• The #define preprocessor directive is introduced in this program.


• #define SIZE 5
• defines a symbolic constant SIZE whose value is 5.
• A symbolic constant is an identifier that’s replaced with replacement
text by the C preprocessor before the program is compiled.

© 2016 Pearson Education, Ltd. All rights reserved. 33


6.4 Array Examples (Cont.)

• When the program is preprocessed, all occurrences of the symbolic


constant SIZE are replaced with the replacement text 5.
• Using symbolic constants to specify array sizes makes programs more
modifiable.
• In Fig. 6.5, we could have the first for loop fill a 1000-element array
by simply changing the value of SIZE in the #define directive from
5 to 1000.
• If the symbolic constant SIZE had not been used, we’d have to
change the program in three separate places.

© 2016 Pearson Education, Ltd. All rights reserved. 34


© 2016 Pearson Education, Ltd. All rights reserved. 35
6.4 Array Examples (Cont.)

• If the #define preprocessor directive is terminated with a


semicolon, the preprocessor replaces all occurrences of the symbolic
constant SIZE in the program with the text 5;.
• 5; instead of 5

© 2016 Pearson Education, Ltd. All rights reserved. 36


© 2016 Pearson Education, Ltd. All rights reserved. 37
© 2016 Pearson Education, Ltd. All rights reserved. 38
© 2016 Pearson Education, Ltd. All rights reserved. 39
6.4 Array Examples (Cont.)

Summing the Elements of an Array


• Figure 6.6 sums the values contained in the 12-element integer array
a.
• The for statement’s body does the totaling.

© 2016 Pearson Education, Ltd. All rights reserved. 40


© 2016 Pearson Education, Ltd. All rights reserved. 41
6.4 Array Examples (Cont.)

Using Arrays to Summarize Survey Results


• Our next example uses arrays to summarize the results of data
collected in a survey.
• Consider the problem statement.
• Forty students were asked to rate the quality of the food in the student
cafeteria on a scale of 1 to 10 (1 means awful and 10 means excellent). Place
the 40 responses in an integer array and summarize the results of the poll.
• This is a typical array application (see Fig. 6.7).
• We wish to summarize the number of responses of each type (i.e., 1
through 10).
© 2016 Pearson Education, Ltd. All rights reserved. 42
© 2016 Pearson Education, Ltd. All rights reserved. 43
© 2016 Pearson Education, Ltd. All rights reserved. 44
6.4 Array Examples (Cont.)

• The array responses is a 40-element array of the students’


responses.
• We use an 11-element array frequency to count the number of
occurrences of each response.
• We ignore frequency[0] because it’s logical to have response 1
increment frequency[1] rather than frequency[0].
• This allows us to use each response directly as the index in the
frequency array.

© 2016 Pearson Education, Ltd. All rights reserved. 45


6.4 Array Examples (Cont.)

• The for loop takes the responses one at a time from the array
responses and increments one of the 10 counters (frequency[1]
to frequency[10]) in the frequency array.
• The key statement in the loop is
• ++frequency[responses[answer]];
which increments the appropriate frequency counter depending on
the value of responses[answer].

© 2016 Pearson Education, Ltd. All rights reserved. 46


6.4 Array Examples (Cont.)

• When the counter variable answer is 0, responses[answer] is 1,


so ++frequency[responses[answer]]; is interpreted as
• ++frequency[1];
which increments array element one.
• When answer is 1, responses[answer] is 2, so
++frequency[responses[answer]]; is interpreted as
• ++frequency[2];
which increments array element two.

© 2016 Pearson Education, Ltd. All rights reserved. 47


6.4 Array Examples (Cont.)

• When answer is 2, responses[answer] is 6, so


++frequency[responses[answer]]; is interpreted as
• ++frequency[6];
which increments array element six, and so on.
• Regardless of the number of responses processed in the survey, only
an 11-element array is required (ignoring element zero) to summarize
the results.
• If the data contained invalid values such as 13, the program would
attempt to add 1 to frequency[13].
• This would be outside the bounds of the array.

© 2016 Pearson Education, Ltd. All rights reserved. 48


6.4 Array Examples (Cont.)

• C has no array bounds checking to prevent the program from referring


to an element that does not exist.
• Thus, an executing program can “walk off” either end of an array
without warning—a security problem that we discuss in Section 6.11.
• You should ensure that all array references remain within the bounds
of the array.

© 2016 Pearson Education, Ltd. All rights reserved. 49


© 2016 Pearson Education, Ltd. All rights reserved. 50
© 2016 Pearson Education, Ltd. All rights reserved. 51
6.4 Array Examples (Cont.)

Graphing Array Element Values with Histograms


• Our next example (Fig. 6.8) reads numbers from an array and graphs
the information in the form of a bar chart or histogram—each
number is printed, then a bar consisting of that many asterisks is
printed beside the number.
• The nested for statement draws the bars.
• Note the use of puts("") to end each histogram bar.

© 2016 Pearson Education, Ltd. All rights reserved. 52


© 2016 Pearson Education, Ltd. All rights reserved. 53
© 2016 Pearson Education, Ltd. All rights reserved. 54
6.4 Array Examples (Cont.)

Rolling a Die 60,000,000 Times and Summarizing the Results in an


Array
• Roll a single six-sided die 60,000,000 times to test whether the
random number generator actually produces random numbers.
• An array version of this program is shown in Fig. 6.9.

© 2016 Pearson Education, Ltd. All rights reserved. 55


© 2016 Pearson Education, Ltd. All rights reserved. 56
© 2016 Pearson Education, Ltd. All rights reserved. 57
Lecture 10.3

Character Arrays

58
6.5 Using Character Arrays to Store and Manipulate
Strings
• We now discuss storing strings in character arrays.
• So far, the only string-processing capability we have is outputting a
string with printf.
• A string such as "hello" is really an array of individual characters in C.
• A character array can be initialized using a string literal.
• For example,
• char string1[] = "first";
initializes the elements of array string1 to the individual characters in
the string literal "first".

© 2016 Pearson Education, Ltd. All rights reserved. 59


6.5 Using Character Arrays to Store and Manipulate
Strings
• In this case, the size of array string1 is determined by the compiler based
on the length of the string.
• The string "first" contains five characters plus a special string-termination
character called the null character.
• Thus, array string1 actually contains six elements.
• The character constant representing the null character is '\0'.
• All strings in C end with this character.
• A character array representing a string should always be defined large enough
to hold the number of characters in the string and the terminating null
character.

© 2016 Pearson Education, Ltd. All rights reserved. 60


6.5 Using Character Arrays to Store and Manipulate
Strings
• Character arrays also can be initialized with individual character
constants in an initializer list, but this can be tedious.
• The preceding definition is equivalent to
• char string1[] =
{'f', 'i', 'r', 's', 't', '\0'};
• Because a string is really an array of characters, we can access
individual characters in a string directly using array index notation.
• For example, string1[0] is the character 'f' and string1[3] is
the character 's'.

© 2016 Pearson Education, Ltd. All rights reserved. 61


6.5 Using Character Arrays to Store and Manipulate
Strings
• We also can input a string directly into a character array from the keyboard using
scanf and the conversion specifier %s.
• For example,
• char string2[20];
creates a character array capable of storing a string of at most 19 characters
and a terminating null character.
• The statement
• scanf("%19s", string2);
reads a string from the keyboard into string2.
• The name of the array is passed to scanf without the & used with nonstring
variables.

© 2016 Pearson Education, Ltd. All rights reserved. 62


6.5 Using Character Arrays to Store and Manipulate
Strings
• Function scanf will read characters until a space, tab, newline or end-of-file
indicator is encountered.
• The string2 should be no longer than 19 characters to leave room for the
terminating null character.
• If the user types 20 or more characters, your program may crash or create a
security vulnerability.
• For this reason, we used the conversion specifier %19s so that scanf reads a
maximum of 19 characters and does not write characters into memory
beyond the end of the array string2.

© 2016 Pearson Education, Ltd. All rights reserved. 63


6.5 Using Character Arrays to Store and Manipulate
Strings
• It’s your responsibility to ensure that the array which the string is
read into is capable of holding any string that the user types at the
keyboard.
• Function scanf does not check how large the array is.
• Thus, scanf can write beyond the end of the array.

© 2016 Pearson Education, Ltd. All rights reserved. 64


6.5 Using Character Arrays to Store and Manipulate
Strings
• A character array representing a string can be output with printf
and the %s conversion specifier.
• The array string2 is printed with the statement
• printf("%s\n", string2);
• Function printf, like scanf, does not check how large the character
array is.
• The characters of the string are printed until a terminating null
character is encountered.

© 2016 Pearson Education, Ltd. All rights reserved. 65


6.5 Using Character Arrays to Store and Manipulate
Strings
• Figure 6.10 demonstrates initializing a character array with a string
literal, reading a string into a character array, printing a character
array as a string and accessing individual characters of a string.

© 2016 Pearson Education, Ltd. All rights reserved. 66


© 2016 Pearson Education, Ltd. All rights reserved. 67
© 2016 Pearson Education, Ltd. All rights reserved. 68

You might also like