Introduction to Computer Science - Fall 2004

C Arrays

Example 1 - simple array manipulations

#include<stdio.h >

int main(){
    int num[5];      /* num is an array of 5 integers*/
    int i;

    printf("Please enter 5 integers - elements of the array ");
    for (i = 0; i < 5; i++){
      scanf("%d", &num[i]);
    }
    printf("Elements of the array are: \n");
    for (i = 0; i < 5; i++){
      printf("the element %d is %d \n", i, num[i]);
    }

    return 0;
}

Example 2 - sum and average of the elements of the array

#include<stdio.h >

int main(){
    int num[5] = {1, 3, -4, 5, 2};
    int sum = 0;
    double average;
    for (i = 0; i < 5; i++){
      sum += num[i];
    }
    average = (double) sum /5;
    printf("The sum is %d and the average is %f\n", sum, average);

    return 0;
}

Example 3 - the max element of the array

#include<stdio.h >

#define SIZE 5

int main(){
    int num[SIZE] = {0}; /* initialization of all elements of the array to 0 */
    int i, max;
    /* input array */
    for (i = 0; i < 5; i++){
      scanf("%d", &num[i]);
    }
    max = num[0];
    for (i = 1; i < 5; i++){
      if (max < num[i])
        max = num [i];
    }
    printf("The maximum is %d \n", max);

    return 0;
}

Example 4 - compare two arrays

#inlcude < stdio.h >

#define SIZE 5

int main(){
    int a[SIZE] = {0}, b[SIZE] = {0}; /* initialization of all elements of the arrays to 0 */
    int i;
    int equal = 1; /* 1 ( true ) means that two arraysare indentical, 0 ( false ) - otherwise */
    /* input array */
    for (i = 0; i < 5; i++){
      scanf("%d%d", &a[i], &b[i]);
    }
    for (i = 0; ( i < 5 ) && equal ; i++){
      if (a[i] != b[i] )
        equal = 0;
    }
    if ( equal )
      printf("The arrays are identical \n");
    else
      printf("The arrays are not identical \n");

    return 0;
}