Module 1.3

Your First C++ Program

Time to write your first C++ program! In this lesson, you will learn the anatomy of a C++ program, how to display output, read input, and understand the essential building blocks that every C++ program needs. Let's start coding!

35 min read
Beginner
Hands-on Examples
What You'll Learn
  • Structure of a C++ program
  • The main() function explained
  • Output with cout and input with cin
  • Comments and documentation
  • Variables and basic data types
Contents
01

Hello, World!

Every programmer's journey begins with the classic "Hello, World!" program. This tradition started in the 1970s and serves as a simple way to verify that your programming environment is working correctly. Let's write your first C++ program!

What is a Program?

A program is a set of instructions written in a programming language that tells the computer what to do. Think of it like a recipe - you provide step-by-step instructions, and the computer follows them exactly.

C++ programs are compiled into machine code before execution, making them very fast!

Your First C++ Program

Here is the complete "Hello, World!" program in C++. Don't worry if it looks complex - we'll break down every part step by step.

// My first C++ program
#include <iostream>

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

Output:

Hello, World!
Beginner Tip: Type this code exactly as shown (C++ is case-sensitive!), save it as hello.cpp, compile it with g++ hello.cpp -o hello, and run with ./hello (or hello.exe on Windows).

Breaking It Down

Let's understand each line of our Hello World program:

Line Code What It Does
1 // My first C++ program A comment - ignored by the compiler, for humans only
2 #include <iostream> Includes the input/output library (needed for cout)
3 (empty line) Blank lines improve readability
4 int main() { The main function - where execution starts
5 std::cout << "Hello, World!" << std::endl; Prints "Hello, World!" to the screen
6 return 0; Tells the OS the program ran successfully
7 } Closes the main function

Simplified Version with "using namespace"

Typing std:: before every cout and cin can get tedious. You can simplify your code by adding using namespace std; at the top:

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}
Note: While using namespace std; is convenient for learning, professional code often uses std:: explicitly to avoid naming conflicts in larger projects.

More Hello World Variations

#include <iostream>
using namespace std;

int main() {
    // Multiple output statements
    cout << "Hello!" << endl;
    cout << "Welcome to C++ programming!" << endl;
    cout << "Let's learn together!" << endl;
    
    // Print numbers
    cout << "The answer is: " << 42 << endl;
    
    // Print on same line (no endl)
    cout << "Part 1 ";
    cout << "Part 2" << endl;
    
    // Print multiple items in one statement
    cout << "Name: " << "Alice" << ", Age: " << 25 << endl;
    
    return 0;
}

Output:

Hello!
Welcome to C++ programming!
Let's learn together!
The answer is: 42
Part 1 Part 2
Name: Alice, Age: 25
Practice Questions

Task: Write a C++ program that displays "My name is [Your Name]"

Show Solution
#include <iostream>
using namespace std;

int main() {
    cout << "My name is Sarah" << endl;
    return 0;
}

Task: Display a box made of asterisks with "C++" inside

Show Solution
#include <iostream>
using namespace std;

int main() {
    cout << "**********" << endl;
    cout << "*  C++   *" << endl;
    cout << "**********" << endl;
    return 0;
}

Task: Print "7 x 8 = 56" but calculate 56 using multiplication

Show Solution
#include <iostream>
using namespace std;

int main() {
    cout << "7 x 8 = " << 7 * 8 << endl;
    return 0;
}

Task: Write a program that prints a famous quote with the author's name on the next line.

Show Solution
#include <iostream>
using namespace std;

int main() {
    cout << "\"The only way to do great work is to love what you do.\"" << endl;
    cout << "  - Steve Jobs" << endl;
    return 0;
}

Task: Display a restaurant menu with at least 4 items and their prices formatted nicely.

Show Solution
#include <iostream>
using namespace std;

int main() {
    cout << "=============================" << endl;
    cout << "     PIZZA PALACE MENU       " << endl;
    cout << "=============================" << endl;
    cout << "1. Margherita Pizza ... $12.99" << endl;
    cout << "2. Pepperoni Pizza .... $14.99" << endl;
    cout << "3. Caesar Salad ....... $8.99" << endl;
    cout << "4. Garlic Bread ....... $4.99" << endl;
    cout << "=============================" << endl;
    return 0;
}
02

