Your First C++ Program
Hello, World!
#include <iostream>
int main() {
std::cout << "Hello, World!\n";
return 0;
}
Line by line
| Code | Meaning |
|---|---|
#include <iostream> | include the input/output stream library (cout, cin) |
int main() | the entry point; every program has exactly one main |
{ ... } | the body of the function |
std::cout | the standard character output stream (the console) |
<< | insertion operator: sends data into the stream |
"Hello, World!\n" | a string literal; \n is a newline |
; | ends a statement |
return 0; | tells the operating system the program succeeded |
What is std::?
std is the namespace of the standard library. std::cout means "the cout that belongs to std". (Namespaces are covered in Unit 2.)
Chaining output
std::cout << "Age: " << 20 << '\n';
Each << sends the next item.
'\n' vs std::endl
'\n'adds a newlinestd::endladds a newline and flushes the buffer (slower) Use'\n'normally; usestd::endlonly when output must appear immediately.
Escape sequences
\n newline · \t tab · \\ backslash · \" double quote · \' single quote
Common beginner mistakes
- Forgetting the
; - Writing
coutwithoutstd::(or a using declaration) Maininstead ofmain(C++ is case-sensitive)- Using
<<in the wrong direction (>>is for input)
About return 0
In main only, you may omit it: reaching the end of main returns 0 automatically.
Example
#include <iostream>
int main() {
std::cout << "Hello, World!\n";
std::cout << "Welcome to " << "C++" << " on BudgetBuddy Learn" << '\n';
std::cout << "Name:\tAsha\nCity:\tPokhara\n";
std::cout << "She said \"C++ is fast\" \\o/\n";
std::cout << 7 << " + " << 5 << " = " << 7 + 5 << std::endl;
return 0;
}
/* Output:
Hello, World!
Welcome to C++ on BudgetBuddy Learn
Name: Asha
City: Pokhara
She said "C++ is fast" \o/
7 + 5 = 12
*/