C++ - First Program

Overview

Estimated time: 25–35 minutes

Write and run your first C++ program, read input, and print formatted output with std::cout.

Learning Objectives

  • Compile and execute a simple C++ program.
  • Use standard input/output streams.
  • Understand the role of main and return codes.

Prerequisites

Hello, World

#include <iostream>
int main(){
  std::cout << "Hello, World!\n";
}

Expected Output:

Hello, World!

Input and output

#include <iostream>
#include <string>

int main(){
  std::string name;
  std::cout << "What is your name? ";
  std::getline(std::cin, name);
  std::cout << "Nice to meet you, " << name << "!\n";
}

Sample Run:

What is your name? Alice
Nice to meet you, Alice!

Common Pitfalls

  • Mixing std::cin & operator>> with std::getline without handling leftover newlines—prefer getline for full lines.
  • Forgetting to include necessary headers (iostream, string).

Checks for Understanding

  1. How do you read a full line from input?
  2. How do you print a value?
Show answers
  1. std::getline(std::cin, line)
  2. std::cout << value;

Exercises

  1. Ask the user for two integers and print their sum.
  2. Prompt for first and last name and print a greeting using both.