Loading lessons...
Project 1: Hello World Builder
Project 1: Hello World Builder
Time to build your first real program. You already know the pieces - #include, int main(), cout, and comments - so practice connecting them into one working, compile-able file.
The goal
Write a C++ program that prints a hello message, then prints your name and your age on separate lines.
What you practice
- Writing the
#includepreprocessor directive - Setting up
int main() - Printing with
coutand the stream operator<< - Leaving comments your future self can read
Starter code
Start from this real program:
#include <iostream>
using namespace std;
int main() {
cout << "Hello world!" << endl;
return 0;
}
Save it as hello.cpp and compile with g++ hello.cpp -o hello.
Step-by-step
- Inside
int main(), declarestring name;and anint age;. - Give them values - your own name and age.
- Print with
cout << "My name is " << name << "!" << endl;. - Print
cout << "I am " << age << " years old." << endl;. - Add a comment above
main()that describes the program in one sentence. - Recompile and run. Tweak the wording until the output reads naturally.
Checklist
- [ ]
#include <iostream>is the first content line - [ ]
using namespace std;lets you usecout - [ ]
int main()returns an integer - [ ] Your name and your age are both printed
- [ ] A comment explains the program
- [ ] The program compiles and runs without errors
TL;DR
- Start with the right
#includesocoutworks. - Code runs inside
int main(). cout << value << endlprints text and numbers.//starts a single-line comment.