0% found this document useful (0 votes)
28 views15 pages

Arrays (Incomplete)

The document discusses arrays in C, which allow storing multiple values of the same type using a single variable name. Arrays must be declared with the array type, name, and size, and individual elements can then be accessed using the array name and index/subscript. Values can be assigned to array elements by specifying the array name and index along with the assignment operator.

Uploaded by

otienophabian200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views15 pages

Arrays (Incomplete)

The document discusses arrays in C, which allow storing multiple values of the same type using a single variable name. Arrays must be declared with the array type, name, and size, and individual elements can then be accessed using the array name and index/subscript. Values can be assigned to array elements by specifying the array name and index along with the assignment operator.

Uploaded by

otienophabian200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

3/2/2023

Objectives
General Objective
To use one dimensional and multidimensionalarray
variables
Arrays in C Specific Objectives:
To
declare them
initialise them
access their elements
discuss how they are stored in memory

Arrays Arrays
Arrays are used when you are dealing with several
related variables of the same type. You may decide to have
E.g. say you want 10 different variables to represent the 10
different integers,
to write a program that will let the user enter 10
integers e.g. 2 4 6 8 … 10 scanf statements to have the user enter
and then print them out in the reverse order that they values for them, and then
were entered i.e. … 8 6 4 2 …
10 printf statements to print them out in
How will you do this? reverse order.

1
3/2/2023

Arrays
Arrays A diagrammatic representation

This is clearly too much code for such a


simple task.
Imagine if you want to do the same thing
with 1000 integers!
Fortunately, C allowsarrays:
a sequence of variables of the same type.

Arrays
Arrays

An array is an identifier that refers to a collection of data


items that all have thesame name. I T E M S
The data items must be of thesame type (e.g. all integers or
all characters). 0 1 2 3 4

you CANNOT store multiple types of data in an array. A representation of an


Note that: an array is a fixed number of data items. array with 5 character
Once you create it you cannot change its size. elements

2
3/2/2023

Arrays Arrays
Declaring Them Declaring Them
To declare an array, you must specify 3
things: char arr_names[5];
the array type This declares an array of5 elements
the array name (identifier) of type char.
the array size (number of values you The name of the array isarr_names.
will store).

Arrays Arrays
Declaring Them Accessing the Values

We now know an array is a collection of data


arr_names (Array name / identifier)
items that all have thesame name and type.
How can we distinguish the individual array
elements from one another?
<=5 characters shall be stored here
By using the value that is assigned to a
subscript.

3
3/2/2023

Arrays Arrays
Accessing Their Elements Accessing the Values
(Array name /
arr_names identifier)
We use the following array syntax:

Elements array_name[i]
[0] [1] [2] [3] [4] Indices / In C, array elements start at position (index) 0.
subscript Square brackets are used to access eachindexed value (aka
element).
Each element can be accessed by a combination of thearray’s Thus:
name and its position in the array (subscript/index).
arr_student_age[5]
BEWARE the off-by-one error; we start from index 0 (not 1).
refers to the sixth element in an array calledarr_student_age.

Arrays Arrays
Accessing Their Elements Accessing Their Elements
int numbers[10]; To access the separate values in this array, you must use
the name of the array followed by
We are declaring an array of 10 the index (subscript) of the element you want to access
integers. within square brackets.
The first element of the array has index 0.
The name of the array is So the numbers array has 10 elements with indexes 0
numbers. through 9.

4
3/2/2023

Arrays
Accessing Array Elements
Accessing Their Elements
numbers
NOTE:
The value inside of the brackets does not have to be a
constant.
To access numbers’ first element:
It could be a variable or expression.
numbers[0] E.g.:

To access the tenth (last) element: numbers[age]

numbers[9]
or even

numbers[mark * 2 + 1]

Arrays Arrays
Assigning Values Assigning Values
int marks [5]; //var declaration
marks We have created an array calledmarks
marks[0] = 21;
21 28 8 16 0 marks has space for 5 int variables.
marks[1] = 28; [0] [1] [2] [3] [4] We then assign integer values to the variables.

marks[2] = 8; Notice that we stored 0 in the last space of the array.


This is a common technique used by C programmers to
marks[3] = 16; signify the end of an array.

marks[4] = 0;

5
3/2/2023

Arrays Arrays
Assigning Values Assigning Values

A single value in an array can be assigned


a value just like any other variable. The following are valid expressions (assuming
numbers is an array of integers):
Just specify the array with the index to numbers[5] = 820;
the left of an assignment operator.
numbers[x] = numbers[x-1] + numbers[x-2];
arr_digits[i] = 0;

Arrays Arrays
Assigning Values Declaring Them
Assigning values to array elements: Arrays may consist of any of the valid
numbers[8] = mark; data types.

Assigning array elements to a variable:


Arrays are declared along with all
other variables in the declaration
mark = numbers [9]; section of the program …