Anatomy of a C++ Program

Every C++ program follows a specific structure. Understanding this structure is crucial for writing correct and organized code. Let's examine the essential parts that make up every C++ program.

Program Structure
// 1. Preprocessor Directives
#include <iostream>
#include <string>

// 2. Namespace Declaration (optional)
using namespace std;

// 3. Function Declarations (optional)
void greet();

// 4. Main Function (required)
int main() {
    // 5. Statements
    greet();
    return 0;
}

// 6. Function Definitions
void greet() {
    cout << "Hello!" << endl;
}
Key Components
1
Preprocessor Directives Lines starting with # - processed before compilation
2
Namespace Declaration Avoids typing std:: repeatedly
3
Function Declarations Tell the compiler about functions defined later
4
main() Function Entry point - every program must have exactly one
5
Statements The actual instructions - end with semicolons
6
Function Definitions The actual code for declared functions

Preprocessor Directives

Lines beginning with # are preprocessor directives. They are processed before the actual compilation begins. The most common directive is #include, which copies the contents of a header file into your program.

Think of #include as importing a toolbox - you get access to pre-built tools (functions) you can use.

// Common header files you'll use:
#include <iostream>   // Input/Output: cout, cin, endl
#include <string>     // String handling: string class
#include <cmath>      // Math functions: sqrt(), pow(), sin()
#include <vector>     // Dynamic arrays: vector class
#include <fstream>    // File handling: ifstream, ofstream
#include <iomanip>    // Output formatting: setw(), setprecision()

The main() Function

The main() function is the entry point of every C++ program. When you run a program, execution always starts at the first line inside main() and proceeds line by line until it reaches return or the closing brace.

// main() can be written in several ways:

// Style 1: Standard (most common)
int main() {
    // code here
    return 0;
}

// Style 2: With command-line arguments
int main(int argc, char* argv[]) {
    // argc = number of arguments
    // argv = array of argument strings
    return 0;
}

// Style 3: Alternative argument style
int main(int argc, char** argv) {
    return 0;
}
Why return 0? The return value tells the operating system if the program succeeded (0) or failed (non-zero). This is useful for scripts and automation that need to know if a program completed correctly.

Statements and Semicolons

A statement is a complete instruction that tells the computer to do something. In C++, most statements end with a semicolon (;). Forgetting a semicolon is one of the most common beginner mistakes!

#include <iostream>
using namespace std;

int main() {
    // Each of these is a statement (ends with ;)
    int age = 25;                          // Variable declaration
    cout << "Hello" << endl;              // Output statement
    age = age + 1;                         // Assignment statement
    
    // Multiple statements on one line (legal but not recommended)
    int x = 5; int y = 10; int z = 15;
    
    // One statement across multiple lines (legal)
    cout << "This is a very long message "
         << "that spans multiple lines "
         << "in the source code"
         << endl;
    
    return 0;
}
Common Error: Missing semicolon!
cout << "Hello"    // ERROR: missing semicolon!
cout << "World";   // Compiler error on THIS line (confusing!)
Practice Questions

Task: Find and fix the error in this code:

#include <iostream>

int Main() {
    std::cout << "Hello";
    return 0;
}
Show Solution

Error: Main() should be main() (lowercase). C++ is case-sensitive!

#include <iostream>

int main() {  // Fixed: lowercase 'main'
    std::cout << "Hello";
    return 0;
}

Task: This code needs to use sqrt(). Add the correct include:

#include <iostream>
// Add missing include here

int main() {
    std::cout << sqrt(16) << std::endl;
    return 0;
}
Show Solution
#include <iostream>
#include <cmath>  // Contains sqrt(), pow(), etc.

int main() {
    std::cout << sqrt(16) << std::endl;  // Outputs: 4
    return 0;
}

Task: Find and fix the syntax error in this code:

#include <iostream>
using namespace std;

int main() {
    cout << "Line 1" << endl
    cout << "Line 2" << endl;
    return 0;
}
Show Solution

Error: Missing semicolon at the end of line 5.

#include <iostream>
using namespace std;

