CMPE 150: Introduction To Computing: Arrays
CMPE 150: Introduction To Computing: Arrays
to Computing
Arrays
Motivation
• You may need to define many variables of
the same type.
– Defining so many variables one by one is
cumbersome.
• Probably you would like to execute similar
statements on these variables.
– You wouldn't want to write the same
statements over and over for each variable.
• Soln:
#include <stdio.h>
int main()
{ int i, sum=0, grade; float avg;
• Soln #1:
#include <stdio.h>
int main()
{ int i, sum=0, grade; float avg;
for (i=0; i<350; i++)
{ scanf("%d", &grade); WRONG!
sum += grade; "grade" contains the
} score of the last student.
avg = sum/350.0; You have already lost the
previous 349 scores.
for (i=0; i<350; i++)
if (grade<avg)
printf("Below avg: %d\n",grade);
return 0;
}
int a[3];
...
a={5,8,2} is wrong.
i=-2;
m[i] = 9.2; /* Run-time error */
#include<stdio.h>
int main()
{ int X[100], i;
float avg=0,var=0; Unbiased variance of a
sample is defined as
N
for (i=0; i<100; i++)
{ scanf("%d",&X[i]); ∑(X
i =1
i − µ ) 2
avg += X[i];
} N −1
avg /= 100;
for (i=0; i<100; i++)
var += (X[i]-avg) * (X[i]-avg);
var /= 99;
printf("variance:%f\n", var);
return 0;
}
#include <stdio.h>
int main()
{ int i, hist[101]={0}, score;
#include <stdio.h>
#define SIZE 10
int main()
{ int numbers[SIZE], i;
int main()
{ int p1[MAX]={0}, p2[MAX]={0}, result[MAX]={0}, i, n;
int main()
{ int ar[10];
read_array(ar,10);
bubble_sort(ar,10);
print_array(ar,10);
return 0;
}