Declaring Variables and Translating Algorithms into Python and C

This is where it all comes together: you take an algorithm written in pseudocode and translate it into a real program. We will do every example in Python and C side by side, so you can see how each pseudocode statement becomes code.

Build on what you learned in Forms 1–3

These Lower School ICT posts cover the basics of this topic:

In this post:

  • Declaring variables and constants
  • A pseudocode-to-code translation table
  • Worked example 1: sequence (average of 3 scores)
  • Worked example 2: selection inside a WHILE loop (counting passes)

Declaring variables and constants

To declare a variable means to give it a name and (in many languages) a data type, so the computer sets aside memory for it.

  • In C you must declare each variable with its type before using it: int (integer), float (real), char (character), char name[20] (string), bool (Boolean, with #include <stdbool.h>). Constants can be made with #define PASS_MARK 50 or const int PASS_MARK = 50;.
  • In Python a variable is created when you first assign a value to it, and Python works out the type: age = 15 (int), price = 12.5 (float), name = "Kezia" (str), paid = True (bool). Constants are written in CAPITALS by convention: PASS_MARK = 50.

Python

# Declaring (creating) variables and a constant in Python
SCHOOL_NAME = "Island Secondary"   # constant (by convention, CAPITALS)
age = 15                            # integer
height = 1.62                       # real (float)
grade = 'A'                         # character (a string of length 1)
name = "Kezia"                      # string
is_prefect = True                   # Boolean
print(name, "is", age, "years old and got grade", grade)
print("Height:", height, "m  Prefect:", is_prefect, " School:", SCHOOL_NAME)

C

/* Declaring variables and a constant in C */
#include <stdio.h>
#include <stdbool.h>

#define SCHOOL_NAME "Island Secondary"   /* constant */

int main(void)
{
    int age = 15;              /* integer */
    float height = 1.62;       /* real */
    char grade = 'A';          /* character */
    char name[20] = "Kezia";   /* string (array of characters) */
    bool is_prefect = true;    /* Boolean (1 = true, 0 = false) */

    printf("%s is %d years old and got grade %c\n", name, age, grade);
    printf("Height: %.2f m  Prefect: %d  School: %s\n", height, is_prefect, SCHOOL_NAME);
    return 0;
}

Translation table

PseudocodePythonC
READ ageage = int(input())scanf(“%d”, &age);
READ priceprice = float(input())scanf(“%f”, &price);
PRINT “Total: “, totalprint(“Total:”, total)printf(“Total: %.2f\n”, total);
total ← 0total = 0total = 0;
IF x > 5 THEN … ELSE … ENDIFif x > 5:
    …
else:
    …
if (x > 5) { … } else { … }
FOR i ← 1 TO 10 DO … ENDFORfor i in range(1, 11):for (i = 1; i <= 10; i++) { … }
WHILE x <> -1 DO … ENDWHILEwhile x != -1:while (x != -1) { … }
a AND b, a OR b, NOT aa and b, a or b, not aa && b, a || b, !a
x MOD y, x DIV yx % y, x // yx % y, x / y (both integers)

Remember: Python uses indentation (spaces) to show which lines belong inside an IF or a loop; C uses curly braces { } and ends each statement with a semicolon.

Worked example 1: average of three scores (sequence)

Pseudocode

START
    READ score1, score2, score3
    average ← (score1 + score2 + score3) / 3
    PRINT "The average is ", average
STOP

Python

# Find the average of three test scores
score1 = float(input("Enter score 1: "))
score2 = float(input("Enter score 2: "))
score3 = float(input("Enter score 3: "))
average = (score1 + score2 + score3) / 3
print("The average is", format(average, ".2f"))

C

/* Find the average of three test scores */
#include <stdio.h>

int main(void)
{
    float score1, score2, score3, average;

    printf("Enter score 1: ");
    scanf("%f", &score1);
    printf("Enter score 2: ");
    scanf("%f", &score2);
    printf("Enter score 3: ");
    scanf("%f", &score3);

    average = (score1 + score2 + score3) / 3;
    printf("The average is %.2f\n", average);
    return 0;
}

Sample run: scores 60, 70 and 85 → The average is 71.67.

Worked example 2: counting passes (WHILE loop with selection)

Pseudocode

PASS_MARK ← 50
count ← 0
passed ← 0
READ mark
WHILE mark <> -1 DO
    count ← count + 1
    IF mark >= PASS_MARK THEN
        PRINT "Pass"
        passed ← passed + 1
    ELSE
        PRINT "Fail"
    ENDIF
    READ mark
ENDWHILE
PRINT passed, " out of ", count, " students passed"

Python

# Count how many students passed (mark of 50 or more).
# Enter -1 to stop.
PASS_MARK = 50
count = 0
passed = 0
mark = int(input("Enter mark (-1 to stop): "))
while mark != -1:
    count = count + 1
    if mark >= PASS_MARK:
        print("Pass")
        passed = passed + 1
    else:
        print("Fail")
    mark = int(input("Enter mark (-1 to stop): "))
print(passed, "out of", count, "students passed")

C

/* Count how many students passed (mark of 50 or more).
   Enter -1 to stop. */
#include <stdio.h>

#define PASS_MARK 50

int main(void)
{
    int mark, count = 0, passed = 0;

    printf("Enter mark (-1 to stop): ");
    scanf("%d", &mark);
    while (mark != -1)
    {
        count = count + 1;
        if (mark >= PASS_MARK)
        {
            printf("Pass\n");
            passed = passed + 1;
        }
        else
        {
            printf("Fail\n");
        }
        printf("Enter mark (-1 to stop): ");
        scanf("%d", &mark);
    }
    printf("%d out of %d students passed\n", passed, count);
    return 0;
}

Sample run with 72, 45, 50 then −1: Pass, Fail, Pass, then 2 out of 3 students passed. Notice that the mark of 50 (a boundary value) correctly gives “Pass”.

Try running these yourself. You can install Python (IDLE or Thonny) and a C compiler such as gcc or Code::Blocks, or use an online editor.

Try it: Pseudocode to code

Choose the correct Python or C statement for each pseudocode line.

READ age (Python)
PRINT total (C, total is an integer)
IF mark >= 50 THEN (Python)
WHILE n <> 0 DO (C)
FOR i ← 1 TO 5 DO (Python)
Declare a real variable called price (C)

Related

Related: Demo: Constants, Variables and Datatypes.; Python Example: Indefinite prompting to determine the corresponding grade for a given mark

Paper 1 practice (multiple choice)

Choose the best answer for each question. Try them all before you check.

1. Which C statement declares an integer variable called count?
(A) count int;
(B) int count;
(C) integer count
(D) declare count

2. In Python, which statement reads a whole number from the user?
(A) num = input(int)
(B) num = int(input())
(C) scanf(num)
(D) READ num

3. The pseudocode operator <> is written in Python and C as
(A) =
(B) ==
(C) !=
(D) <>

4. Which C data type is used for a real number such as 12.75?
(A) int
(B) char
(C) float
(D) bool

5. In Python, the lines inside an if statement are shown by
(A) curly braces
(B) semicolons
(C) indentation
(D) ENDIF

Show answers

1. B
2. B
3. C
4. C
5. C

Paper 2 practice (structured question)

The following pseudocode finds the total cost of tickets for a school concert:

READ num_tickets
cost ← num_tickets * 40
IF num_tickets >= 10 THEN
    cost ← cost - 50
ENDIF
PRINT cost

(a) Write a declaration, in a high-level language of your choice, for:

(i) the variable num_tickets (1 mark)

(ii) the variable cost (1 mark)

(b) Explain why the ticket price of $40 could be declared as a constant. (1 mark)

(c) Translate the pseudocode into a high-level language of your choice. (5 marks)

(d) State the output when num_tickets is 12. (2 marks)

Total: 10 marks

Show answers

(a)

(i) Int num_tickets; (in C) or num_tickets = 0 (in Python) (1 mark)

(ii) Int cost; or float cost; (in C) or cost = 0 (in Python) (1 mark)

(b) The price does not change while the program runs, so storing it as a constant makes the program easier to read and update (1 mark).

(c)
• Reading num_tickets correctly, e.g. num_tickets = int(input()) or scanf("%d", &num_tickets); (1 mark)
• cost = num_tickets * 40 (1 mark)
• if num_tickets >= 10 with correct syntax (1 mark)
• cost = cost - 50 inside the if (1 mark)
• print(cost) or printf("%d", cost); (1 mark)

(d) 12 × 40 = 480 (1 mark); 480 − 50 = 430, so 430 is printed (1 mark).

Next: Program Documentation: Internal and External Documentation

Syllabus link: This post is relevant to the CSEC® Information Technology Syllabus (CXC 30/G/SYLL 17), Section 8: Program Implementation, Specific Objectives 4 and 5 (“declare variables and constants using elementary data types” and “translate algorithmic statements into high-level language syntax”).

Attributions to media used in this post:

No third-party images are used in this post. Embedded videos are credited on YouTube to their channels.

Updates

2026/10/16

– Syntax highlighting added to code examples.

© 2026 Vedesh Kungebeharry. All rights reserved.

Variables, Constants and Data Types: Integer, Real, Character, String and Boolean

Every program stores data while it runs – a student’s name, a price, the number of goals scored. In this post you will learn the difference between a variable and a constant, and the five data types you need for CSEC: integer, real (floating point), character, string and Boolean.

Build on what you learned in Forms 1–3

These Lower School ICT posts cover the basics of this topic:

In this post:

  • What is a variable?
  • What is a constant?
  • Naming variables (identifiers)
  • Data types with examples

Variables

A variable is a named area of storage (in memory) whose value can change while the program is running. Think of it like a labelled box: the label is the name (for example score) and you can take out the old value and put in a new one at any time.

Example: in a cricket scoring program, runs starts at 0 and changes every time the batsman scores.

Constants

A constant is a named value that never changes while the program is running. Examples: the VAT rate (12.5% in Trinidad and Tobago), the number of days in a week (7), the pass mark (50), or π (3.14159).

Why use a constant instead of just typing the number? If the VAT rate changes, you only change it in one place, and a name like VAT_RATE is easier to understand than 0.125.

Naming variables (identifiers)

  • Use meaningful names: total_price is better than tp or x.
  • Start with a letter; no spaces (use an underscore instead, e.g. first_name).
  • Do not use words that the language already uses, such as if or while.
  • Many programmers write constants in CAPITALS, e.g. PASS_MARK.

Data types

The data type tells the computer what kind of value a variable will hold, and therefore what can be done with it.

Data typeWhat it storesExamples
IntegerWhole numbers (positive, negative or zero), no decimal point15 (age), −3, 0, 2026
Real (floating point)Numbers with a decimal (fractional) part12.50 (price), 1.62 (height), −0.5
CharacterA single letter, digit or symbol‘A’ (grade), ‘M’, ‘$’
StringA group (sequence) of characters, such as words or text“Kezia Ramdial”, “Port of Spain”, “868-555-1234”
BooleanOnly one of two values: TRUE or FALSEis_prefect = TRUE, has_paid = FALSE

Note: a telephone number such as 868-555-1234 is stored as a string, because you never do arithmetic with it and it contains dashes.

Shows how programs store values in variables and assign new values to them.

Video: Programming Basics: Statements & Functions: Crash Course Computer Science #12 – https://www.youtube.com/watch?v=l26oaHV7D40

A quick look in code

Here is how the five data types and a constant look in Python and C. (You will learn more about declaring variables in Section 8.)

Python

# Declaring (creating) variables and a constant in Python
SCHOOL_NAME = "Island Secondary"   # constant (by convention, CAPITALS)
age = 15                            # integer
height = 1.62                       # real (float)
grade = 'A'                         # character (a string of length 1)
name = "Kezia"                      # string
is_prefect = True                   # Boolean
print(name, "is", age, "years old and got grade", grade)
print("Height:", height, "m  Prefect:", is_prefect, " School:", SCHOOL_NAME)

C

/* Declaring variables and a constant in C */
#include <stdio.h>
#include <stdbool.h>

#define SCHOOL_NAME "Island Secondary"   /* constant */

int main(void)
{
    int age = 15;              /* integer */
    float height = 1.62;       /* real */
    char grade = 'A';          /* character */
    char name[20] = "Kezia";   /* string (array of characters) */
    bool is_prefect = true;    /* Boolean (1 = true, 0 = false) */

    printf("%s is %d years old and got grade %c\n", name, age, grade);
    printf("Height: %.2f m  Prefect: %d  School: %s\n", height, is_prefect, SCHOOL_NAME);
    return 0;
}

Sample output (Python): Kezia is 15 years old and got grade A / Height: 1.62 m Prefect: True School: Island Secondary. In C, the Boolean prints as 1 for true.

Try it: Choose the best data type

Choose the most suitable data type for each item.

The number of students in a class
The price of a bake and shark
A student’s grade, e.g. B
A customer’s name
Whether a fee has been paid (yes/no)
A WhatsApp phone number such as 1-876-555-0100
The temperature in °C, e.g. 31.5

Related

Related: Demo: Constants, Variables and Datatypes.

Paper 1 practice (multiple choice)

Choose the best answer for each question. Try them all before you check.

1. A storage location whose value can change while a program runs is called a
(A) constant
(B) variable
(C) data type
(D) compiler

2. Which data type is BEST for storing the price $45.99?
(A) Integer
(B) Character
(C) Real
(D) Boolean

3. Which value is a Boolean?
(A) “Yes please”
(B) TRUE
(C) 25
(D) ‘Y’

4. Which is the BEST example of a constant?
(A) A student’s age
(B) The number of days in a week
(C) The balance in a bank account
(D) The time of day

5. “Montego Bay” would be stored as a
(A) character
(B) integer
(C) string
(D) real

Show answers

1. B
2. C
3. B
4. B
5. C

Paper 2 practice (structured question)

A program is being written for a car rental company in Bridgetown. It stores the customer’s name, the number of days the car is rented, the daily rate of $95.50, whether the customer has insurance, and the car category (A, B or C).

(a) Distinguish between a variable and a constant. (2 marks)

(b) Identify the most suitable data type for EACH of the following:

(i) the customer’s name (1 mark)

(ii) the number of days rented (1 mark)

(iii) whether the customer has insurance (1 mark)

(iv) the car category (1 mark)

(c) The daily rate is the same for every customer. State whether it should be stored as a variable or a constant, and give ONE reason. (2 marks)

Total: 8 marks

Show answers

(a) A variable is a named storage location whose value can change during processing (1 mark); a constant’s value never changes during processing (1 mark).

(b)

(i) String (1 mark)

(ii) Integer (1 mark)

(iii) Boolean (1 mark)

(iv) Character (1 mark)

(c) Constant (1 mark); its value does not change while the program runs / it only needs to be changed in one place if the rate changes (1 mark).

Next: What Is an Algorithm? Definition and Characteristics of a Good Algorithm

Syllabus link: This post is relevant to the CSEC® Information Technology Syllabus (CXC 30/G/SYLL 17), Section 7: Problem-Solving and Program Design, Specific Objective 4 (“distinguish between variables and constants”).

Attributions to media used in this post:

No third-party images are used in this post. Embedded videos are credited on YouTube to their channels.

Updates

2026/10/16

– Syntax highlighting added to code examples.

© 2026 Vedesh Kungebeharry. All rights reserved.

Introduction to Algebra: Variables, Constants, Expressions and Substitution

Algebra is a way of doing maths with letters that stand for numbers. It lets us write rules that work for any number, solve puzzles where a number is unknown, and describe patterns in science, business and computing. The big idea is simple: a letter such as n is just a number we either do not know yet or that can change. In this lesson you will learn the language of algebra – variables, constants, terms and expressions – how to turn words into algebra, and how to substitute numbers into an expression.

Varying quantities, variables and constants

Many quantities in everyday life vary (change): the temperature during the day, the price of a taxi ride as the distance increases, your height as you grow, the credit left on a phone as you use it. Other quantities stay the same: there are always 7 days in a week and 60 minutes in an hour.

  • A variable is a quantity that can change or is unknown. We represent it with a letter: t for temperature, d for distance, n for “a number”.
  • A constant is a quantity that does not change. In the expression 5 + 3k, the number 5 is a constant and k is a variable.
  • Any letter can be used, but choosing a letter that reminds you of the quantity (h for height, c for cost) makes the algebra easier to read. A letter always stands for a number – a means “the number of apples”, not “apples”.

How algebra is written

In arithmetic languageIn algebraNote
3 × n3nLeave out the × sign and write the number first.
a × babLetters are usually written in alphabetical order.
1 × xxWe do not write the 1.
y × yy2“y squared”.
n ÷ 4n4 or n/4Division is usually written as a fraction.

Terms, expressions and equations

  • A term is a single number, a single letter, or numbers and letters multiplied (or divided) together: 7, x, 5y, 3ab, p2.
  • The number in front of a letter is its coefficient: in 5y the coefficient is 5.
  • An expression is one or more terms joined by + or − signs: 4a − 2b + 7 is an expression with three terms. The sign in front of a term belongs to that term.
  • An equation contains an equals sign: 3x + 5 = 11. An expression has no equals sign. (You will solve equations in Term 3.)

Turning words into expressions

WordsExpression
5 more than nn + 5
5 less than nn − 5 (not 5 − n!)
n subtracted from 2020 − n
twice n / double n2n
the product of a and bab
n shared equally among 4n4
3 times the sum of x and 23(x + 2)
the square of yy2

Tip: “more than” and “less than” describe what happens to n. “5 less than n” starts with n and takes 5 away. Test it with a number: 5 less than 12 is 7, and 12 − 5 = 7 ✔

Substitution

To substitute means to replace each letter with a given number and then work out the value. Put the number in brackets if it helps, and follow the order of operations: Brackets, Orders (powers), Division and Multiplication, Addition and Subtraction (BODMAS, also called BIDMAS or PEMDAS).

Worked examples

Example 1: Substituting into expressions

Question: If a = 3, b = 5 and c = 2, find the value of
(a) 4a + b
(b) 2ab
(c) 5b − 3c
(d) a(b + c)
(e) a + bc
(f) a2 + b

  1. (a) 4a + b = 4 × 3 + 5 = 12 + 5 = 17
  2. (b) 2ab = 2 × 3 × 5 = 30
  3. (c) 5b − 3c = 5 × 5 − 3 × 2 = 25 − 6 = 19
  4. (d) a(b + c) = 3 × (5 + 2) = 3 × 7 = 21 (brackets first)
  5. (e) (a + b) ÷ c = (3 + 5) ÷ 2 = 8 ÷ 2 = 4 (the fraction line acts like brackets)
  6. (f) a2 + b = 3 × 3 + 5 = 9 + 5 = 14

Answer: 17, 30, 19, 21, 4, 14.

Example 2: An expression from a real situation

Question: A taxi charges a $5 pick-up fee plus $3 for every kilometre. Write an expression for the fare for k km, and find the fare for a 7 km ride.

  1. Cost of the kilometres: 3 × k = 3k dollars. Add the fixed fee: 5 + 3k.
  2. Here 5 is a constant and k is the variable.
  3. Substitute k = 7: 5 + 3 × 7 = 5 + 21 = 26.

Answer: Fare = $(5 + 3k); a 7 km ride costs $26.

Example 3: Writing an expression

Question: Phone credit starts at $100 and $15 is used each week. Write an expression for the credit left after k weeks. How much is left after 4 weeks?

  1. Credit used after k weeks: 15k. Credit left: 100 − 15k.
  2. Substitute k = 4: 100 − 15 × 4 = 100 − 60 = 40.

Answer: 100 − 15k dollars; $40 after 4 weeks.

Common mistakes

  • Treating 3a as a two-digit number. If a = 4, then 3a = 3 × 4 = 12, not 34.
  • Reversing “less than”. “7 less than y” is y − 7, not 7 − y.
  • Ignoring the order of operations. With b = 5 and c = 2, 5b − 3c = 25 − 6 = 19. Working left to right without care gives wrong answers.
  • Calling an equation an expression. If there is an = sign, it is an equation.
  • Thinking a letter is an object. In 3a + 2b, the letters stand for numbers (such as the cost of an apple), not for “apples” and “bananas”.

Practice questions

Try these yourself first, then open each answer to check your working.

1. Constant or variable?
(a) the number of hours in a day
(b) your height
(c) the price of a litre of gasoline

Show answer

(a) Constant (always 24).
(b) Variable.
(c) Variable (prices change).

2. Write as expressions:
(a) 7 less than y
(b) the sum of p and q, divided by 2
(c) 4 times m, plus 9

Show answer

(a) y − 7
(b) p + q2
(c) 4m + 9

3. (a) Is 3x + 5 = 11 an expression or an equation?
(b) How many terms are in 4a − 2b + 7?
(c) What is the coefficient of b in 4a − 2b + 7?

Show answer

(a) An equation (it has an = sign).
(b) Three terms: 4a, −2b and 7.
(c) −2 (the sign belongs to the term; you will meet negative numbers properly in Term 2).

4. If x = 6 and y = 2, find
(a) 3x − 4y
(b) xy3
(c) 2(x + y)
(d) x2 − y2

Show answer

(a) 18 − 8 = 10
(b) 12 ÷ 3 = 4
(c) 2 × 8 = 16
(d) 36 − 4 = 32

5. Pens cost $p each and a notebook costs $12. Write an expression for the cost of 6 pens and one notebook. Find the cost when p = 4.

Show answer

6p + 12. When p = 4: 24 + 12 = $36.

6. A rectangle has length l and width w. Write an expression for its perimeter and find it when l = 9 cm and w = 4 cm.

Show answer

2l + 2w (or 2(l + w)). 18 + 8 = 26 cm.

7. Ana is n years old. Her brother is 3 years older than she is, and her grandmother is five times her age. Write expressions for their ages, then find them when n = 12.

Show answer

Brother: n + 3 = 15. Grandmother: 5n = 60.

Quick check

1. What is a variable?

Show answer

A quantity that can change or is unknown, represented by a letter.

2. What is the difference between an expression and an equation?

Show answer

An equation has an equals sign; an expression does not.

3. Write “n divided by 5” in algebra.

Show answer

n5 (or n/5).

4. If t = 10, what is 4t?

Show answer

40.

Next: Simplifying Algebraic Expressions: Like Terms and the Distributive Law

Curriculum link: This post is relevant to the Trinidad and Tobago National Lower Secondary (NCSE) Mathematics Curriculum – Form 1, Term 1, Strand 1.6 Algebra, Topic 1.6.1 Introducing Algebra – Learning Outcomes 1.6.1.1 (investigating varying quantities), 1.6.1.2 (constants and variables), 1.6.1.3 (using symbols for unknown quantities), 1.6.1.4 (translating word statements into expressions), 1.6.1.5 (identifying an expression) and 1.6.1.6 (substituting whole numbers for variables).

Updates

2026/10/25

– Put each lettered part of the questions and answers on its own line.

© 2026 Vedesh Kungebeharry. All rights reserved.

Variables and Format Specifiers: Printing Values with %d

In the previous lesson you created two variables, x and y, and the compiler warned that you never used them. In this lesson you put them to work. You add them together, print the answer, and then make a mistake that the compiler cannot catch for you.

In this lesson you will

  • Declare, assign and initialise int variables
  • Print the value of a variable with the format specifier %d
  • See how printf matches placeholders to values, in order
  • Meet your first logical error: a program that builds and runs, but gives the wrong answer

Try it: store and add two numbers

Start from your program from the previous lesson. Below y = 6;, add a third variable that holds the sum, and change the message so that it prints the sum:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 5;
    int y;
    y = 6;
    int sum = x + y;
    printf("The sum is %d\n", sum);
    return 0;
}
The sum is 11