int main() {
    cout << "Line 1" << endl;  // Added semicolon
    cout << "Line 2" << endl;
    return 0;
}

Task: Identify why this program won't compile:

#include <iostream>
using namespace std;

void main() {
    cout << "Hello!" << endl;
}
Show Solution

Error: main() must return int, not void. This is a C++ standard requirement.

#include <iostream>
using namespace std;

int main() {        // Changed void to int
    cout << "Hello!" << endl;
    return 0;       // Added return statement
}

Task: Write a complete C++ program that displays the current date (hardcoded) using proper program structure with all required components.

Show Solution
#include <iostream>  // Required for cout
using namespace std; // Optional but convenient

int main() {
    // Display current date (hardcoded)
    cout << "============================" << endl;
    cout << "  Today's Date Information  " << endl;
    cout << "============================" << endl;
    cout << "Date: January 15, 2026" << endl;
    cout << "Day: Thursday" << endl;
    cout << "============================" << endl;
    
    return 0;  // Indicate successful execution
}
03

Output with cout

The cout (pronounced "see-out") object is your primary tool for displaying output to the screen. It stands for "character output" and is part of the iostream library. Let's master how to use it!

What is cout?

cout is a predefined object of the ostream class that represents the standard output stream (usually your screen). The << operator is called the insertion operator - it "inserts" data into the output stream.

Think of << as an arrow pointing where the data should go: data flows from right to left into cout.

Basic Output

#include <iostream>
using namespace std;

int main() {
    // Printing text (strings)
    cout << "Hello, World!";           // Output: Hello, World!
    
    // Printing with new line
    cout << "Line 1" << endl;          // endl = end line
    cout << "Line 2\n";                 // \n also creates new line
    
    // Printing numbers
    cout << 42 << endl;                 // Integer: 42
    cout << 3.14159 << endl;            // Float: 3.14159
    
    // Printing expressions (calculated automatically)
    cout << 10 + 5 << endl;             // Output: 15
    cout << 100 / 4 << endl;            // Output: 25
    
    return 0;
}

Chaining Multiple Items

You can chain multiple items in a single cout statement using multiple << operators. This is cleaner than writing multiple cout statements.

#include <iostream>
using namespace std;

int main() {
    string name = "Alice";
    int age = 25;
    double gpa = 3.85;
    
    // Chaining multiple outputs
    cout << "Name: " << name << endl;
    cout << "Age: " << age << " years old" << endl;
    cout << "GPA: " << gpa << "/4.0" << endl;
    
    // All in one statement
    cout << name << " is " << age << " with GPA " << gpa << endl;
    
    // Mixing calculations
    cout << "In 10 years, " << name << " will be " << age + 10 << endl;
    
    return 0;
}

Output:

Name: Alice
Age: 25 years old
GPA: 3.85/4.0
Alice is 25 with GPA 3.85
In 10 years, Alice will be 35

Escape Sequences

Escape sequences are special character combinations that represent characters you can't easily type, like tabs, new lines, or quotes. They all start with a backslash (\).

Escape Sequence Name Effect
\n Newline Moves cursor to next line
\t Tab Horizontal tab (usually 4-8 spaces)
\\ Backslash Prints a single backslash
\" Double Quote Prints a double quote character
\' Single Quote Prints a single quote character
\r Carriage Return Moves cursor to beginning of line
#include <iostream>
using namespace std;

int main() {
    // Newline examples
    cout << "Line 1\nLine 2\nLine 3" << endl;
    
    // Tab for formatting
    cout << "Name\tAge\tCity" << endl;
    cout << "Alice\t25\tNew York" << endl;
    cout << "Bob\t30\tLos Angeles" << endl;
    
    // Printing quotes and backslash
    cout << "She said \"Hello!\"" << endl;
    cout << "Path: C:\\Users\\Documents" << endl;
    
    return 0;
}

Output:

Line 1
Line 2
Line 3
Name    Age     City
Alice   25      New York
Bob     30      Los Angeles
She said "Hello!"
Path: C:\Users\Documents
endl vs \n: Both create a new line, but endl also flushes the output buffer (forces immediate display). Use \n for better performance in loops; use endl when you need to ensure output appears immediately.
Practice Questions