6
3/2/2023

Array Example Array Example


#include <stdio.h> #include<stdio.h>
void main()
int main() {
{ // Declare an array to store the ages (in years) of five children
int ageArray[5];
int numbers[100]; <— Xcode warning: Unused //Enter the values of the elements of the array
float averages[20];
ageArray[0]=10;
variable ‘averages' ageArray[1]=11;
numbers[2] = 10; ageArray[2]=9;
ageArray[3]=8;
--numbers[2]; ageArray[4]=12;
//Now print the ages of the children
printf("The 3rd element of array Numbers is printf("The first child's age is %d years.\n"
,ageArray[0]);
%d\n", numbers[2]); printf("The second child's age is %d years. \n"
printf("The third child's age is %d years. \n"
,ageArray[1]);
,ageArray[2]);
} printf("The fourth child's age is %d years. \n",ageArray[3]);
printf("The fifth child's age is %d years. \n"
,ageArray[4]);
Output? }
The 3rd element of array Numbers is 9 Output?
Program ended with exit code: 0

Output Arrays
Processing Them
The first child's age is 10 years.
The second child's age is 11 years.
The third child's age is 9 years. C does NOT allow single operations involving entire arrays.
The fourth child's age is 8 years.
The fifth child's age is 12 years. Any operations must be carried out on anelement by
Program ended with exit code: 36 element basis.

Note: Examples of operations:

The exit code is not 0 as the compiler assignment


warned us that:
comparison
Return type of ‘main’ is not ‘int’

7
3/2/2023

Arrays Arrays
Assigning Values
Processing Them
For instance, it is NOT acceptable to assign one array to
another array even if they are similar:
Instead, you have to copy one element (value) at a time.
i.e. even if they have the same data type, same
Thus, any such operations must be carried out onan
dimensionality and same size.
element by element basis.
Let numbers and elements be arrays of 10 integers each.
We usually accomplish this within aloop.
It is NOT possible to say:
Each pass through the loop is used to process one array
elements = numbers; element.

Arrays Arrays
Processing Them Processing Them
for (i = 0; i < 10; ++i)
We usually use for loops to iterate over {
an array when printf("The number is: %d",
numbers[i]);
accessing its elements or }
The condition takes into account the fact
writing data to those elements.
that the numbers array has 10 elements.

8
3/2/2023

Arrays Arrays: Processing Them


