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

Arrays Information Slides

The document provides an overview of arrays and functions in C programming, detailing how to define, initialize, and manipulate arrays, including multidimensional and variable-length arrays. It also covers function definitions, local variables, and the return of function results. Key concepts include array bounds checking and the use of the 'const' qualifier for constants.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Arrays Information Slides

The document provides an overview of arrays and functions in C programming, detailing how to define, initialize, and manipulate arrays, including multidimensional and variable-length arrays. It also covers function definitions, local variables, and the return of function results. Key concepts include array bounds checking and the use of the 'const' qualifier for constants.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Programming in C

Arrays and Functions


Array
Defining an Array
General Form:

type id[length];

By defining an array we are


allocating enough memory to
hold an ordered set of length
length data items whose type is
type:

float averages[200];
int values[10];
3
Defining an Array
Referencing items in an array is
easy and similar to other
languages you may have
encountered previously:

4
What values do you think are in the “empty” slots?
Defining an Array
Referencing items in an array is 🤔
easy and similar to other
languages you may have
encountered previously: 🤔

🤔
🤔
🤔

5
Initializing Arrays
Just as you can assign initial int counters[5] = { 0, 0, 0, 0, 0 };

values to variables when they int integers[5] = { 0, 1, 2, 3, 4,


are declared, so can you assign 5 };
initial values to the elements of
char letters[5] = { ‘a’, ‘b’, ‘c’,
an array. ‘d’, ‘e’ };

This is done by simply listing the float data[500] = { 1.5, 2.3 };


initial values of the array,
int x = 123;
starting from the first element. int a[10] = { [9] = x+1, [2] = 3, [6]
= 2 };
Values in the list are separated
by commas and the entire list is char word[] = { ‘H’, ‘e’, ‘l’, ‘l’,
‘o’ }; 6
enclosed in a pair of braces.
Initializing Arrays
Just as you can assign initial int counters[5] = { 0, 0, 0, 0, 0 };

values to variables when they int integers[5] = { 0, 1, 2, 3, 4,


are declared, so can you assign 5 };
initial values to the elements of
char letters[5] = { ‘a’, ‘b’, ‘c’,
an array. ‘d’, ‘e’ };

This is done by simply listing the float data[500] = { 1.5, 2.3 };


initial values of the array,
int x = 123;
starting from the first element. int a[10] = { [9] = x+1, [2] = 3, [6]
= 2 };
Values in the list are separated
by commas and the entire list is char word[] = { ‘H’, ‘e’, ‘l’, ‘l’,
‘o’ }; 7
enclosed in a pair of braces.
Initializing Arrays
Just as you can assign initial int counters[5] = { 0, 0, 0, 0, 0 };

values to variables when they int integers[5] = { 0, 1, 2, 3, 4,


are declared, so can you assign 5 };
initial values to the elements of
char letters[5] = { ‘a’, ‘b’, ‘c’,
an array. ‘d’, ‘e’ };

This is done by simply listing the float data[500] = { 1.5, 2.3 };


initial values of the array,
int x = 123;
starting from the first element. int a[10] = { [9] = x+1, [2] = 3, [6]
= 2 };
Values in the list are separated
by commas and the entire list is char word[] = { ‘H’, ‘e’, ‘l’, ‘l’,
‘o’ }; 8
enclosed in a pair of braces.
Initializing Arrays
Just as you can assign initial int counters[5] = { 0, 0, 0, 0, 0 };

values to variables when they int integers[5] = { 0, 1, 2, 3, 4,


are declared, so can you assign 5 };
initial values to the elements of
char letters[5] = { ‘a’, ‘b’, ‘c’,
an array. ‘d’, ‘e’ };

This is done by simply listing the float data[500] = { 1.5, 2.3 };


initial values of the array,
int x = 123;
starting from the first element. int a[10] = { [9] = x+1, [2] = 3, [6]
= 2 };
Values in the list are separated
by commas and the entire list is char word[] = { ‘H’, ‘e’, ‘l’, ‘l’,
‘o’ }; 9
enclosed in a pair of braces.
Initializing Arrays
Just as you can assign initial int counters[5] = { 0, 0, 0, 0, 0 };

