Lec2 - Arrays (Part2)
Lec2 - Arrays (Part2)
PART 2
Angelika S. Balagot
Instructor
Target Topics
int main () {
Output:
int i;
int value[3];
int numbers[6] = {2,4,6,8,10,12}; 24681012
char word[] = {‘h’,‘e’,‘l’,‘l’,‘o’};
hello
for (i=0; i<6; i++) 555
printf(“%d", numbers[i]);
printf(“\n”);
for (i=0; i<5; i++)
printf(“%c", word[i]);
printf(“\n”);
for (i=0; i<3; i++) {
value[i] = 5;
printf(“%d", value[i]);
}
}
Array Operations
B. Updating and totaling array elements
#include <stdio.h>
Output:
int main () {
1, A 2, B 3, C 4, D 5, E …
• As can be seen – after one “pass” over the array, the largest element
(5 in this case) has reached its correct position – extreme right. Let us
try to repeat this process, focusing on 4:
• Currently - [1, 4, 2, 3, 5]:
• (1, 4) is correct. However, (4, 2) is an incorrect order. Therefore, we
swap 4 and 2 to get [1, 2, 4, 3, 5]. Now again, (4, 3) is incorrect so we
do another swap and get [1, 2, 3, 4, 5].
Array Operations
C. Sorting – Bubble Sort
• Example:
int age[3][5];
double salary[2][3][5];
Two-Dimensional Array
• int papersize[x][y];
Two-Dimensional Array
• int papersize[3][5];
Two-Dimensional Array
• So, to access the value of the 1st Row and 2nd Column, you need
to write:
• data type arr[0][1];
Initializing 2D Arrays
int a[2][3] = {
{0, 1, 2}, /*Row 1*/
{3, 4, 5} /*Row 2*/
};
Initializing 2D Arrays
• Take note that the nested braces, which indicate the intended
row, is optional.
• The following is equivalent to the previous example:
• int scores[x][y][z];
Three-Dimensional Array
• int scores[x][y][z];
• int scores[2][4][3];
Three-Dimensional Array
int a[2][2][3] =
{
{ • Three-dimensional
/*Table 1*/
{0, 1, 2}, /*Row 1*/
arrays may be initialized
{3, 4, 5} /*Row 2*/ by specifying bracketed
}, values for each row. For
{ example, we have an
/*Table 2*/
{6, 7, 8}, /*Row 1*/ array with 2 tables, 2
{9, 10, 11} /*Row 2*/ rows and each row has
}, 3 columns.
};
Initializing 3D Arrays
• Take note that the nested braces, which indicate the intended row,
is optional. The following is equivalent to the previous example:
• So to access the
int a[2][2][3] = {
{ {0, 1, 2},{3, 4, 5} } },
value 3, you can
{ {6, 7, 8},{9, 10, 11} } use the ff:
}; • int a[0][1][0];
Topic 1.7: Passing Arrays to
Functions
Passing Arrays to Functions
• As a pointer…
• As a sized array…
• As an unsized array…
As a POINTER
#include <stdio.h>
#include <stdio.h>
#include <stdio.h>
Angelika S. Balagot
Instructor