Task: Print a receipt showing: Item, Price (use tabs for alignment)

Show Solution
#include <iostream>
using namespace std;

int main() {
    cout << "=== RECEIPT ===" << endl;
    cout << "Item\t\tPrice" << endl;
    cout << "Coffee\t\t$3.50" << endl;
    cout << "Sandwich\t$7.99" << endl;
    cout << "Cookie\t\t$1.50" << endl;
    cout << "===============" << endl;
    return 0;
}

Task: Print: File located at: "C:\Program Files\App\data.txt"

Show Solution
#include <iostream>
using namespace std;

int main() {
    cout << "File located at: \"C:\\Program Files\\App\\data.txt\"" << endl;
    return 0;
}

Task: Create variables for name ("Alex"), age (22), and city ("Boston"). Print them all in one cout statement.

Show Solution
#include <iostream>
#include <string>
using namespace std;

int main() {
    string name = "Alex";
    int age = 22;
    string city = "Boston";
    
    cout << name << " is " << age << " years old and lives in " << city << "." << endl;
    
    return 0;
}

Task: Print a table of 3 students with their names and grades using tab escape sequences for alignment.

Show Solution
#include <iostream>
using namespace std;

int main() {
    cout << "Student\t\tGrade" << endl;
    cout << "------------------------" << endl;
    cout << "Alice\t\tA" << endl;
    cout << "Bob\t\tB+" << endl;
    cout << "Charlie\t\tA-" << endl;
    
    return 0;
}

Task: Print a small diamond shape using asterisks (*) with cout.

Show Solution
#include <iostream>
using namespace std;

int main() {
    cout << "  *  " << endl;
    cout << " *** " << endl;
    cout << "*****" << endl;
    cout << " *** " << endl;
    cout << "  *  " << endl;
    
    return 0;
}
04

Input with cin

While cout sends output to the screen, cin (pronounced "see-in") reads input from the keyboard. This allows your programs to interact with users and work with dynamic data instead of hardcoded values.

What is cin?

cin is a predefined object of the istream class that represents the standard input stream (usually your keyboard). The >> operator is called the extraction operator - it "extracts" data from the input stream and stores it in a variable.

Think of >> as an arrow pointing where the data should go: data flows from cin into your variable.

Basic Input

#include <iostream>
using namespace std;

int main() {
    int age;
    
    // Prompt the user
    cout << "Enter your age: ";
    
    // Read input into variable
    cin >> age;
    
    // Use the input
    cout << "You are " << age << " years old." << endl;
    cout << "In 10 years, you'll be " << age + 10 << "!" << endl;
    
    return 0;
}

Sample Run:

Enter your age: 25
You are 25 years old.
In 10 years, you'll be 35!

Reading Different Data Types

The cin object can read different data types automatically. It converts the text input to the appropriate type based on the variable you're storing it in.

Reading Integers
int quantity;
cout << "Enter quantity: ";
cin >> quantity;
cout << "You entered: " << quantity << endl;
Integer Input: When reading an int, cin expects whole numbers only. If user enters "5.7", only 5 is read (decimal part stays in buffer).
Reading Decimal Numbers
double price;
cout << "Enter price: ";
cin >> price;
cout << "Price is: $" << price << endl;
Decimal Input: Use double or float for numbers with decimals. User can enter "19.99" or "20" (automatically converted to 20.0).
Reading a Single Word
string firstName;
cout << "Enter first name: ";
cin >> firstName;
cout << "Hello, " << firstName << "!" << endl;
Important: cin >> stops at whitespace! If user types "John Smith", only "John" is stored. Use getline() for full names (covered below).
Reading a Single Character
char grade;
cout << "Enter grade (A-F): ";
cin >> grade;
cout << "Your grade is: " << grade << endl;
Character Input: Reads only the first character. If user types "ABC", only 'A' is stored. Useful for menu choices, yes/no prompts, or single-letter grades.

Reading Multiple Values

#include <iostream>
using namespace std;

int main() {
    int x, y, z;
    
    // Method 1: Separate prompts
    cout << "Enter x: ";
    cin >> x;
    cout << "Enter y: ";
    cin >> y;
    
    // Method 2: One line, space-separated input
    cout << "Enter three numbers (space-separated): ";
    cin >> x >> y >> z;
    
    cout << "Sum: " << x + y + z << endl;
    
    return 0;
}

