// Lab 3 Solution // Do not distribute beyond class this semester. /* Pseudocode solution: MAX_LEN = 5 history: [string; MAX_LEN] current_len: int = 0 func get_input() func add_to_history(input) func print_history() func main(): loop: let input = get_input() add_to_history(input) if input == "print": print_history() func add_to_history(input): if current_len < MAX_LEN: history[current_len] = input current_len += 1 else: remove_oldest_record() history[current_len] = input current_len += 1 func remove_oldest_record(): ensure(current_len > 0) free(history[0]) for i from 1 to current_len: history[i - 1] = history[i] current_len -= 1 func print_history(): for i from 0 to current_len: print(history[i]) */ #include #include #include #define MAX_LEN 5 char *input_history[MAX_LEN]; int history_count = 0; void add_to_history(char *input); void remove_oldest_record(); void print_history(); char *get_input(); int main() { while (1) { char *input = get_input(); add_to_history(input); if (strcmp(input, "print") == 0) { print_history(); } } // TODO: Free the memory of the input history return 0; } char *get_input() { char *buffer = NULL; size_t bufsize = 0; printf("Enter input: "); size_t len = getline(&buffer, &bufsize, stdin); if (len == -1) { exit(1); } // Remove the newline character at the end of the input buffer[len - 1] = '\0'; return buffer; } void add_to_history(char *input) { if (history_count >= MAX_LEN) { remove_oldest_record(); } input_history[history_count] = input; history_count++; } void remove_oldest_record() { if (history_count > 0) { // Free the memory of the oldest record free(input_history[0]); for (int i = 1; i < history_count; i++) { input_history[i - 1] = input_history[i]; } history_count--; } } void print_history() { for (int i = 0; i < history_count; i++) { printf("%s\n", input_history[i]); } }