#include <stdio.h>
Processing Them #define SIZE 10
int main(void)
{
Recall the problem we started with i.e.: int num1, numbers[SIZE];
for (num1 = 0; num1 < SIZE; num1++)
write a program that will let the user enter 10 {
integers e.g. 2 4 6 8 … printf("Enter number: ");
scanf("%d", &numbers[num1]);
and then print them out in the reverse order that }
they were entered i.e. … 8 6 4 2 … printf(“\nReversing the numbers:\n");
for (num1 = SIZE - 1; num1 >= 0; num1--)
How will you do this? printf("%d\n", numbers[num1]);
}
Output?

Sample User’s Screen


NB: This slide shows BOTH the user’s input, and the program’s output.
Arrays
Enter
Enter
number: 2
number: 4
Accessing Their Elements – The
Enter
Enter
number: 6
number: 8
Example Explained
Enter number: 10
Enter number: 12
Enter number: 14
Enter number: 16
Enter
Enter
number: 18
number: 20
A constant, SIZE, is used to represent the
Reversing the numbers:
number of integers used.
20
18
16
The reason you might do this is in case you
14
12
think you might change your mind and want
10
8
to change it later.
6
4
2
Program ended with exit code: 0

9
3/2/2023

Arrays Arrays
Accessing Their Elements – The Example Accessing Their Elements – The Example Explained
Explained

The first "for" loop loops from 0 to SIZE-1.


For instance, let's say you want to change the program to let
the user enter 20 integers and print them out in reverse order.
This is because the array is indexed with
these values.
Now, you only have to change 10 to 20 in one place. The second "for" loop loops from SIZE-1
If you didn't use a constant, how many places would you have down to 0.
to change 10 to 20? This is because we are printing out the array
3 places (everywhere that SIZE is being used). in reverse order.

Arrays Arrays
Accessing Their Elements – The Example Explained Accessing Their Elements – The Example Explained

Note: for (num1 = SIZE - 1; num1 >= 0; num1--)


printf("%d\n", numbers[num1]);
for (num1 = SIZE - 1; num1 >= 0; num1--)
printf("%d\n", numbers[num1]); We place a ‘\n’ at the end of the printf statement in the
second loop for each value to be printed on its own line.
Each iteration of this loop contains just one simple
statement Often, when printing out the values of an array, you will
want to print them out on one line separated by spaces or
(the call to the printf function)
commas.
There is no need to enclose it in curly braces.
Let's say you want to print out the 10 elements of array
However, it’s preferable that you do so. Why? numbers on one line separated by commas.
For readability and consistency. How would you rewrite the output loop?

10
3/2/2023

Arrays
Accessing Their Elements – The Example Explained
Arrays
If you wrote: Accessing Their Elements – The Example Explained

for (num1 = SIZE - 1; num1 >= 0; num1--)


printf(“%d, ", numbers[num1]); You need two extra statements to
It would print out: ensure:
no comma is printed out before the
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Program ended with exit first element to be printed or after
code: 0 the last, and
only one newline is printed out at
There would be a comma at the end of the list of
numbers. the end.

Arrays Arrays
Accessing Their Elements – The Example Explained Accessing Their Elements – The Example Explained

printf("%d", numbers[SIZE - 1]);


for (num1 = SIZE - 2; num1 >= 0; num1--) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
printf(", %d", numbers[num1]); Program ended with exit code: 0
printf("\n");
The last element of the array is printed first.
Each other element is then printed in reverse order with
Output: a comma before each.
When the loop ends, we print out a newline once.
10, 9, 8, 7, 6, 5, 4, 3, 2, 1
Program ended with exit code: 0

11
3/2/2023

Arrays Arrays
Accessing Their Elements – The Example Explained
Accessing Their Elements – A 2nd
printf("%d", numbers[SIZE - 1]); Example:
for (num1 = SIZE - 2; num1 >= 0; num1--)
printf(", %d", numbers[num1]);
printf("\n");
The following programme reads in
In this for loop, notice that unlike our first version of this program, we are text one character at a time until an
now starting num1 at
EOF is read and keeps track of how
SIZE - 2
instead of many times each digit (0 through 9) is
SIZE - 1 encountered.
Why?
We’ve already printed out thearray’s last element.

#include <stdio.h>
Arrays
Accessing Their Elements – A 2nd
Arrays
int main(void)
{
Example: Initialising Values
char c;
int arr_digits[10];
int x; We have to initialise all the values in the array.
for (x = 0; x <= 9; x++)
arr_digits[x] = 0; Just like with simple variables, if the array values are not
while ((c = getchar()) != EOF) initialised, they are unpredictable.
{
if ((c >= '0') && (c <= '9')) Why do we have to initialise the array here but not in the
++arr_digits[c -'0']; first program?
}
for (x = 0; x <= 9; x++) Because in the first program, we have the user enter all
printf("%d\n", arr_digits[x]); the values, and these values are assigned directly to the
return 0; array.
}
Output:

12
3/2/2023

Arrays Arrays
Initialising Values Assigning Values

Also note that a single value in an array can be


In this program, we are counting digits, and assigned a valuejust like any other variable.
incrementing the values in the array but never Just specify the array with the index to the left of an
assigning them directly to a specific value. assignment operator.
The following are valid expressions (assuming
We need all the values to start at 0 to have this numbers is an array of integers):
program work. numbers[5] = 820;
numbers[x] = numbers[x-1] + numbers[x-2];

Arrays Arrays
Accessing Their Elements – A 2nd Example
Assigning Values Explained:

Remember, it is NOT acceptable to assign


one array to another array. In the example2 prog, when we read a digit, we can check if the
character 'c' represents a digit by checking if it is greater than or
Let numbers and elements be arrays of equal to the character '0' and less than or equal to thecharacter '9'.
10 integers each. This is because the ASCII codes for the digits 0,1,2,…,9 are 48
through 57 respectively.
It is NOT possible to say: It is for this reason also that we can subtract the character '0' from

elements = numbers; the character 'c' to find the appropriate index in the array.
Characters used in expressions are treated as their ASCII values, so
'0' - '0' = 0, '1' - '0' = 1, etc.
Instead, you have to copy one element
(value) at a time.

13
3/2/2023

A Grading Program
Write a program that allows me to
Assignment/ enter 5 marks, and then gives me their
Homework
average.
Use what you’ve learned about arrays.
The output should be similar to
what’s in the next slide…

Sample User’s Screen


NB: This slide shows BOTH the user’s input, and Note:
the program’s ouput.
Please enter 5 marks: Each mark:

1: 45 is numbered sequentially.
2: 66 is neatly aligned on its own line.
3: 24
4: 88 Always remember that it is crucial that both
5: 32 your code and

The average mark is: 51.00 your output


are readable.
Program ended with exit code: 0

14
3/2/2023

Arrays
Arrays
Initialising Values
What does the following code snippet do? Just like with simple variables, if the array
v a l u e s a r e n o t i n i t i a l i s e d, t h e y a r e
unpredictable.
int arr_digits[10], i; Why do we have toinitialise the array here
for (i = 0; i <= 9; i++) but not in the example program (the one
arr_digits[i] = 0; reversing numbers)?
Because in the first program, we have the
It initialises all the values in the array to zero. user enter all the values, and these values
are assigned directly to the array.

15

You might also like