Sample Run:

Enter three numbers (space-separated): 10 20 30
Sum: 60

Reading Full Lines with getline()

The cin >> operator stops reading at whitespace. To read an entire line (including spaces), use getline().

#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    string address;
    
    cout << "Enter your full name: ";
    getline(cin, fullName);  // Reads entire line including spaces
    
    cout << "Enter your address: ";
    getline(cin, address);
    
    cout << "\nDelivery to:" << endl;
    cout << fullName << endl;
    cout << address << endl;
    
    return 0;
}

Sample Run:

Enter your full name: John Michael Smith
Enter your address: 123 Main Street, Apt 4B
Delivery to:
John Michael Smith
123 Main Street, Apt 4B
Common Pitfall: When mixing cin >> with getline(), you need to clear the newline character left in the buffer:
int age;
string name;

cin >> age;
cin.ignore();       // Clear the leftover newline!
getline(cin, name); // Now this works correctly
Practice Questions

Task: Read two numbers and display their sum, difference, and product

Show Solution
#include <iostream>
using namespace std;

int main() {
    double num1, num2;
    
    cout << "Enter first number: ";
    cin >> num1;
    
    cout << "Enter second number: ";
    cin >> num2;
    
    cout << "\nResults:" << endl;
    cout << "Sum: " << num1 + num2 << endl;
    cout << "Difference: " << num1 - num2 << endl;
    cout << "Product: " << num1 * num2 << endl;
    
    return 0;
}

Task: Ask for full name and age, then greet them and calculate birth year

Show Solution
#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    int age;
    int currentYear = 2026;
    
    cout << "Enter your full name: ";
    getline(cin, fullName);
    
    cout << "Enter your age: ";
    cin >> age;
    
    int birthYear = currentYear - age;
    
    cout << "\nHello, " << fullName << "!" << endl;
    cout << "You were born in " << birthYear << "." << endl;
    
    return 0;
}

Task: Read Celsius temperature and convert to Fahrenheit. Formula: F = C * 9/5 + 32

Show Solution
#include <iostream>
using namespace std;

int main() {
    double celsius;
    
    cout << "Enter temperature in Celsius: ";
    cin >> celsius;
    
    double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
    
    cout << celsius << " C = " << fahrenheit << " F" << endl;
    
    return 0;
}

Task: Read length and width from user, calculate and display the area of a rectangle.

Show Solution
#include <iostream>
using namespace std;

int main() {
    double length, width;
    
    cout << "Enter rectangle length: ";
    cin >> length;
    
    cout << "Enter rectangle width: ";
    cin >> width;
    
    double area = length * width;
    
    cout << "Area = " << area << " square units" << endl;
    
    return 0;
}

Task: Ask for student's full name (with getline) and 3 test scores. Display the name and average score.

Show Solution
#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    double score1, score2, score3;
    
    cout << "Enter student's full name: ";
    getline(cin, fullName);
    
    cout << "Enter 3 test scores (space-separated): ";
    cin >> score1 >> score2 >> score3;
    
    double average = (score1 + score2 + score3) / 3.0;
    
    cout << "\n=== Grade Report ===" << endl;
    cout << "Student: " << fullName << endl;
    cout << "Scores: " << score1 << ", " << score2 << ", " << score3 << endl;
    cout << "Average: " << average << endl;
    
    return 0;
}
05

Variables and Data Types

Variables are containers that store data in your program. Unlike Python, C++ is a statically typed language, meaning you must declare the type of data a variable will hold before using it.

What is a Variable?

A variable is a named storage location in memory that holds a value. In C++, you must specify what type of data the variable will store when you create it. The type determines how much memory is allocated and what operations are allowed.

Think of a variable as a labeled box - the label is the variable name, and the box can only hold one type of item.

Fundamental Data Types

Type Description Size Example
int Integer (whole numbers) 4 bytes int age = 25;
double Floating-point (decimals) 8 bytes double price = 19.99;
float Single-precision decimal 4 bytes float pi = 3.14f;
char Single character 1 byte char grade = 'A';
bool Boolean (true/false) 1 byte bool isValid = true;
string Text (sequence of chars) varies string name = "Alice";

