Lesson 1 of 10
Your first program
- 10 min
- 5 checks
- 3 hints
- Go to task
Goal
The main function, printing with cout, and a function that returns a value
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.
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- square(7) returns 49
- square works with zero and negative numbers
- The first line is Hello from C++
- The second line is 7 squared = 49
- Exactly two lines