values to variables when they int integers[5] = { 0, 1, 2, 3, 4,


are declared, so can you assign 5 };
initial values to the elements of
char letters[5] = { ‘a’, ‘b’, ‘c’,
an array. ‘d’, ‘e’ };

This is done by simply listing the float data[500] = { 1.5, 2.3 };


initial values of the array,
int x = 123;
starting from the first element. int a[10] = { [9] = x+1, [2] = 3, [6]
= 2 };
Values in the list are separated
by commas and the entire list is char word[] = { ‘H’, ‘e’, ‘l’, ‘l’,
‘o’ }; 10
enclosed in a pair of braces.
Initializing Arrays
Just as you can assign initial int counters[5] = { 0, 0, 0, 0, 0 };

values to variables when they int integers[5] = { 0, 1, 2, 3, 4,


are declared, so can you assign 5 };
initial values to the elements of
char letters[5] = { ‘a’, ‘b’, ‘c’,
an array. ‘d’, ‘e’ };

This is done by simply listing the float data[500] = { 1.5, 2.3 };


initial values of the array,
int x = 123;
starting from the first element. int a[10] = { [9] = x+1, [2] = 3, [6]
= 2 };
Values in the list are separated
by commas and the entire list is char word[] = { ‘H’, ‘e’, ‘l’, ‘l’,
‘o’ }; 11
enclosed in a pair of braces.
Initializing Arrays
Just as you can assign initial int counters[5] = { 0, 0, 0, 0, 0 };

values to variables when they int integers[5] = { 0, 1, 2, 3, 4,


are declared, so can you assign 5 };
initial values to the elements of
char letters[5] = { ‘a’, ‘b’, ‘c’,
an array. ‘d’, ‘e’ };

This is done by simply listing the float data[500] = { 1.5, 2.3 };


initial values of the array,
int x = 123;
starting from the first element. int a[10] = { [9] = x+1, [2] = 3, [6]
= 2 };
Values in the list are separated
by commas and the entire list is char word[] = { ‘H’, ‘e’, ‘l’, ‘l’,
‘o’ }; 12
enclosed in a pair of braces.
The const Qualifier
● Variables can be declared as const double pi = 3.141592654;

const (constant). pi = pi / 2;
● Changing the value of a
const results in a compiler
error.
● In addition to the software
engineering benefit, it also
allows the compiler to place
the value of a constant in
read-only memory,
optimize based on its value,
etc., making your code 13
Multidimensional Arrays
int M[4][5]; // M[i][j]

int sum = M[0][2] + M[2]


[4];

M[2][1] = M[0][0] * 2;

14
Multidimensional Arrays
int M[4][5]; // M[i][j]

int sum = M[0][2] + M[2]


[4];

M[2][1] = M[0][0] * 2;

int M[4][5] = {
{ 10, 5, -3, 17, 82 },
{ 9, 0, 0, 8, -7 },
{ 32, 20, 1, 0, 14 },
{ 0, 0, 8, 7, 6 }
}; 15
Multidimensional Arrays
int M[4][5]; // M[i][j]

int sum = M[0][2] + M[2]


[4];

M[2][1] = M[0][0] * 2;

int M[4][5] = {
10, 5, -3, 17, 82,
9, 0, 0, 8, -7,
32, 20, 1, 0, 14,
0, 0, 8, 7, 6
}; 16
Multidimensional Arrays
int M[4][5]; // M[i][j]

int sum = M[0][2] + M[2]


[4];

M[2][1] = M[0][0] * 2;

int M[4][5] = {
{ 10, 5, -3 },
{ 9, 0, 0 },
{ 32, 20, 1 },
{ 0, 0, 8 }
}; 17
Multidimensional Arrays
int M[4][5]; // M[i][j]

int sum = M[0][2] + M[2]


[4];

M[2][1] = M[0][0] * 2;