Declaring and Initializing Variables

Declaration

Creating a variable (reserving memory space) without giving it a value.

int count;      // Variable exists but has garbage value
double price;   // Memory reserved, no value yet
Initialization

Giving a variable its first value (can be done at declaration or later).

int count = 10;     // Declare + Initialize (best!)
count = 20;         // Assign new value later
Best Practice: Always initialize variables when you declare them. Uninitialized variables contain "garbage" - random leftover data in memory that can cause bugs!
Basic Variable Types
int age = 25;           // Whole numbers
double salary = 55000.50;  // Decimal numbers
char initial = 'J';     // Single character (use single quotes)
bool isEmployed = true; // true or false
string city = "New York"; // Text (use double quotes)
Note: Each type serves a purpose - int for counting, double for measurements/money, char for single characters, bool for yes/no decisions, and string for text. Choose the right type for your data!
Multiple Declarations
// Declare multiple variables of the same type in one line
int x = 1, y = 2, z = 3;

// Equivalent to:
int a = 10;
int b = 20;
int c = 30;
Shortcut: You can declare multiple variables of the same type separated by commas. This is useful for related variables like coordinates (x, y, z) or RGB values (r, g, b).
Constants (const)
const double PI = 3.14159;
const int MAX_SIZE = 100;
const string APP_NAME = "MyApp";

// PI = 3.14;  // ERROR! Cannot modify a constant
Protection: Use const for values that should never change. The compiler will prevent accidental modifications. Convention: use UPPER_CASE names for constants to make them easily recognizable.
Using Variables in Output
cout << "Age: " << age << endl;           // Age: 25
cout << "Salary: $" << salary << endl;    // Salary: $55000.5
cout << "Employed: " << isEmployed << endl; // Employed: 1 (true=1, false=0)
Display: Chain variables with text using <<. Note that bool values display as 1 (true) or 0 (false), not as "true"/"false" text.

Variable Naming Rules

Valid Names
  • age - lowercase letters
  • firstName - camelCase
  • total_count - underscores
  • _private - starts with underscore
  • MAX_VALUE - constants in CAPS
  • item2 - letters and numbers
Invalid Names
  • 2ndPlace - cannot start with number
  • my-variable - no hyphens allowed
  • my variable - no spaces allowed
  • int - reserved keyword
  • class - reserved keyword
  • $price - no special characters

Type Conversion

C++ allows converting values from one data type to another. This can happen automatically (implicit) or manually (explicit). Understanding type conversion helps avoid unexpected behavior and data loss.

Implicit Conversion (Widening)
int intVal = 10;
double doubleVal = intVal;  // int to double (safe)
cout << "Int to Double: " << doubleVal << endl;  // Output: 10
Safe Conversion: Converting from a smaller type (int) to a larger type (double) is called widening. No data is lost because double can hold all int values.
Implicit Conversion (Narrowing)
double pi = 3.14159;
int truncated = pi;  // double to int (loses decimal)
cout << "Double to Int: " << truncated << endl;  // Output: 3
Data Loss Warning: Converting from double to int is called narrowing. The decimal part (.14159) is truncated (chopped off), not rounded. This can lead to unexpected results!
Explicit Conversion (Casting)
// Without cast: integer division
cout << 7 / 2 << endl;  // Output: 3 (not 3.5!)

// With cast: floating-point division
double result = static_cast<double>(7) / 2;
cout << "7/2 with cast: " << result << endl;  // Output: 3.5
static_cast: Use static_cast<type>(value) to explicitly convert a value. This tells the compiler you intentionally want this conversion, and makes your code clearer to other developers.
Character ↔ Integer Conversion
// Character to ASCII value
char ch = 'A';
int ascii = ch;
cout << "ASCII of 'A': " << ascii << endl;  // Output: 65

// ASCII value to character
char fromInt = 66;
cout << "Char from 66: " << fromInt << endl;  // Output: B
ASCII Values: Characters are stored as numbers internally (ASCII codes). 'A' = 65, 'B' = 66, 'a' = 97, '0' = 48. You can convert between char and int freely to work with these values.
Practice Questions

