Blending data and logic#
Two different programming styles#
Imagine you want to write an application that checks if the entered food is one of the following vegetables or not:
carrot
beetroot
cabbage
Take 1
#include <stdio.h>
#include <string.h>
#define LINE_SIZE 30
char line[LINE_SIZE];
int main(void) {
printf("I can help you with your diet.\n");
printf("Enter the food: ");
scanf("%s", line);
if (strcmp(line, "carrot") == 0 || strcmp(line, "beetroot") == 0 ||
strcmp(line, "cabbage") == 0)
puts("✅ this is a vegetable.");
else
puts("❌ I don't know what this is.");
}
Take 2
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE_SIZE 30
#define VEGETABLE_COUNT 3
char line[LINE_SIZE];
const char MESSAGE_WELCOME[] = "I can help you with your diet.\n"
"Enter the food: ";
const char KNOWN_VEGETABLES[][LINE_SIZE] = {"carrot", "beetroot", "cabbage"};
const char MESSAGE_POSITIVE[] = "✅ this is a vegetable.";
const char MESSAGE_NEGATIVE[] = "❌ I don't know what this is.";
int main(void) {
printf(MESSAGE_WELCOME);
scanf("%s", line);
for (size_t i = 0; i < _Countof KNOWN_VEGETABLES; ++i)
if (strcmp(line, KNOWN_VEGETABLES[i]) == 0) {
puts(MESSAGE_POSITIVE);
return EXIT_SUCCESS;
}
puts(MESSAGE_NEGATIVE);
}
char variable[][N]
means a collection of strings, where for each stringN
characters are reserved. We will introduce this.
Activity 12
Which differences do you notice regarding:
readability
structure, e.g., where which components of code is located
How could this difference affect the programming experience?
Steps:
3 min think individually and discuss with your partner