C++ · Module 1 · Lesson 31 min read

Your First C++ Program

Hello, World!

c
#include <iostream>

int main() {
    std::cout << "Hello, World!\n";
    return 0;
}

Line by line

CodeMeaning
#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::coutthe 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

c
std::cout << "Age: " << 20 << '\n';

Each << sends the next item.

'\n' vs std::endl

  • '\n' adds a newline
  • std::endl adds a newline and flushes the buffer (slower) Use '\n' normally; use std::endl only when output must appear immediately.

Escape sequences

\n newline · \t tab · \\ backslash · \" double quote · \' single quote

Common beginner mistakes

  • Forgetting the ;
  • Writing cout without std:: (or a using declaration)
  • Main instead of main (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

C++
#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
*/