Introduction to Computer Science - Fall 2004

C Arrays

Example 1 - histograms (p.210 chapter 6 of your textbook)

#include<stdio.h >
#define SIZE 10

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

    printf("Please enter %d integers - elements of the array ", SIZE);
    for (i = 0; i < SIZE; i++){
      scanf("%d", &num[i]);
    }

    printf("The histogram\n ");

    for (i = 0; i < SIZE; i++){
      printf("%d %d", i, num[i]);

      for (j = 1; j <= num[i]; j++){
        printf("%c", '*');
      }
      printf("\n");
    }

    return 0;
}

Example 2 - rolling dice and counting frequencies (p. 211 chapter 6 of your textbook)

#include<stdio.h >
#include<stdlib.h >
#include<time.h >
#define SIZE 7

int main(){
    int frequency[SIZE] = {0}; /* all counters have initial value 0 */
    int face; /* random value between 1 and 6 */
    int roll; /* total amount of rolls */
    int i;

    srand(time(NULL)); /* seed random-number generator */

    for (roll = 1; roll <= 6000; roll++){
      face = 1 + rand ( )% 6;
      frequence[face]++;
    }

    printf("%s%17s\n", "Face", "Frequency");

    for (face = 1; face < SIZE; face++){
      printf("%4d%17d\n", face, frequency[ face ]);
    }

    return 0;
}

Example 3 - string manipulations

#include<stdio.h >
#define SIZE 20

int main(){
    char word[SIZE];     /* reserves SIZE char spaces */
    int i = 0;
    scanf("%s", word );

    while (word[i] != '\0'){
      printf("%c\n", word[i] );
      i++;
    }
    printf("\n");

    printf("%s", word); /* prints string */

    return 0;
}