Laborarory: Arrays

Gábor Horváth / Zsolt Kohári · 2020.10.01.

Character codes. Creation and handling of arrays. Simple array algorithms.

1. Character codes

What does the following program do? How does it work? How to exit from it, what does end of file mean? Why does variable letter appear twice in printf()? The scanf("%c", &letter) == 1 expression has two effects, what are these?

#include <stdio.h>

int main(void) {
    char letter;
    while (scanf("%c", &letter) == 1) {
        printf("letter='%c', letter=%d\n", letter, letter);
    }

    return 0;
}

Note, that the program will print the output when you hit Enter after typing a line of text. This does not mean that scanf() is not reading the input by single characters. The line buffered input is the feature of the console window of the operating system and lets the user edit mistyped input before the program receives it.

Hint:The program keeps reading characters until the user sends an end of file signal. Under Windows pressing F6Enter or Ctrl+ZEnter on a new line, under Linux Ctrl+d will send end of file.

2. Indexing out of bounds

Try the following program, what output do you expect? What do you get, why?

This program has undefined behaviour.

Compiling and running on different platforms
and/or using a different C compiler
may change its behaviour.
#include <stdio.h>

int main(void) {
  double t[10];
  int a = 1, b = 2, c = 3;

  printf("a=%d\nb=%d\nc=%d\n", a, b, c);

  /* indexing out of bounds */
  t[-1] = 0.2;
  t[10] = 0.3;
  printf("\n");

  printf("a=%d\nb=%d\nc=%d\n", a, b, c);

  return 0;
}

Try the following program. What does while (true) mean?

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    int array[10], i;

    for (i = 0; i < 10; i = i + 1)
        array[i] = i;
    i = 0;
    while (true) {
        printf("%dth element: %d\n", i, array[i]);
        i += 1;
    }

    return 0;
}

The second program contains an infinite loop: while (true). Theoretically this program would run forever but sooner or later it tries to access a memory location that is not dedicated to your program and then the operating system will stop it.

3. Least

Write a program that creates an array of ten elements! Assign initial values to the array elements, too! (So you do not need to read them one by one.) Print the array to the screen!

Array: 25 69 54 8 77 6 29 10 3 98

Modify your program to print the corresponding index values, too!

The array: [0]=25 [1]=69 [2]=54 [3]=8 [4]=77 [5]=6 [6]=29 [7]=10 [8]=3 [9]=98

Extend your program to find and print the least element of the array. (Test it for three cases: when the least number is the first element of the array; when it is the last; when it is somewhere in between them!) Print the array in such manner that a special mark is printed at the least element.

The least: 3
Marked: 25 69 54 8 77 6 29 10 3[MIN] 98

Solution

#include <stdio.h>

int main(void) {
    int array[10] = { 25, 69, 54, 8, 77, 6, 29, 10, 3, 98 };

    /* Printing */
    printf("Array: ");
    for (int i = 0; i < 10; i = i + 1)
        printf(" %d", array[i]);
    printf("\n\n");

    /* Printing */
    printf("The array:");
    for (int i = 0; i < 10; i = i + 1)
        printf(" [%d]=%d", i, array[i]);
    printf("\n\n");

    /* Minimum finding */
    int minloc = 0;
    for (int i = 1; i < 10; i = i + 1)
        if (array[i] < array[minloc])
            minloc = i;
    printf("The least: %d\n", array[minloc]);
    printf("Index of the least: %d\n", minloc);

    /* Marked printing */
    printf("Marked: ");
    for (int i = 0; i < 10; i = i + 1) {
        printf(" %d", array[i]);
        if (i == minloc)
            printf("[MIN]");
    }
    printf("\n");

    return 0;
}

4. Shifting an array

25 69 54  8 77  6 29 10  3 98
69 54  8 77  6 29 10  3 98 25
54  8 77  6 29 10  3 98 25 69
 8 77  6 29 10  3 98 25 69 54
77  6 29 10  3 98 25 69 54  8
 6 29 10  3 98 25 69 54  8 77
29 10  3 98 25 69 54  8 77  6

Write a program that contains an array of 10 elements initialized by values of your choice.

Shift all elements in the array towards the beginning of the array by one cell. The first element should go into the last cell (you may call this process rotation ). Repeat the shifting (rotation) process 10 times, printing the array after each step. Your output should be similar to the one shown on the right side.

Keep in mind, that the task is not to obtain the output by using tricky indexing! The elements of the array must actually move around!

LOOP

    print the array        only printf here, no change in the array

    rotate the array to the left by 1 the array changes, no printf here

END OF LOOP

Hint

There is no need for a second array! The second element can overwrite the first, the third can overwite the second… The only qestion is what shall we put into the last cell. Make a drawing and find out the necessary steps.

Solution

#include <stdio.h>

