What is an Array ?
An array is data structure (type of memory layout)
that stores a collection of individual values that
are of the same data type.
Arrays are useful because instead of having to
separately store related information in different
variables (named memory locations), you can store
them—as a collection—in just one variable.
65 72 83 79 97 87 79 57 … 78
65
72 83
79
97
87
79
57
78
…
scores
How to
Sort
Search
?
score1
score2
…
scoren
scores(1) scores(2) … scores(n)
Array
• element
arrayname[position-number]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
c[6]
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
c
Array
Name
Arrays
Array
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
c[6]
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
c
c[0] = 3;
scanf(“%d”, &c[1]);
printf(“%d”, c[1]);
Defining Arrays
arrayType arrayName[numberOfElements]
#define MAX 200;
int c[12];
float f[1000];
int a[MAX], b[MAX*10];
int n, m=5, x[m];
scanf(“%d”,&n);
int y[n];
Arrays Inilialization
arrayType arrayName[numberOfElements] = {valueList};
int a[5] = {1, 2, 3, 4, 5};
int a[5] = {1};
int a[ ] = {1, 2, 3, 4, 5};
Using Arrays
Example:Using Arrays
**************
***
*******
Using Arrays
Example:Using Arrays
#include <stdio.h>
#define SIZE 10
void main() {
int n[SIZE] = {19, 2, 15, 7, 11, 9, 13, 5, 17, 1};
int i ,j;
printf("%s%13s%17sn", "Element", "Value", "Histogram");
for (i=0; i<=SIZE-1; i++) {
printf("%7d%13d", i, n[i]);
for (j=1; j<=n[i]; j++)
printf("%c", '*');
printf("n");
}
}
Using Arrays
Example:Using Arrays
Element Value Histogram
0 19 *******************
1 3 ***
2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
7 5 *****
8 17 *****************
9 1 *
Using Arrays
Example:Using Arrays
#include <stdio.h>
#define MAX 32
void main()
{ float score[MAX], sum, best;
int i;
printf("Input %d scores:n",MAX);
for (i=0; i<MAX; i++)
scanf("%f", &score[i]);
Using Arrays
Example:Using Arrays
sum=best=score[0];
for (i=1;i<MAX;i++)
{ sum+=score[i];
if (best<score[i])
best=score[i];
}
printf("The average:%.1fn", sum/MAX);
printf("The best:%.1fn", best);
}
#include <stdio.h>
#define MAX 32
void main()
{ float score[MAX], sum;
int i, best;
printf("Input %d scores:n",MAX);
for (i=0; i<MAX; i++)
scanf("%f", &score[i]);
Using Arrays
Example:Using Arrays
65 72 83 79 97 87 79 57 91 78
Using Arrays
Example:Using Arrays
sum=score[0];
best=0;
for (i=1; i<MAX; i++)
{ sum+=score[i];
if (score[best]<score[i])
best=i;
}
printf("The average:%.1fn", sum/MAX);
printf("The best:%.1fn", score[best]);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 7
void main() {
int face, roll, frequency[SIZE]={0};
srand(time(NULL));
Using Arrays
Example:Using Arrays
frequency[1], …, frequency[6]

Session11 single dimarrays