C
Adding tasks
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.
Exercise 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.
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;
}
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;
}
Test yourself
-
Next id
struct Task t;
t.id = ____; /* next id */
Show answer
struct Task t;
t.id = count + 1; /* next id */
-
When adding a new task to an array, what should we do?
- Put the new struct at index count and increment count
- Only increment count
- Redefine the array
- Nothing
Show answer
Put the new struct at index count and increment count — The new task goes to tasks[count] and count is incremented.
-
Match add concepts
- add_task
- task add function
- tasks[count]
- new task slot
- count + 1
- new count
- strcpy
- string copy
Next lesson: Listing tasks