Skip to content
My Compiler
LoginRegister

Code Examples

Short, runnable examples for the basics. Choose a language and open any example in the compiler.

  1. Hello, World!

    Every language starts here: print a message to the screen to check that everything works.

    #include <iostream>
    
    int main() {
        std::cout << "Hello, World!" << std::endl;
        return 0;
    }
    Open in compiler
  2. Variables

    Variables store values such as text, whole numbers and decimals so you can reuse them.

    #include <iostream>
    #include <string>
    
    int main() {
        std::string name = "Ada";
        int age = 21;
        double height = 1.75;
        std::cout << name << " " << age << " " << height << std::endl;
        return 0;
    }
    Open in compiler
  3. Conditions

    if / else lets your program choose a path depending on a value.

    #include <iostream>
    
    int main() {
        int age = 18;
        if (age >= 18) {
            std::cout << "Adult" << std::endl;
        } else if (age >= 13) {
            std::cout << "Teenager" << std::endl;
        } else {
            std::cout << "Child" << std::endl;
        }
        return 0;
    }
    Open in compiler
  4. Loops

    Loops repeat a block of code: use for when you know the count and while when you wait for a condition.

    #include <iostream>
    
    int main() {
        for (int i = 1; i <= 5; i++) {
            std::cout << i << std::endl;
        }
        int n = 3;
        while (n > 0) {
            std::cout << "Countdown " << n-- << std::endl;
        }
        return 0;
    }
    Open in compiler
  5. Functions

    A function packs code into a reusable block that takes inputs and returns a result.

    #include <iostream>
    
    int add(int a, int b) {
        return a + b;
    }
    
    int main() {
        std::cout << add(2, 3) << std::endl;
        return 0;
    }
    Open in compiler
  6. Fibonacci sequence

    Each number is the sum of the two before it. A classic exercise that combines variables, loops and arithmetic.

    #include <iostream>
    
    int main() {
        int a = 0, b = 1;
        for (int i = 0; i < 10; i++) {
            std::cout << a << " ";
            int next = a + b;
            a = b;
            b = next;
        }
        return 0;
    }
    Open in compiler
Code Examples | My Compiler