Task: Declare variables for: name (string), age (int), gpa (double), grade (char)

Show Solution
#include <iostream>
#include <string>
using namespace std;

int main() {
    string name = "Alice Johnson";
    int age = 20;
    double gpa = 3.85;
    char grade = 'A';
    
    cout << "=== Student Profile ===" << endl;
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "GPA: " << gpa << endl;
    cout << "Grade: " << grade << endl;
    
    return 0;
}

Task: Use a const for PI, read radius, calculate and display area

Show Solution
#include <iostream>
using namespace std;

int main() {
    const double PI = 3.14159;
    double radius;
    
    cout << "Enter circle radius: ";
    cin >> radius;
    
    double area = PI * radius * radius;
    
    cout << "Area = " << area << " square units" << endl;
    
    return 0;
}

Task: Create two int variables with values 10 and 20. Swap their values using a third (temp) variable and print before/after.

Show Solution
#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 20;
    
    cout << "Before swap: a = " << a << ", b = " << b << endl;
    
    // Swap using temp variable
    int temp = a;
    a = b;
    b = temp;
    
    cout << "After swap:  a = " << a << ", b = " << b << endl;
    
    return 0;
}

Task: Declare an int with value 7 and another int with value 2. Calculate their division as both int and double (using casting).

Show Solution
#include <iostream>
using namespace std;

int main() {
    int a = 7, b = 2;
    
    // Integer division (truncates)
    int intResult = a / b;
    cout << "Integer division: 7 / 2 = " << intResult << endl;
    
    // Double division (preserves decimal)
    double doubleResult = static_cast<double>(a) / b;
    cout << "Double division:  7 / 2 = " << doubleResult << endl;
    
    return 0;
}

Task: Create a mini product tracker with: product name (string), price (double), quantity (int), is_available (bool). Calculate and display total value.

Show Solution
#include <iostream>
#include <string>
using namespace std;

int main() {
    // Product information
    string productName = "Wireless Headphones";
    double price = 79.99;
    int quantity = 15;
    bool isAvailable = true;
    
    // Calculate total inventory value
    double totalValue = price * quantity;
    
    // Display product info
    cout << "=== Product Inventory ===" << endl;
    cout << "Product: " << productName << endl;
    cout << "Price: $" << price << endl;
    cout << "Quantity: " << quantity << " units" << endl;
    cout << "Available: " << (isAvailable ? "Yes" : "No") << endl;
    cout << "Total Value: $" << totalValue << endl;
    
    return 0;
}
06

Comments and Documentation

Comments are notes in your code that the compiler ignores. They explain what your code does, making it easier for you and others to understand. Good comments are essential for maintaining and debugging code.

Types of Comments

Single-Line Comments ( // )
// This is a single-line comment
// Each line needs its own //

int age = 25;  // inline comment after code
int score = 100;  // explains what the variable is for
Usage: Use // for short comments. Everything after // until the end of the line is ignored by the compiler. Great for quick notes and inline explanations.
Multi-Line Comments ( /* */ )
/*
   This is a multi-line comment.
   It can span multiple lines.
   Useful for longer explanations.
*/

/* You can also use it on a single line */
Usage: Use /* */ for longer comments that span multiple lines. Also useful for temporarily disabling blocks of code during debugging. Note: Multi-line comments cannot be nested!
Documentation Comments (Doxygen)
/**
 * @brief Calculates the area of a rectangle.
 * @param width The width of the rectangle.
 * @param height The height of the rectangle.
 * @return The calculated area.
 */
double calculateArea(double width, double height) {
    return width * height;
}
Usage: Documentation comments starting with /** are used by tools like Doxygen to auto-generate documentation. Use tags like @brief, @param, and @return to describe functions professionally.
Commenting Out Code
int main() {
    int result = calculate();
    
    /* This code is temporarily disabled for debugging:
    cout << "Debug info: " << result << endl;
    cout << "Extra output" << endl;
    */
    
    cout << "Final: " << result << endl;
    return 0;
}
Debugging Tip: Use comments to temporarily disable code instead of deleting it. This is useful when testing or debugging. Remember to remove commented-out code before final submission - version control (Git) keeps history for you!

