Lab 2 · Explore: C in a notebook¶

Introduction to Computer Science (YMT113) · Fall 2026

This notebook is the playground half of Lab 2 (and a preview for week 3). Nothing here is graded. It shows that you can write, compile and run C inside a Jupyter notebook: a cell starting with %%writefile hello.c saves the cell as a file, and a cell starting with ! runs a terminal command.

Where to run it: in Google Colab (the Open in Colab button on the lab page; gcc is preinstalled) or in your codespace (pick the Python kernel).

1 · hello, world¶

%%writefile hello.c
#include <stdio.h>

int main(void)
{
    printf("hello, world\n");
}
Writing hello.c
!gcc -o hello hello.c && ./hello
hello, world

Two commands joined by &&: compile (gcc -o hello hello.c), and if that worked, run (./hello). Try removing the semicolon and running both cells again: read the error the compiler gives you.

2 · Types and printf¶

Change the values, run again. What happens if you print an int with %f?

%%writefile types.c
#include <stdio.h>

int main(void)
{
    int age = 19;
    float gpa = 3.75;
    char initial = 'F';
    printf("age %i, gpa %.2f, initial %c\n", age, gpa, initial);
    printf("an int takes %zu bytes, a float %zu, a char %zu, a double %zu\n",
           sizeof(int), sizeof(float), sizeof(char), sizeof(double));
}
Writing types.c
!gcc -o types types.c && ./types
age 19, gpa 3.75, initial F
an int takes 4 bytes, a float 4, a char 1, a double 8

3 · A byte as bits (the Part C program, explained)¶

(n >> i) & 1 shifts the number right by i places and keeps only the last bit. Watch it work for one number:

%%writefile bits.c
#include <stdio.h>

int main(void)
{
    int n = 73;
    for (int i = 7; i >= 0; i--)
    {
        int bit = (n >> i) & 1;
        printf("i=%i  n>>i=%3i  bit=%i\n", i, n >> i, bit);
    }
}
Writing bits.c
!gcc -o bits bits.c && ./bits
i=7  n>>i=  0  bit=0
i=6  n>>i=  1  bit=1
i=5  n>>i=  2  bit=0
i=4  n>>i=  4  bit=0
i=3  n>>i=  9  bit=1
i=2  n>>i= 18  bit=0
i=1  n>>i= 36  bit=0
i=0  n>>i= 73  bit=1

4 · Integer overflow, on purpose¶

An int has 32 bits. What happens one past the largest value? (We meet this properly in week 3.)

%%writefile overflow.c
#include <stdio.h>
#include <limits.h>

int main(void)
{
    int big = INT_MAX;
    printf("largest int : %i\n", big);
    big = big + 1;
    printf("plus one    : %i\n", big);
    unsigned char byte = 255;
    byte = byte + 1;
    printf("255 + 1 in one byte: %i\n", byte);
}
Writing overflow.c
!gcc -Wno-overflow -o overflow overflow.c && ./overflow
largest int : 2147483647
plus one    : -2147483648
255 + 1 in one byte: 0

The bits wrap around, like an odometer. This exact behavior grounded the Boeing 787 (week 3's wow moment).

5 · Your turn¶

Copy any cell, change the program, run it. Ideas: print your name and age; print 5 / 2 and 5.0 / 2; count from 1 to 10 with a for loop.