The warnings from the previous lesson have gone, because every variable is now used. Notice that you cannot simply write the word sum inside the quotes. That would print the letters s-u-m. Instead, you leave a placeholder, %d, where the number should go, and pass sum after a comma.

Now change one thing. Make the message more informative by printing all three numbers. Before you build, think about which value lands in which %d:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 5;
    int y;
    y = 6;
    int sum = x + y;
    printf("The sum of %d and %d is %d\n", sum, x, y);
    return 0;
}

Break it on purpose: put the values in the wrong order

Build and run the program above. Observe:

The sum of 11 and 5 is 6

There are no errors and no warnings, and the program ran. But 11 plus 5 is not 6! Before reading on, look at the line of code and work out why the computer printed exactly this.

Now fix it so that the values are listed in the same order as the sentence: x, then y, then sum.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 5;
    int y;
    y = 6;
    int sum = x + y;
    printf("The sum of %d and %d is %d\n", x, y, sum);
    return 0;
}
The sum of 5 and 6 is 11

What just happened

printf fills its placeholders strictly from left to right. The first %d gets the first value after the string, the second %d gets the second value, and so on. It has no idea what your sentence means. In the broken version the first value was sum (11), so the sentence began “The sum of 11”. The computer did exactly what it was told.

This kind of mistake is called a logical error. The code follows every rule of C, so it builds and runs, but it does not do what you intended. Compare it with the syntax errors from the previous lesson, which the compiler refuses to build. Logical errors are found by testing: work out the answer you expect (5 + 6 = 11) and check that the program agrees.