Comment Best Practices

Good Comments
// Calculate tax (7.5% sales tax)
double tax = price * 0.075;

// Skip negative values
if (value < 0) continue;

// TODO: Add input validation
// FIXME: Handle division by zero
Bad Comments
// Increment i by 1
i++;  // Obvious, no comment needed

// This is a variable
int x = 5;

// Add a and b
int sum = a + b;  // Code is self-explanatory
Rule of Thumb: Comment the "why", not the "what". Good code should be self-explanatory about what it does; comments should explain why you're doing it that way.
Practice Questions

Task: Add meaningful comments to this code:

double price = 49.99;
double discount = 0.20;
double finalPrice = price * (1 - discount);
Show Solution
// Original product price
double price = 49.99;

// 20% discount for members
double discount = 0.20;

// Apply discount to get final price
double finalPrice = price * (1 - discount);

Task: Convert these single-line comments to a multi-line comment block:

// This program calculates BMI
// BMI = weight / (height * height)
// Weight in kg, height in meters
Show Solution
/*
 * This program calculates BMI
 * BMI = weight / (height * height)
 * Weight in kg, height in meters
 */

Task: Identify which comments are unnecessary and should be removed:

int count = 0;        // Set count to 0
count++;              // Increment count by 1
count = count + 10;   // Add 10 to count
// Reset if exceeds threshold (100)
if (count > 100) count = 0;
Show Solution

Bad comments (should be removed):

  • "Set count to 0" - obvious from code
  • "Increment count by 1" - obvious from code
  • "Add 10 to count" - obvious from code

Good comment (should keep):

  • "Reset if exceeds threshold (100)" - explains the WHY
int count = 0;
count++;
count = count + 10;
// Reset if exceeds threshold (100)
if (count > 100) count = 0;

Task: Write a proper file header comment for a calculator program that includes: program name, author, date, and description.

Show Solution
/*
 * Program: Simple Calculator
 * Author: Your Name
 * Date: January 2026
 * 
 * Description:
 * A basic calculator program that performs arithmetic
 * operations (addition, subtraction, multiplication,
 * division) on two numbers entered by the user.
 *
 * Usage: Run the program and follow the prompts.
 */

#include <iostream>
using namespace std;

int main() {
    // Calculator code here...
    return 0;
}

Task: Add proper documentation comments to this function using Doxygen style:

double calculateBMI(double weight, double height) {
    return weight / (height * height);
}
Show Solution
/**
 * @brief Calculates Body Mass Index (BMI) from weight and height.
 * 
 * BMI is a measure of body fat based on height and weight.
 * BMI Categories:
 *   - Underweight: BMI < 18.5
 *   - Normal: 18.5 <= BMI < 25
 *   - Overweight: 25 <= BMI < 30
 *   - Obese: BMI >= 30
 * 
 * @param weight The person's weight in kilograms (kg).
 * @param height The person's height in meters (m).
 * @return The calculated BMI value.
 * 
 * @example
 *   double bmi = calculateBMI(70.0, 1.75); // Returns ~22.86
 */
double calculateBMI(double weight, double height) {
    return weight / (height * height);
}

Key Takeaways

Program Structure

Every C++ program needs #include directives, a main() function, and statements ending with semicolons

Output with cout

Use cout with the insertion operator (<<) to display output. Chain multiple items and use endl for newlines

Input with cin

Use cin with the extraction operator (>>) to read input. Use getline() for strings with spaces

Data Types

C++ is statically typed. Use int, double, char, bool, and string. Declare type before variable name

Constants

Use const for values that should not change. Convention is UPPER_CASE names for constants

Comments

Use // for single-line and /* */ for multi-line comments. Comment the "why", not the "what"

Knowledge Check

Test your understanding of C++ basics:

Question 1 of 6

What is the correct way to output "Hello" in C++?

Question 2 of 6

Which header file is needed for cin and cout?

Question 3 of 6

What type should be used for storing 3.14159?

Question 4 of 6

What does return 0; in main() indicate?

Question 5 of 6

Which variable name is INVALID in C++?

Question 6 of 6

How do you read a full line of text including spaces?

Answer all questions to check your score