int M[4][5] = {
[0][0] = 10,
[0][1] = 5,
[0][2] = -3
};
18
Multidimensional Arrays
int M[4][5]; // M[i][j]

int sum = M[0][2] + M[2]


🤔 🤔 [4];
🤔 🤔 🤔 🤔 🤔
M[2][1] = M[0][0] * 2;
🤔 🤔 🤔 🤔 🤔
🤔 🤔 🤔 🤔 🤔 int M[4][5] = {
[0][0] = 10,
[0][1] = 5,
[0][2] = -3
};
19
Variable Length Arrays
What happens if you do not
know the size of your array at
compilation time?

C allows arrays to be declared


as variable length using an
integer.

However, the length is fixed


after its declaration and may
not be changed while that
array is still declared.
20
Array Length, Iteration, Bounds Checking
In a language such as Java we
have the luxury that the
compiler and Java virtual
machine (JVM) will perform
array bounds checking.

If the length of an array is


exceeded, the JVM will throw
an
ArrayOutOfBoundsException.
In C, we need to indicate the length of the array explicitly.
Java also attaches to each
21
array the length - pretty
Array Length, Iteration, Bounds Checking
Thus, if we define a function
that must iterate over an
array, we must tell it the
length of the given array.

22
Array Length, Iteration, Bounds Checking
Thus, if we define a function
that must iterate over an
array, we must tell it the
length of the given array.

So, what happens if we


accidentally exceed the
bounds of an array?

Let us run the program to see


what happens!

23
Function
Defining a Function
Defining functions in C is
easy.

25
Arguments and Local Variables

Functions can have


arguments defined in
the usual way.

It is also easy to
declare local
variables.

26
Function Prototype Declaration

This is referred to as
the function
prototype
declaration.

The body of the


function follows the
declaration.

Notice that this


function must be
declared before its
27
use in main.
Automatic Local Variables
Variables defined inside a function are known as automatic local
variables because they are automatically “created” each time the
function is called, and because their values are local to the function.
The value of a local variable can only be accessed by the function in
which the variable is defined. Its value cannot be accessed by any other
function.

When defining a local variable inside a function, it is more precise in C


to use the keyword auto before the definition of the variable:

Because the C compiler assumes that any variable declared in a 28


function is automatic, the keyword auto is rarely used!
Returning Function Results
Returning function results is
also similar to other
languages (e.g., Java)

29
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo %ebp
{{ yoo
who yoo
•• %esp
••
amI amI
who();
who();
•• amI
••
}}
amI

Course feedback:
https://bit.ly/
2klMxqH
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo
{{ who(…)
who(…) yoo
yoo
•{
•{ who
%ebp
•• •• •• •• who
amI();
amI();
who(); amI amI
who(); %esp
•• •• •• ••
•• amI();
amI(); amI
}} •• •• ••
}} amI

Course feedback:
https://bit.ly/
2klMxqH
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo
{{ who(…)
who(…) yoo
yoo
•{
•{ amI(…)
amI(…) who
•• {•{ •• ••

who
amI();
amI();
who(); •• amI amI
who();
•• •• •••• •• %ebp
amI amI
•• amI();
amI();
amI();
amI();

• ••• ••
• %esp
}}
}} •• amI
}}

