CodeBlanks Logo Icon CodeBlanks

Task model

Design the Task struct and array.

Project: To-do CLI

In this 5-lesson project you'll build a to-do list CLI app. Each lesson adds one piece, and by the final lesson you'll have a complete app.

You'll use:

  • struct Task for the task model
  • add_task, list_tasks, complete_task functions
  • an array holding tasks and a count counter
  • strcpy to copy titles

Ready? Let's start.

Task array

To handle many tasks we use an array of struct Task. A count variable tracks how many tasks have been added.

struct Task tasks[10];
int count = 0;
/* tasks[count] is the next free slot */

This structure lets us add, list and complete tasks. The array has a fixed size (10); count marks the used part.

Practice Create the first task and print it

Define struct Task with fields: int id, char title[50], int done. In main create a task with struct Task t = {1, "Shopping", 0};. Print the fields with printf("%d %s %d\n", t.id, t.title, t.done);. Output should be 1 Shopping 0.

Starter code

main.c
#include <stdio.h>
#include <string.h>

/* struct Task definition: id, title (50 chars), done fields */

int main(void) {
    /* create a task and print id, title, done fields */
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

1 Shopping 0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is struct Task defined?

  • int struct Task { };
  • Task { int id; char title[50]; int done; }
  • struct Task = (id, title, done)
  • struct Task { int id; char title[50]; int done; }; Correct answer

Explanation: The struct keyword, type name and braces with fields define a struct.

2 Field access

Question
struct Task t;
t.____ = 1;  /* task number */
Answer
struct Task t;
t.id = 1;  /* task number */

Explanation: A dot accesses a struct field.

3 Match struct concepts

Term Meaning
struct Task task structure
t.id id field
t.title title field
t.done status field

All lessons in Beginner