C/C++ Arena

Step 3 of 7

void functions

Not every function computes a value. Some exist for what they do, like printing. Their return type is void, meaning "returns nothing":

#include <stdio.h>

void greet(int times) {
    for (int i = 0; i < times; i++) {
        printf("hi ");
    }
    printf("\n");
}

void banner(void) {
    printf("=== START ===\n");
}

int main(void) {
    banner();
    greet(3);
    greet(1);
    return 0;
}
=== START ===
hi hi hi 
hi 

Details

Why bother?

Even small helpers make code easier to read. print_bar(10) says what it does; a loop that prints ten = characters has to be read to be understood. And if you need the same output in five places, a function means one place to fix when it changes.

Your task

Write void print_bar(int n) that prints n = characters followed by a newline. print_bar(5) prints =====.

Challenge 2

Write void print_row(char c, int n) that prints the character c exactly n times, then a newline. print_row('#', 3) prints ###.

Challenge 3

Write void print_box(int w, int h) that prints a hollow box w characters wide and h rows tall. The first and last rows are all #. The rows in between have # at both ends and spaces inside. print_box(4, 3) prints:

####
#  #
####

Previous: Write a function Next: Prototypes