Lesson 11 +10 XP

Statements and Program Structure

Statements and Program Structure

Everything a C program shows you is a sequence of statements strung together. Let's see how they stack up.

What is a statement?

A statement is the smallest unit of work in a program: a single instruction. In C a statement ends with a semicolon.

int x;          // a declaration (creates a variable)
x = 5;          // an assignment (stores a value)
printf("%d", x); // an output statement
  • int x; declares a variable.
  • x = 5; stores the value 5 in it.
  • printf("%d", x); sends the value to the console.

Three statements, three tasks. Each one is a complete instruction.

A program is a list of statements

When main runs, it sweeps through its statements top to bottom. Order matters:

#include <stdio.h>

int main() {
    printf("First!\n");
    printf("Second!\n");
    return 0;
}

The console prints "First!" before "Second!", exactly because the statements run in order.

Structure: functions group statements

A function is a named bundle of statements. main is the function that's automatically called first. Real programs then create other functions to bundle repeating tasks.

Blocks

{ } - a block groups one or more statements into a unit. It tells the compiler "these lines belong together".

TL;DR

  • A statement is a single instruction, usually ending with ;.
  • A program is basically a list of statements run in order.
  • main is the starter function; other functions group tasks.
  • { } blocks bundle statements together.