Step 1
Hello, robot
Compile and run your first C++ program, print to the console and store values in variables.
Your first program
C++ is compiled: when you press Run (or ⌘/Ctrl + Enter), a compiler first checks your whole program and turns it into machine code, and only then does it run. Here's a complete program:
#include <iostream>
int main() {
std::cout << "Hello, robot!" << "\n";
}
#include <iostream>brings in the part of the standard library that prints text.- Every program starts at
main. Its instructions go between the curly braces{ }and run from top to bottom. std::coutis the console.<<sends a value to it, and you can chain as many as you like."\n"starts a new line.- Each instruction ends with a semicolon
;. Forget one and the compiler stops with an error that names the line.
Text in double quotes is a string. Numbers don't need quotes.
Variables
A variable is a named value, and in C++ every variable has a type, written before its name:
int joints = 4; // a whole number
double speed = 0.5; // a number with a decimal point
std::string color = "red"; // text (needs #include <string>)
From then on, use the name wherever you'd use the value. You can store a new value later (speed = 0.8;), but the variable keeps its type: joints = 4.7; quietly stores 4, because an int has no room for decimals. Anything after // is a comment, which the compiler ignores.
std::cout doesn't add spaces between values, so put them in the text yourself:
std::cout << "The " << color << " ball" << "\n"; // The red ball
Your task
- Give the robot arm a name: store a string in a
std::stringvariable calledname. - The arm has four joints. Store the number
4in anintvariable calledjoints. - Print a sentence like
Rex has 4 joints, using both variables.