Break it on purpose: forget a comma

In the fixed program, delete the comma between x and y so that the line ends x y, sum);. Build it:

main.c:10:45: error: expected ')' before 'y'

This time it is a syntax error, and the build fails. A printf call is a string literal followed by a comma-separated list of values, and every value needs its comma. Put the comma back and build again.

Name it: declaring, assigning and initialising

Your program now uses three slightly different ways to create and fill a variable. Each one has a name:

  • int y; is a declaration. It tells the compiler the variable’s type (int, a whole number) and its identifier (its name, y). No value is given yet.
  • y = 6; is an assignment. It stores a value in a variable that already exists.
  • int x = 5; is a declaration with initialisation. It creates the variable and gives it a first value in one statement.
  • int sum = x + y; also initialises, using the result of a calculation.

A format specifier such as %d tells printf two things: where a value goes in the text, and how to display it. %d means “display an int as a decimal (base-10) whole number”. Other types need other specifiers, which is the subject of the next lesson.

Your turn: start a reference table. Search for the common printf format specifiers and start a table with three columns: data type, specifier, example. Add int → %d now, and keep adding rows as the series goes on.

Key terms

  • Variable: a named storage location in memory that holds a value of a particular type.
  • Declaration: introduces a variable’s type and identifier, e.g. int y;
  • Assignment: stores a value in an existing variable, e.g. y = 6;
  • Initialisation: gives a variable its first value when it is declared, e.g. int x = 5;
  • Format specifier: a placeholder such as %d that marks where, and how, a value is printed.
  • Logical error: the program builds and runs but produces the wrong result.

Quick check

  1. What does printf("%d minus %d\n", y, x); print when x is 5 and y is 6?

    Show answer

    6 minus 5. The first %d takes the first value listed (y).

  2. Is “The sum of 11 and 5 is 6” caused by a syntax error or a logical error? How would you notice it?

    Show answer

    A logical error. The program builds and runs. You notice it by testing: compare the output with the answer you worked out yourself.

  3. Which line is a declaration with initialisation: int a;, a = 3; or int b = 3;?

    Show answer

    int b = 3;. It declares b and gives it a first value in the same statement.

  4. What happens if a printf has three %d placeholders but only two values after the string?

    Show answer

    GCC warns format '%d' expects a matching 'int' argument. If you run it anyway, the third number printed is meaningless. Always match each placeholder to one value.

Optional: a recorded demonstration of these steps starts around 33:00.

Part of the Introduction to C series. Next: int vs float: Truncation, Binary, and Choosing the Right Specifier