Lesson 1 of 10

Your first program

Goal

The main function, printing with cout, and a function that returns a value

01

Explanation

A C++ program starts running from a single function called main, and everything before it is setup: #include <iostream> brings in the input and output tools, and using namespace std; saves you from writing std:: in front of each of their names.

You print with cout and the << operator: put each piece of text or number you want to print after a <<, one after another, and endl moves you to a new line. Every statement in C++ ends with a semicolon.

C++ is a compiled language, which means the compiler turns all of your code into a program before a single line of it runs. One typo stops everything, and the compiler tells you the number of the line with the mistake. You write the type of the value a function returns before its name, so int square(int n) takes a whole number and returns a whole number.

02

Your task

Complete square(n) so it returns n squared, then print two lines from main: Hello from C++ and then 7 squared = 49, where the 49 comes from square(7) instead of being typed by hand. Then press “Run and check” to see the result.

Checks

5 checks
  1. square(7) returns 49
  2. square works with zero and negative numbers
  3. The first line is Hello from C++
  4. The second line is 7 squared = 49
  5. Exactly two lines
03

Hints

0/3
Track lessons0 of 10 done

C++ is the language behind game engines, browsers and operating systems, because it's fast and gives you full control.

Beginner level, 10 lessons, 2 hours in total.

main.cpp
OutputC++17 (GCC 9, Judge0)

Compiling and running your code on the server.

–/5

Compiling and running your code on the server.

5 checks listed under “Your task”.

Track lessons0 of 10 done

C++ is the language behind game engines, browsers and operating systems, because it's fast and gives you full control.

Beginner level, 10 lessons, 2 hours in total.