Values and variables

Print things, and give values names so you can use them again.

Your C code runs inside your browser tab. Nothing to install.

Printing a value

A program is a list of instructions that run from top to bottom.

A C program starts at a function called main. The first line brings in printf, which prints. \n inside the quotes ends the line, and each statement ends with a semicolon.

Load the example and press Run. The first run downloads the compiler, about 100 MB, and can take a minute. Your browser keeps it for next time.

Example
#include <stdio.h>

int main(void) {
    printf("Hello\n");
    printf("%d\n", 42);
    return 0;
}

Naming a value

A variable is a name for a value.

In C you say what kind of value a variable holds: int for a whole number. Text is held in a char array. To print a variable, printf needs a placeholder: %d for a whole number and %s for text.

After that, the name can be used wherever the value is needed.

Example
#include <stdio.h>

int main(void) {
    char name[] = "Asha";
    int marks = 82;
    printf("%s\n", name);
    printf("%d\n", marks + 5);
    return 0;
}

Your turn: a variable

Create a variable and print it.

Practice task

Create a variable called `city` holding the text Pune, then print it.

Your answer is run and checked in the lesson. Try it now.

Working with numbers

Numbers can be added with +, subtracted with -, multiplied with * and divided with /.

Dividing one int by another gives a whole number and drops the remainder.

Multiplying and dividing happen before adding and subtracting. Use brackets to change the order.

Example
#include <stdio.h>

int main(void) {
    int price = 250;
    int quantity = 3;
    int total = price * quantity;
    printf("%d\n", total);
    printf("%d\n", (total + 50) / 2);
    return 0;
}

Your turn: a calculation

Three subjects were marked 82, 67 and 91.

Practice task

Store the three marks 82, 67 and 91 in variables, then print their average: the sum divided by 3.

Your answer is run and checked in the lesson. Try it now.