int main(void) {
    int array[10] = {25, 69, 54, 8, 77, 6, 29, 10, 3, 98};

    /* Printing and shifting 10 times */
    for (int j = 0; j < 10; j = j + 1) {
        /* Printing */
        for (int i = 0; i < 10; i = i + 1)
            printf("%d ", array[i]);
        printf("\n");

        /* Shifting */
        int tmp = array[0]; /* Saving the first element */
        for (int i = 0; i < 9; i = i + 1)
            array[i] = array[i+1]; /* Shifting */
        array[9] = tmp; /* Put the saved element to the last position */
    }

    return 0;
}

5. Highway I.

An automatic speed control unit on a highway delivers data of the speeding cars only for several days in the following format: „hours minutes speed”. For example 12 45 198 means that at 12:45 some car passed by at a speed of 198 km/h. Data is terminated by 0 0 0.

Write a C program that reads the data (several hours-minutes-speed triplets, until the terminating 0-0-0 triplet) and prints a table with the fastest speeding car in every hour! If there was no car violating the speed limit in a given hour, exclude that interval from the output. The output should be like:

14:00-14:59 -> 145 km/h
16:00-16:59 -> 167 km/h

(Hint: all speed values are positive.)

Solution

#include <stdio.h>

int main(void) {
   int max_speed[24] = {0};
   int hour, min, speed;

   scanf("%d %d %d", &hour, &min, &speed);
   while (speed != 0) {
      if (speed > max_speed[hour])
         max_speed[hour] = speed;
      scanf("%d %d %d", &hour, &min, &speed);
   }

   for (int i = 0; i < 24; i = i + 1)
      if (max_speed[i] > 0)
         printf("%2d:00-%02d:59 -> %d km/h\n", i, i, max_speed[i]);

   return 0;
}

6. Further problems for practicing

Pretty printing of an array

Write a program segment (extend one of your programs using arrays) that prints the elements of an array in a nice format, separating the elements by a comma and enclosing the list of values in a pair of square brackets. Your code should be nice, too: a single loop is necessary, no conditional statement is needed.

[ 25, 69, 54, 8, 77, 6, 29, 10, 3, 98 ]

Monotonity

Write a program that contains an initialized array of integers. The program should check whether all elements of the array, in the given order form a monotonously increasing series, a monotonously decreasing one, or neither of them!

Test your program for all three cases, especially breaking the monotonity with the first two or with the last two elements.

Hint

Which programming theorem can be applied here? In other words: what do we need to find to know that it is NOT a monotonously increasing series?

Average of the last five values

Write a program that reads numbers from the user. Entry terminates when the user gives 0. After that the program should print the average of the last five entries. (Suppose there were at least five values read.)

Hint

The idea of „let's make an array of million elements, that is surely sufficient to store all the values” is completely wrong (there are entries that would not fit). How many numbers shall be remembered at any moment? Do we need an array at all? If yes, then of what size? Do we need to shift the elements in the array?

River

We measure the depth of the water at every two meters across the river, and put the values in an array (initialize by these values). This is the result:

0.1, 1, 1.5, 1.7, 2, 2.3, 2.8, 4.5, 9.8, 12, 14.1, 13, 11.9, 8.7, 6.1, 3.5, 1, 0.5

Write a program to find out where is the steepest the bottom of the river.

Hint

Which programming theorem can be applied? Which of the steepness values are we looking for? Note that uphill or downhill does not matter (fabs in math.h delivers absolute value), and keep your index values within the bounds!

Less or greater?

There is an integer array of n elements filled with values. Write a program that reads a number from the user (limit) and decides which set has more elements: elements of the array that are less than limit or those greater than limit.

Highway II.

It was a short test

An automatic speed control unit on a highway delivers data of the speeding cars only for several days in the following format: „hours minutes speed”. For example 12 45 198 means that at 12:45 some car passed by at a speed of 198 km/h. Data is terminated by 0 0 0.

The fine for driving faster than 140 km/h is 50 EUR, over 180 km/h it is 150 EUR.

Write a C program that reads the data and prints a table with the sum of the fines in every hour! Output should look like:

12:00-12:59, 650 EUR
13:00-13:59, 1400 EUR

Statistics on letters

A: 5 times
B: 3 times
C: 4 times
...

Read the text from standard input (terminated by end of file signal). The text is in ALL UPERCASE LETTERS. Give statistics of the frequency of each letter (just disregard any other character).

Statistics of Mid-semester Tests I.

It was a short test

A tutor wants to see statistics of the Mid-semester Tests delivered by the students. There were four different test sheets (A…D), three problems of 10 points each. The scores are integers, and a student can earn maximum 30 points. To pass the test the student must earn at least 2 points for each problem, and at least 12 for the whole test.

Write a program that reads the test scores: a letter and then three numbers, line by line. Then the program prints how many students succeeded in each of the 4 different tests. Input is terminated by x 0 0 0.

Sample input:

A 1 10 7
C 3 3 5
B 10 10 9
x 0 0 0

Sample output:

A 0
B 1
C 0
D 0