0% found this document useful (0 votes)
4 views7 pages

Arrays

The document provides an overview of arrays in programming, including how to create and access one-dimensional and multidimensional arrays. It includes examples of declaring arrays, populating them with values, and accessing their elements using loops. Additionally, it highlights a common bug related to array indexing in C programming.

Uploaded by

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

Arrays

The document provides an overview of arrays in programming, including how to create and access one-dimensional and multidimensional arrays. It includes examples of declaring arrays, populating them with values, and accessing their elements using loops. Additionally, it highlights a common bug related to array indexing in C programming.

Uploaded by

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

Arrays

0 1 2 3 4 5
Creating an Array
<data type> name[<size>];

Example:
int temperature[3]; 0 1 2
temperature[0] = 65;
temperature[1] = 87;
temperature[2] = 30; 65 87 30
OR

int temperature[] = { 65, 87,


30 };
Accessing Array Elements

0 1 2

65 87 30
for (int i = 0; i < 3; i++)
{
printf("%d\n",
temperature[i]);
}
#include <stdio.h>
#include <cs50.h>

#define CLASS_SIZE 30

int main(void)
{
// declare array
int scores_array[CLASS_SIZE];

// populate array
for (int i = 0; i < CLASS_SIZE; i++)
{
printf("Enter score for student %d: ", i)
scores_array[i] = GetInt();
}
}
Where's the bug?

string class[3] = { "Sam", "Jess", "Kim" };

for (int i = 0; i <= 3; i++)


{
printf("%s\n", class[i]);
}
Multidimensional Arrays
0,0 0,1 0,2

char board[3][3];
board[1][1] = 'o';
x x
1,0 1,1 1,2
board[0][0] = 'x';

o
board[2][0] = 'o';
board[0][2] = 'x';

2,0 2,1 2,2

o
Accessing Multidimensional
Array Elements

// print out all elements


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
printf("%c", board[i]
[j]);
printf("\n");
}

You might also like