CodeBlanks Logo Icon CodeBlanks

Your first program

Learn to write your first C++ program with main, #include and iostream.

Your first program

The entry point of every C++ program is the main function. When the program starts, main is called and runs until return 0;.

To write a program you first include the standard I/O library with #include <iostream>. std::cout prints text to the screen; std::endl ends the line and moves the cursor to the next line.

From the command line you compile with g++ hello.cpp -o hello and run with ./hello. C++ source files usually use the .cpp extension.

What is #include?

#include is a preprocessor directive: before compiling, the compiler pastes the named header file into your source. <iostream> provides std::cout and std::cin for input and output.

Header names go inside <...> and are not followed by a semicolon. Standard library headers do not use a .h extension; for your own headers you write #include "mine.hpp" with quotes.

A program can have several #include lines; each one must be on its own line.

Practice Write your first program

Complete the skeleton below. Inside main, use std::cout to print Hello World and end the line with std::endl.

Starter code

main.cpp
#include <iostream>

int main() {
    // Print the message
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    // Print the message
    std::cout << "Hello World" << std::endl;
    return 0;
}

Expected output

Hello World

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the entry point of a C++ program?

  • the start function
  • the main function Correct answer
  • the run function
  • the init function

Explanation: The main function is the entry point of a C++ program.

2 The #include line

Question
#include <____> to include the input/output library.
Answer
#include <iostream> to include the input/output library.

Explanation: iostream provides std::cout and std::cin.

3 Match the program parts

Term Meaning
int main() Entry point
return 0; Successful exit
std::cout Output writing
#include Library inclusion

All lessons in Beginner