Course feedback:
https://bit.ly/
2klMxqH
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo
{{ who(…)
who(…) yoo
yoo
•{
•{ amI(…)
amI(…) who
•• {•{ •• amI(…)
• ••
amI(…) who
amI();
amI();
who(); • amI amI
who(); •{{
•• • ••• •• ••
• •
amI amI
•• amI();
amI();
amI();
amI();
••
}} • • •
• ••• • amI();
amI(); %ebp
}} •• • amI amI

}} •• %esp
}}
Course feedback:
https://bit.ly/
2klMxqH
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo
{{ who(…)
who(…) yoo
yoo
•{
•{ amI(…)
amI(…) who
•• {•{ •• amI(…)
• ••
amI(…) who
amI();
amI();
who(); • amI amI
who(); •{{ amI(…)
amI(…)
•• • ••• •• ••{
• •
{ amI amI
•• amI();
amI();
amI();
amI();
•• •
•• ••• •• •
}} • amI();
amI();
••
}} •• • amI amI
• amI();
amI();
}} •• •
• %ebp
}} amI
••
}} %esp
Course feedback:
https://bit.ly/
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo
{{ who(…)
who(…) yoo
yoo
•{
•{ amI(…)
amI(…) who
•• {•{ •• amI(…)
• ••
amI(…) who
amI();
amI();
who(); • amI amI
who(); •{{
•• • ••• •• ••
• •
amI amI
•• amI();
amI();
amI();
amI();
••
}} • • •
• ••• • amI();
amI(); %ebp
}} •• • amI amI

}} •• %esp
}}
Course feedback:
https://bit.ly/
2klMxqH
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo
{{ who(…)
who(…) yoo
yoo
•{
•{ amI(…)
amI(…) who
•• {•{ •• ••

who
amI();
amI();
who(); •• amI amI
who();
•• •• •••• •• %ebp
amI amI
•• amI();
amI();
amI();
amI();

• ••• ••
• %esp
}}
}} •• amI
}}

Course feedback:
https://bit.ly/
2klMxqH
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo
{{ who(…)
who(…) yoo
yoo
•{
•{ who
%ebp
•• •• •• •• who
amI();
amI();
who(); amI amI
who(); %esp
•• •• •• ••
•• amI();
amI(); amI
}} •• •• ••
}} amI

Course feedback:
https://bit.ly/
2klMxqH
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo
{{ who(…)
who(…) yoo
yoo
•{
•{ amI(…)
amI(…) who
•• {•{ •• ••

who
amI();
amI();
who(); •• amI amI
who();
•• •• •••• •• %ebp
amI amI
•• amI();
amI();
amI();
amI();

• ••• ••
• %esp
}}
}} •• amI
}}

Course feedback:
https://bit.ly/
2klMxqH
Carnegie Mellon

Example Stack

yoo(…)
yoo(…) yoo
{{ who(…)
who(…) yoo
yoo
•{
•{ who
%ebp
•• •• •• •• who
amI();
amI();
who(); amI amI
who(); %esp
•• •• •• ••
•• amI();
amI(); amI
}} •• •• ••
}} amI

Course feedback:
https://bit.ly/
2klMxqH
Carnegie Mellon

Example Stack

yoo %ebp
yoo(…)
yoo(…) yoo
{{ who yoo
%esp
••
•• amI amI
who();
who();
•• amI
••
}} amI

Course feedback:
https://bit.ly/
2klMxqH
Application
Functions and Arrays
● Passing an array to a int minimum(int v[100]) {
function: you only ...
need to provide the return min_value;
array name. }

● To declare a function int main() {


that receives an array int grades[100] = { ... };
you need to provide the minimum(grades);
array declaration. return 0;
}

42
Functions and Arrays
● Passing an array to a int minimum(int v[100]) {
function: you only need ...
to provide the array return min_value;
name. }

● To declare a function int main() {


that receives an array int grades[100] = { ... };
you need to provide minimum(grades);
the array declaration. return 0;
}

43
Functions and Arrays
● Passing an array to a int minimum(int v[]) {
function you only need ...
to provide the array return min_value;
name. }

● To declare a function int main() {


that receives an array int grades[] = { ... };
you need to provide the minimum(grades);
array declaration. return 0;
}
● Lastly, the length is
optional in the 44
Functions and Arrays
● Another interesting
property of passing an
array to a function is
that an array can be
modified inside a
function.

● An array is mutable
(can be affected by a
callee).

● What does main print 45


