Additional exercises

Additional exercises#

Activity 78 (Fizz buzz)

Fizz buzz is a group game for children to teach them about division. If a number is divisible by three, you must say Fizz; if by five, Buzz; if by both Fizz buzz. For example a typical round looks like this:

1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, Fizz Buzz, 16 …

Write a program that outputs the Fizz buzz sequence for numbers less than 40. You can use colors to make the Fizz buzz numbers easier to notice:

Fizz buzz💚, 1, 2, Fizz💙, 4, Buzz💛, Fizz💙, 7, 8, Fizz💙, Buzz💛, 11, Fizz💙, 13, 14, Fizz buzz💚, 16, 17, Fizz💙, 19, Buzz💛, Fizz💙, 22, 23, Fizz💙, Buzz💛, 26, Fizz💙, 28, 29, Fizz buzz💚, 31, 32, Fizz💙, 34, Buzz💛, Fizz💙, 37, 38, Fizz💙, 

Activity 79 (Is there a bug? (2))

Analyze the following code snippets. Is there a bug in each code? If yes, where?

Should loop over the characters of a word:

#define WORD_LEN 40
char word[WORD_LEN];

for (size_t i = 1; i <= WORD_LEN; i++)
  if (word[i] == 'x')
// ...

Should replace a with A in the input word.

for (size_t i = 0; i < sizeof(word); ++i)
    if (word[i] == "a")
        word[i] = "A";

Activity 80 (How to debug)

The following program should output a, but it does not. How would you debug it?

#include <stddef.h>
#include <stdio.h>
#include <string.h>

#define ASCII_LETTER_COUNT 'z' - 'a' + 1

size_t letter_to_index(char letter) { return letter - 'a'; }
char index_to_char(size_t index) { return index + 'a'; }

char ascii_letter_with_highest_occurrence(const char *word) {
  size_t occ[ASCII_LETTER_COUNT];

  // Loops over the letters and increases their occurrence count
  for (size_t i = 0; i < strlen(word); ++i)
    ++occ[letter_to_index(word[i])];

  size_t max = 0;
  char char_with_highest_occ_index;
  for (size_t i = 0; i < occ[i]; ++i)
    if (occ[i] > max)
      char_with_highest_occ_index = i;
  return index_to_char(char_with_highest_occ_index);
}
int main() { putc(ascii_letter_with_highest_occurrence("merhaba"), stdout); }

Output

b