C
Listing tasks
Learn to print tasks formatted with ListTasks.
The list_tasks function
To print all tasks we write the list_tasks function. A for loop runs from 0 to count and prints each task.
void list_tasks(struct Task tasks[], int count) {
for (int i = 0; i < count; i++) {
printf("%d %s %d\n", tasks[i].id, tasks[i].title, tasks[i].done);
}
}
The function returns void; it only prints, it does not change anything. Exactly count tasks are printed.
Walking with a for loop
The pattern for (int i = 0; i < count; i++) starts at 0 and walks every element up to (but not including) count. i is the index, tasks[i] is the task at that index.
for (int i = 0; i < count; i++) {
printf("%d %s\n", tasks[i].id, tasks[i].title);
}
This pattern is standard for walking arrays. The count bound marks the used part of the array.
Exercise Add the list_tasks function
Add the void list_tasks(struct Task tasks[], int count) function to the code below. Inside it use a for (int i = 0; i < count; i++) loop to print each task as printf("%d %s %d\n", tasks[i].id, tasks[i].title, tasks[i].done);. In main replace the two printf calls with a list_tasks(tasks, count); call. Output should be 1 Shopping 0 and 2 Sport 0.
Show example solution
#include <stdio.h>
#include <string.h>
struct Task {
int id;
char title[50];
int done;
};
int add_task(struct Task tasks[], int count, const char *title) {
tasks[count].id = count + 1;
strcpy(tasks[count].title, title);
tasks[count].done = 0;
return count + 1;
}
void list_tasks(struct Task tasks[], int count) {
for (int i = 0; i < count; i++) {
printf("%d %s %d\n", tasks[i].id, tasks[i].title, tasks[i].done);
}
}
int main(void) {
struct Task tasks[10];
int count = 0;
count = add_task(tasks, count, "Shopping");
count = add_task(tasks, count, "Sport");
list_tasks(tasks, count);
return 0;
}
Test yourself
-
What is used to list all tasks?
- A single printf
- A for loop over all tasks
- An if statement
- A switch
Show answer
A for loop over all tasks — A for loop walks all tasks from 0 to count.
-
Match listing concepts
- list_tasks
- listing function
- for
- loop
- count
- task count
- %d %s %d
- print format
-
Loop bound
for (int i = 0; i < ____; i++) { /* print task */ }
Show answer
for (int i = 0; i < count; i++) { /* print task */ }
Next lesson: Completing tasks