Functions and Prototypes
● Remember how we said int minimum(int v[]) {
that we had to declare a ...
function before its use? return min_value;
}
● In this example, we do
exactly that, we declare int main() {
minimum before it is int grades[] = { ... };
used in main. minimum(grades);
return 0;
● What if we wanted to }
declare it after main?
46
Functions and Prototypes
● Then we declare the int main() {
prototype for the function int minimum(int v[]);
without the function body int grades[] = { ... };
before we use it in main!
minimum(grades);
● The prototype could also be return 0;
declared globally - i.e., }
outside of any function.
int minimum(int v[]) {
● The purpose of this will ...
become apparent later return min_value;
when we discuss larger }
programs.
47
Global Variables #include <stdio.h>

int counter = 0;
A variable that is not declared
locally to a function is global void tally() { counter++; }
to the file it is declared in.
int main() {
In other words, all functions
tally(); tally(); tally();
declared later in the same file
printf(“%i\n”, counter);
have access to that function.
return 0;
}

The output of this program is 3.


48
int tally() {
Automatic and static int counter = 0;
counter++;
Static Variables return counter;
}
We already talked about
automatic variables in C. int main() {
int r = 0;
C also allows you to define r=tally(); r=tally();
variables as static. r=tally();
printf(“%i\n”, r);
A variable with a static
return 0;
annotation will retain its value
}
across function calls.
The output of this program is 3.
49
C Strings
Arrays of Characters

51
Variable Length Character Strings

Although this works well enough, there is a problem. How might we


write a function to determine the length of this array of characters?

52
Variable Length Character Strings

Although this works well enough, there is a problem. How might we


right a function to determine the length of this array of characters?

The C language has a convention where a special character called the


null character is placed in the last entry in the character array to
indicate the end:

Now, you could easily imagine writing a function to determine the


length! 53
Variable Length Character Strings

It turns out that C also has a shortcut for defining an array of


characters:

char word[] = { “Hello!” };

The C compiler will automatically insert the null character at the end.
(Note: these are double quotes, not the single quotes that go around
individual characters.)

54
Variable Length Character Strings

It turns out that C also has a shortcut for defining an array of


characters:

char word[] = { “Hello!” };

The C compiler will automatically insert the null character at the end.
Furthermore, you can omit the braces:

char word[] = “Hello!”;

And there you have it, the C string is born!


55
Variable Length Character Strings

It turns out that C also has a shortcut for defining an array of


characters:

char word[] = { “Hello!” };

The C compiler will automatically insert the null character at the end.
Furthermore, you can omit the braces: You can also print strings
out:
char word[] = “Hello!”;
printf(“%s\n”, word);
And there you have it, the C string is born!
56
String Equality
Unfortunately, this does not work:

if (string1 == string2) { … }

This, in effect, is trying to compare two arrays, and arrays can’t be


compared like that either.

Rather, we need to compare strings character by character:

string1[0] == string2[0] && string1[1] && string2[1] && …

You should probably do that in a loop. Fortunately, there are library


functions for doing exactly this (strncmp) in the string.h library. But, we
57
need more first...
Inputting Character Strings
It couldn’t be easier...

58
The Null String
A character string that contains no characters other than the null
character has a special name in the C language; it is called the null
string.

Always remember that the null string does, in fact, have a character in
it, albeit a null one.

char buffer[5] = ””;

The above defines a character array of 5 items with the first set to null.

[’\0’, ?, ?, ?, ?]
59
Escape Characters
There are all
sorts of escape
characters that
can be used in
strings:

60
Constant Strings
You can have multi-line strings:

61
Constant Strings
You can have multi-line strings:

But, the backslash is kinda clunky. Do this instead:

The compiler will automatically concatenate adjacent strings. 62


Constant Strings
Or this form is more common:

char letter[] = “abcdefghijklmnopqrstuvwxyz”


“ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

63
10-sec Q &A
Raise your hand if it is a string
char letter[] = “abcdefghijklmnopqrstuvwxyz”
“ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

65
Raise your hand if it is a string
char letter[] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’};

66
Raise your hand if it is a string
char letter[] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\n’};

67
Raise your hand if it is a string
char letter[] = {‘\0’};

68
Raise your hand if the size of array is equal to
5 chars
char buffer[5] = ””;

69
Raise your hand if the size of array is equal to
5 chars
char buffer[5] = ”hello”;

70

You might also like