Transcript Arrays / C
CGS 3460
Array
What is an array
Data structure that holds a group (list) of homogenous elements of a
specific type
• Associate a set of values with a single variable name
• All of these values must be of the same data type
• Think grades for example
Why?
Process a group of values using a loop
Consider dealing with grades of 50 students
• Without arrays you would declare 50 variables for each student
CGS 3460
How to Define
Declaration
type <var_name>[size];
Example
To define an integer array called numbers
of size 5
• int numbers[5];
• Compare to normal integer declaration
• Each number is called an element
• Indexed from 0 to N-1 (4)
numbers
0
1
2
3
4
CGS 3460
How to Use
How to refer to an individual
element of an array
Accessed by their position in the array,
e.g.
• numbers[1] = 2;
• Set the element at index 1 of
numbers to 2
Do this for any element (0 – 4)
Operation on element in an array
Same as normal variable
numbers[0]
numbers[1]
numbers[2]
numbers[3]
numbers[4]
2
CGS 3460
Array Manipulation
int first, i;
int numbers[5];
numbers[0] = 12;
numbers[1] = 14;
numbers[2] = 6;
numbers[3] = 8;
numbers[4] = 7;
first = numbers[0]; //first becomes 12
numbers[1] = numbers[0] + 10;
numbers[3] = numbers[0] + numbers[1] + numbers[2];
i = 2;
numbers[i] = 50;
numbers[i-1] = numbers[i];
numbers[i] = numbers[i] + numbers[i+1];
numbers[0]
numbers[1]
numbers[2]
numbers[3]
numbers[4]
12
22
14
50
50
90
6
40
8
7
CGS 3460
Example – 0
Get a set of numbers from user
int numbers[5], i;
for( i = 0; i <5; i++ )
scanf("%i", &numbers[i]);
CGS 3460
Example – I
Calculate statistics of a set of numbers
Average
int sum = 0;
double avg;
for( i = 0; i <5; i++ )
sum = sum + numbers[i];
avg = sum / 5; -999999;
numbers[0];
Max value
1;
int maxValue = 0;
for( i = 0; i <5; i++ ) {
if (maxValue < numbers[i])
maxValue = numbers[i];
}
Instead of setting an
arbitrary number, use the
first element in the array to
make sure the maximum
number in this array would
be found
CGS 3460
Fibonacci Numbers in an Array
n
0
1
2
3
4
5
6
F(n)
0
1
1
2
3
5
8
CGS 3460
Code
#include <stdio.h>
int main()
{
int F[15], i;
F[0] = 0; //set initial values
F[1] = 1; //set initial values
for ( i = 2; i< 15; i++ )
f[i] = f[i - 2] + f[i - 1];
for ( i = 0; i< 15; i++ )
printf("%i\n", f[i]);
return 0;
}
CGS 3460
Initializing Arrays
Initializing an array using a
comma-separated list of values
in { }
int number[ ] = { 5, 7, 2 };
• Size of an array is automatically
set as the number of elements
within { }
numbers[0]
numbers[1]
numbers[2]
5
7
2
CGS 3460
Initializing Arrays
Initializing part of an array, and
other numbers will set to 0
int numbers[5] = { 3, 1};
numbers[0]
numbers[1]
numbers[2]
numbers[3]
numbers[4]
3
1
0
0
0
CGS 3460
Initializing Arrays
Initializing part of an array, and
other numbers will set to 0
int numbers[5] = { [0] = 3, [2] = 1};
numbers[0]
numbers[1]
numbers[2]
numbers[3]
numbers[4]
3
0
1
0
0
CGS 3460
Character Arrays
You can have an array of characters
char word[ ] = {‘H’,’e’,’l’,’l’,’o’,’!’}
word[0]
H
e
l
l
o
!
CGS 3460
Strings
A sequence of characters delimited by “ “ (not part of the
string)
“hello”
“Neko”
“This is some random sentence that I typed!”
C does not have a string type
It uses an array of characters
Array contains a null character (‘\0’) to denote the end of the string
Uses %s to print
CGS 3460
Example
Stores “hello” in character array of size 10
Only represent strings of length 9
Unless we increase the size of str
%s specifes string format specifier
causes the printf function to step through the character
array and print each character until it encounters the null
character
No null character (‘\0’) could print undesirable results
// declare a character array
//that can hold 10 characters
char str[10];
str[0] = 'h';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = '\0'; // null character
// now print the string to display
printf ("%s \n", str);
Tedious way of initalizing strings
hello
CGS 3460
Strings
Initialization
char word[ ]="hello";
char word[ ]={"hello“};
word[0]
h
char word[10] = “hello”;
word[0] char word[10] = {“hello”};
h
e
l
l
o
\0
e
l
l
o
\0
CGS 3460
Getting String Input
Several ways – scanf is simplest but most dangerous
Example take input and print it
// demonstrates string input
#include <stdio.h>
main ()
{
// variables declaration
char name[11];
// get input from user
printf ("Your name (10 letters max):\n");
scanf ("%s", &name);
printf ("Hello %s \n", name);
}
Your name (10 letters max):
Neko
Hello Neko
CGS 3460
Notes
In the statement scanf ("%s", &name);
the control string is "%s".
tells the scanf function to interpret the input as a string.
the string is copied into the name array in order.
The & sign stands for address of.
After the input string is copied the null character is added to the end of
the array.
Matter of faith input won’t be over 10 characters
If user exceeds 10 characters
Causes problems
Using scanf is bad idea
See how to handle this later
CGS 3460
Find length of a string
char str[ ] = “do it”;
int i, len;
i = 0;
len = 0;
while (str[i] != '\0')
{
i = i + 1;
}
len = i;
return len;
i
0
len
str
0
d
o
‘‘
i
t
‘\0’
CGS 3460
Find length of a string
char str[ ] = “do it”;
int i, len;
i = 0;
len = 0;
while (str[i] != '\0')
{
i = i + 1;
}
len = i;
return len;
i
0
len
str
0
d
o
‘‘
i
t
‘\0’
CGS 3460
Find length of a string
char str[ ] = “do it”;
int i, len;
i = 0;
len = 0;
while (str[i] != '\0')
{
i = i + 1;
}
len = i;
return len;
i
1
len
str
0
d
o
‘‘
i
t
‘\0’
CGS 3460
Find length of a string
char str[ ] = “do it”;
int i, len;
i = 0;
len = 0;
while (str[i] != '\0')
{
i = i + 1;
}
len = i;
return len;
i
2
len
str
0
d
o
‘‘
i
t
‘\0’
CGS 3460
Find length of a string
char str[ ] = “do it”;
int i, len;
i = 0;
len = 0;
while (str[i] != '\0')
{
i = i + 1;
}
len = i;
return len;
i
3
len
str
0
d
o
‘‘
i
t
‘\0’
CGS 3460
Find length of a string
char str[ ] = “do it”;
int i, len;
i = 0;
len = 0;
while (str[i] != '\0')
{
i = i + 1;
}
len = i;
return len;
i
4
len
str
0
d
o
‘‘
i
t
‘\0’
CGS 3460
Find length of a string
char str[ ] = “do it”;
int i, len;
i = 0;
len = 0;
while (str[i] != '\0')
{
i = i + 1;
}
len = i;
return len;
i
5
len
str
0
d
o
‘‘
i
t
‘\0’
CGS 3460
Find length of a string
char str[ ] = “do it”;
int i, len;
i = 0;
len = 0;
while (str[i] != '\0')
{
i = i + 1;
}
len = i;
return len;
i
5
len
str
5
d
o
‘‘
i
t
‘\0’
CGS 3460
Compare two strings
char str[ ] = “do it”;
int i, len;
i = 0;
len = 0;
while (str[i] != '\0')
{
i = i + 1;
}
len = i;
return len;
i
0
len
str
0
d
o
‘‘
i
t
‘\0’
CGS 3460
Arrays of Arrays
(Multidimensional Arrays)
We have talked about arrays of ints, characters, floats,
etc.
In addition, you can have arrays of arrays
CGS 3460
Multidimensional Arrays
Declaration
type name[ mrows][ncols ];
• e.g. int matrix[5][10];
What it means?
• Declare an array of size mrows
• Each element of that array will be
another array of size ncols of the
given typ
Access
ai , j
n columns
m
a
rows 0 , 0
i changes
matrix[3][4];
Not matrix[3,4], or matrix(3)(4)
m–by–n matrix
a
1, 0
a2 , 0
a0,1
a1,1
a2,1
j changes
a0, 2
a1, 2
a2, 2
CGS 3460
Multidimensional Arrays
Initialization
int M[2][3] = {{1, 2, 3}, {4, 5,6}};
M[0]
1
2
3
M[1]
4
5
6
CGS 3460
Multidimensional Arrays
int M[2][3] = {1, 2, 3, 4, 5, 6};
Numbers will fill up the first row,
then the second row,…
M[0]
1
2
3
M[1]
4
5
6
CGS 3460
Multidimensional Arrays
int M[2][3] = {[0][0] = 1,[1][2]=3};
M[0]
1
0
0
M[1]
0
0
3
CGS 3460
Multidimensional Arrays
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
M[i][j] = 6 – (i * 3 + j)
}
}
M[0]
6
5
4
M[1]
3
2
1
CGS 3460
Multidimensional Arrays
Initialization
int M[2][3] = {{1, 2, 3}, {4, 5,6}};
Or
• int M[2][3] = {1, 2, 3, 4, 5, 6};
• Numbers will fill up the first row, then the second row,…
int M[2][3] = {[0][0] = 1,[1][2]=3};
CGS 3460
The const qualifier
When we need the const qualifier
Specify a variable whose value is constant, i.e., value will not be
changed
How to use
Put const in front of variable definition
• const double pi = 3.141592654;
• const char baseDigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F'};
What if I change its value
E.g. pi = pi * 2;
Get: error: assignment of read-only variable `pi'