C++ Tutorial menu

C++ Introduction

C++ is a fast, general-purpose programming language used for games, systems and high-performance software.

What is C++?

  • C++ was created by Bjarne Stroustrup, starting in 1979, as "C with Classes"
  • It supports object-oriented programming (classes and objects)
  • It is a compiled language, so programs run very fast
  • New versions keep adding modern features: C++11, C++17, C++20 and C++23

Where is C++ Used?

AreaExamples
GamesUnreal Engine, many PC and console games
BrowsersChrome and Firefox are written mostly in C++
FinanceFast trading and banking systems
DevicesRobots, drones, cars and medical machines

Getting Set Up

You need a compiler and an editor:

  • Windows: install Visual Studio Community (choose "Desktop development with C++"), or install g++ with MSYS2 and use VS Code
  • Linux: run sudo apt install g++
  • macOS: run xcode-select --install to get clang++

Save your code in a file such as main.cpp, then compile and run:

Example

text
g++ main.cpp -o main
./main

Your First Program

Example

cpp
#include <iostream>
using namespace std;

int main() {
  cout << "Assalam o Alaikum!" << endl;
  cout << "Welcome to C++." << endl;
  return 0;
}
Output
Assalam o Alaikum!
Welcome to C++.

The example explained

LineMeaning
#include <iostream>Adds the library for input and output (cout, cin)
using namespace std;Lets you write cout instead of std::cout
int main()The main function, where every C++ program starts
cout << "..."Sends text to the screen
endlEnds the line (you can also use "\n")
return 0;Ends the program successfully

Every statement ends with a semicolon ;.

Printing Several Values

You can chain many values with <<, including numbers and maths:

Example

cpp
#include <iostream>
using namespace std;

int main() {
  cout << "Price: Rs " << 350 << "\n";
  cout << "Total for 3: Rs " << 350 * 3 << "\n";
  return 0;
}
Output
Price: Rs 350
Total for 3: Rs 1050

Comments

Example

cpp
// This is a single-line comment

/* This is a
   multi-line comment */

In large projects many programmers write std::cout instead of using namespace std;, to avoid name clashes. Both work; this tutorial uses the shorter form to keep examples easy to read.

Exercise

Exercise

Which line is needed to use cout in a C++ program?

Learn C++ with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp