C++ - Syntax & Basics

Overview

Estimated time: 35–45 minutes

Learn basic syntax: variables, types, expressions vs statements, and simple control flow with if and loops.

Learning Objectives

  • Declare and initialize variables; understand type inference with auto.
  • Write conditionals and loops.
  • Follow modern style basics (use braces, avoid using namespace std in headers).

Prerequisites

Variables and types

#include <iostream>
int main(){
  int x = 10;
  double y = 3.14;
  auto z = x + y; // z is double
  std::cout << z << "\n"; // 13.14
}

Expected Output: 13.14

Control flow

#include <iostream>
int main(){
  for (int i=0; i<3; ++i) std::cout << i << "\n";
}

Expected Output: 0\n1\n2

Expressions vs statements (deeper look)

#include <iostream>
int square(int x){ return x*x; } // function declaration is a statement
int main(){
  int n = 3;              // statement with initializer expression
  int s = square(n+1);    // expression inside parentheses
  std::cout << s << "\n";  // expression with side effects
}

Expected Output: 16

switch basics

#include <iostream>
int main(){
  int grade = 85;
  switch (grade/10) {
    case 10:
    case 9: std::cout << "A\n"; break;
    case 8: std::cout << "B\n"; break;
    default: std::cout << "Other\n"; break;
  }
}

Expected Output (example): B

Loop variants

#include <iostream>
#include <vector>
int main(){
  int i = 3;
  while (i > 0) { std::cout << i-- << ' '; } // while
  std::cout << "\n";

  int j = 0;
  do { std::cout << j++ << ' '; } while (j < 3); // do-while
  std::cout << "\n";

  std::vector xs{10,20,30};
  for (int x : xs) std::cout << x << ' '; // range-for
}

Expected Output: 3 2 1 0 1 2 10 20 30

Common Pitfalls

  • Uninitialized variables—always initialize.
  • Integer division surprises; cast to double when needed.

Checks for Understanding

  1. What does auto do?
  2. How do you write a for loop from 0..n-1?
Show answers
  1. Type deduction from initializer.
  2. for (int i=0; i<n; ++i) { ... }

Exercises

  1. Write a loop that prints even numbers from 2..20.
  2. Compute the sum of 1..N using a loop.