Adding tasks
- C course
- Beginner
- Lesson 84/116
- 6 min
Learn to add tasks with the AddTask function.
The add_task function
To add a task to the array we write the add_task function. It places the new task at index tasks[count] and returns count + 1.
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;
}strcpy copies the title into the array; done = 0 marks the task as pending. The returned value is the new count.
The count counter
The count variable holds how many tasks are in the array. Each add_task call returns the new value count + 1. This way the next add lands in the right slot.
int count = 0;
count = add_task(tasks, count, "Shopping"); /* count = 1 */
count = add_task(tasks, count, "Sport"); /* count = 2 */Each add raises count by one. This pattern mimics dynamic growth in a fixed-size array.
Practice Add the add_task function
Above the existing code add the int add_task(struct Task tasks[], int count, const char *title) function. Inside it write tasks[count].id = count + 1;, strcpy(tasks[count].title, title); and tasks[count].done = 0;, then return count + 1;. In main define struct Task tasks[10]; int count = 0;, add two tasks and print both. Output should be 1 Shopping 0 and 2 Sport 0.
Starter code
#include <stdio.h>
#include <string.h>
struct Task {
int id;
char title[50];
int done;
};
int main(void) {
struct Task t = {1, "Shopping", 0};
printf("%d %s %d\n", t.id, t.title, t.done);
return 0;
}Sample 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;
}
int main(void) {
struct Task tasks[10];
int count = 0;
count = add_task(tasks, count, "Shopping");
count = add_task(tasks, count, "Sport");
printf("%d %s %d\n", tasks[0].id, tasks[0].title, tasks[0].done);
printf("%d %s %d\n", tasks[1].id, tasks[1].title, tasks[1].done);
return 0;
}Expected output
1 Shopping 0 2 Sport 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Next id
struct Task t;
t.id = ____; /* next id */
struct Task t;
t.id = count + 1; /* next id */
Explanation: Each new task gets id count + 1.
2 When adding a new task to an array, what should we do?
- Put the new struct at index count and increment count Correct answer
- Only increment count
- Redefine the array
- Nothing
Explanation: The new task goes to tasks[count] and count is incremented.
3 Match add concepts
| Term | Meaning |
|---|---|
add_task |
task add function |
tasks[count] |
new task slot |
count + 1 |
new count |
strcpy |
string copy |