VII. Arrays
VII. Arrays
IN C PROGRAM
<p> COMSCI 1101 LECTURE </p>
WHAT IS AN ARRAY?
▪ An array is a group of memory locations related by
the fact that they have the same identifier and
data type.
Elements
0 1 2 3 4 5 6 7
Indexes
Array Size = 8
Elements
5 3 2 6 8 10 62 15
0 1 2 3 4 5 6 7
Indexes Index: 3
Element: 6
WHAT IS AN ARRAY?
▪ Array must be declared before they are used.
data_type array_name[size];
▪ Example:
int num[4];
int x = 3;
num[4 – 3] = 101;
num[x * 3 – 6] = 103;
ACCESS ARRAY ELEMENTS
▪ An individual array element can be used just like
variable.
▪ Example:
num[0] = 100;
num[1] = num[0];
printf(“%d”,num[1]);
ACCESS ARRAY ELEMENTS
▪ Array elements can also be used in calculations.
They are also operands.
▪ Example:
void main(){
clrscr();
int num[3], x = 2, y = 1, sum;
num[0] = x;
num[1] = y;
sum = (num[0] + y) * (x + num[1]);
num[2] = sum;
void main(){
clrscr();
char word[] = {‘W’, ‘H’, ‘A’, ‘T’, ‘\0’};
printf(“Index 2 = %c”,word[2]);
getch();
}
Index 2 = A
_}
ARRAY OUT OF BOUNDS
▪ C has no array bounds checking to prevent the
computer from referring to an element that does not
exist.
void main(){
clrscr();
int numbers[5];
printf(“Enter a number: ”);
scanf(“%d”,&numbers[100]);
int num[10];
for(int x = 0; x < 10; x++){
num[x] = x + 1;
}
ARRAYS & LOOPS
▪ Print the values of the elements of num[10]
for(int y = 0; y < 10; y++)
printf(“%d”,num[y]);
void main(){
clrscr();
int num[10], sum = 0;
for(int x=0; x<=9; x++){
printf(“Enter number [%d]: ”,(x+1));
scanf(“%d”,&num[x]);
}
for(int y=0; y<=9; y++){
sum += num[y];
}
printf(“The sum of the 10 integers is %d\n”,sum);
getch();
}
Enter number [1]: 5
Enter number [2]: 9
Enter number [3]: 3
Enter number [4]: 2
Enter number [5]: 7
Enter number [6]: 7
Enter number [7]: 2
Enter number [8]: 5
Enter number [9]: 6
Enter number [10]: 3
The sum of the 10 integers is 49
_}
PASS ARRAYS TO FUNC
▪ Specify the name of the array without any brackets
printArray(num, 4);
getch();
}
1 2 3 4 _
#include <stdio.h>
#include <conio.h>
}
void main(){
clrscr();
int num[10], even = 0, odd = 0;
for(int x=0; x<=9; x++){
printf(“Enter number [%d]: ”,(x+1));
scanf(“%d”,&num[x]);
}
for(int y=0; y<=9; y++){
if(oddOrEven(num[y]))
even++;
else
odd++;
}
printf(“There are %d even and %d odd numbers”,even, odd);
getch();
}
Enter number [1]: 5
Enter number [2]: 9
Enter number [3]: 3
Enter number [4]: 2
Enter number [5]: 7
Enter number [6]: 7
Enter number [7]: 2
Enter number [8]: 5
Enter number [9]: 6
Enter number [10]: 3
There are 3 even and 7 odd numbers_}
THANK
YOU!