c++

C++ for beginners


Section 1: Introduction to C++

C++ is a powerful and fast programming language used for building applications, games, operating systems, and more. It was developed by Bjarne Stroustrup as an extension of the C language, adding object-oriented features such as classes and inheritance.

๐Ÿ”น Your First C++ Program

#include <iostream>
using namespace std;

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

๐Ÿงฉ Explanation

๐Ÿ’ป Try It Yourself

You can test this code on an online compiler like Programiz C++ Compiler.

๐Ÿง  Exercise

Modify the program to print your own message:

#include <iostream>
using namespace std;

int main() {
    cout << "Welcome to my C++ learning website!";
    return 0;
}
  

Section 2: Variables and Data Types

In C++, variables are used to store data values such as numbers, characters, or text. Every variable must have a name and a data type that defines what kind of value it holds.

๐Ÿ”น Example Program

#include <iostream>
using namespace std;

int main() {
    int age = 18;              // Integer variable
    float height = 5.9;        // Decimal number
    char grade = 'A';          // Single character
    string name = "Bright";    // Text
    bool isStudent = true;     // True or False

    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Height: " << height << endl;
    cout << "Grade: " << grade << endl;
    cout << "Is Student: " << isStudent << endl;

    return 0;
}
  

๐Ÿงฉ Explanation

  • int โ†’ Stores whole numbers (e.g., 10, -5, 200).
  • float โ†’ Stores decimal numbers (e.g., 4.5, 3.14).
  • char โ†’ Stores single characters inside single quotes (e.g., 'A').
  • string โ†’ Stores text inside double quotes (e.g., "Hello").
  • bool โ†’ Stores true or false values.
  • endl โ†’ Moves to a new line in output.

๐Ÿ’ป Output Example

Name: Bright
Age: 18
Height: 5.9
Grade: A
Is Student: 1
  

๐Ÿง  Exercise

Try changing the values of the variables and print your own details.

#include <iostream>
using namespace std;

int main() {
    string name = "YourName";
    int age = 20;
    float height = 6.2;
    char grade = 'B';
    bool isStudent = false;

    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Height: " << height << endl;
    cout << "Grade: " << grade << endl;
    cout << "Is Student: " << isStudent << endl;

    return 0;
}
  

Section 3: Getting User Input in C++

In C++, you can take input from the user using the cin command. It reads data entered through the keyboard and stores it in variables.

๐Ÿ”น Example Program

#include <iostream>
using namespace std;

int main() {
    string name;
    int age;

    cout << "Enter your name: ";
    cin >> name;  // take input from user

    cout << "Enter your age: ";
    cin >> age;

    cout << "\nHello " << name << "! You are " << age << " years old." << endl;

    return 0;
}
  

๐Ÿงฉ Explanation

  • cin โ†’ Used to receive input from the user.
  • >> โ†’ Extraction operator (reads data into a variable).
  • cout โ†’ Used to display output on the screen.
  • \n โ†’ Creates a new line (like pressing Enter).

๐Ÿ’ป Output Example

Enter your name: Bright
Enter your age: 18
Hello Bright! You are 18 years old.
  

โš ๏ธ Note

cin only reads one word. If you type a full name like "Bright Twumasi", it will only take "Bright". To read full sentences or names with spaces, use getline() instead.

๐Ÿ”น Example Using getline()

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

int main() {
    string fullName;

    cout << "Enter your full name: ";
    getline(cin, fullName);  // reads entire line including spaces

    cout << "Hello, " << fullName << "!" << endl;

    return 0;
}
  

๐Ÿง  Exercise

Create a program that asks the user for their name, age, and favorite color, then displays a message like:
Hello Bright, you are 18 years old and your favorite color is blue!


Section 5: Ifโ€“Else Statements (Decision Making)

Sometimes your program needs to make decisions โ€” for example, checking if a person is old enough to vote or if a number is positive or negative. In C++, you can do this using the if and else statements.

๐Ÿ”น Example Program: Check Voting Eligibility

#include <iostream>
using namespace std;

int main() {
    int age;

    cout << "Enter your age: ";
    cin >> age;

    if (age >= 18) {
        cout << "You are eligible to vote!" << endl;
    } else {
        cout << "Sorry, you are too young to vote." << endl;
    }

    return 0;
}
  

๐Ÿงฉ Explanation

  • if (condition) โ†’ Checks whether the condition is true.
  • else โ†’ Runs when the if condition is false.
  • >= โ†’ Means "greater than or equal to".

๐Ÿ’ป Example Output

Enter your age: 19
You are eligible to vote!
  

๐Ÿ”น Example 2: Even or Odd Number

#include <iostream>
using namespace std;

int main() {
    int number;

    cout << "Enter a number: ";
    cin >> number;

    if (number % 2 == 0) {
        cout << number << " is even." << endl;
    } else {
        cout << number << " is odd." << endl;
    }

    return 0;
}
  

๐Ÿง  Explanation

  • % โ†’ Finds the remainder after division.
  • If a number divided by 2 has a remainder of 0, itโ€™s even; otherwise, itโ€™s odd.

โšก Extra Tip

You can chain multiple conditions using else if to handle more possibilities.

๐Ÿ”น Example 3: Grade System

#include <iostream>
using namespace std;

int main() {
    int score;

    cout << "Enter your score: ";
    cin >> score;

    if (score >= 80) {
        cout << "Grade: A" << endl;
    } else if (score >= 70) {
        cout << "Grade: B" << endl;
    } else if (score >= 60) {
        cout << "Grade: C" << endl;
    } else if (score >= 50) {
        cout << "Grade: D" << endl;
    } else {
        cout << "Grade: F (Fail)" << endl;
    }

    return 0;
}
  

๐Ÿง  Exercise

Create a program that asks for a user's temperature reading and tells them:

  • โ€œItโ€™s too cold!โ€ if temperature is below 15ยฐC
  • โ€œNice weather!โ€ if itโ€™s between 15ยฐC and 30ยฐC
  • โ€œItโ€™s hot!โ€ if above 30ยฐC

๐Ÿง  C++ Basics Quiz (Sections 1โ€“5)

Test your knowledge from Introduction to Ifโ€“Else Statements. Select the best answer for each question and click Submit.

1๏ธโƒฃ What does #include <iostream> do in C++?






2๏ธโƒฃ Which data type is used to store text?






3๏ธโƒฃ What is the correct way to get input from the user?






4๏ธโƒฃ What operator is used to find the remainder of division?






5๏ธโƒฃ What does the following code print if age = 20?

if (age >= 18) {
  cout << "Adult";
} else {
  cout << "Minor";
}






๐ŸŽฎ C++ Game Development

C++ is one of the best languages for building games โ€” it's fast, powerful, and used in big-name engines like Unreal Engine and Cocos2d-x.

๐Ÿงฉ What Youโ€™ll Learn

  • How games are made with C++
  • Popular game development libraries
  • Building a simple console game

โš™๏ธ 1๏ธโƒฃ How C++ Is Used in Games

Most modern game engines use C++ because it gives full control over memory and performance. For example, Unreal Engine (used for games like Fortnite) is fully written in C++.

๐Ÿงฐ 2๏ธโƒฃ Popular Game Libraries for C++

  • SFML (Simple and Fast Multimedia Library) โ€” for 2D games and graphics
  • SDL (Simple DirectMedia Layer) โ€” used for input, sound, and rendering
  • OpenGL โ€” used for 3D graphics
  • Unreal Engine โ€” professional AAA game engine built with C++

๐Ÿ•น๏ธ 3๏ธโƒฃ Example: Number Guessing Game in C++

Letโ€™s start with a small console-based game to practice logic and loops. This game picks a random number, and the player must guess it!

#include <iostream>
#include <cstdlib>     // For rand() and srand()
#include <ctime>       // For time()

using namespace std;

int main() {
    srand(time(0)); // Seed random number generator
    int secretNumber = rand() % 10 + 1; // Random number between 1 and 10
    int guess;
    int tries = 0;

    cout << "๐ŸŽฏ Welcome to the Number Guessing Game!" << endl;
    cout << "I'm thinking of a number between 1 and 10..." << endl;

    do {
        cout << "Enter your guess: ";
        cin >> guess;
        tries++;

        if (guess > secretNumber)
            cout << "Too high! Try again.\n";
        else if (guess < secretNumber)
            cout << "Too low! Try again.\n";
        else
            cout << "๐ŸŽ‰ Congratulations! You guessed it in " << tries << " tries.\n";

    } while (guess != secretNumber);

    return 0;
}
  

๐Ÿ’ก Explanation:

  • srand(time(0)) seeds the random number generator so the number changes each time.
  • rand() % 10 + 1 generates a random number between 1 and 10.
  • A do-while loop repeats until the correct number is guessed.

๐Ÿš€ Next Steps

  • Try expanding the game โ€” add score limits or levels.
  • Learn SFML to make graphical games (draw characters, play sounds, etc.).
  • Build a small 2D game like Pong or Snake.

Keep practicing โ€” every big game started as a simple idea coded line by line.


๐ŸŽฎ C++ Game Development

C++ is one of the best languages for building games โ€” it's fast, powerful, and used in big-name engines like Unreal Engine and Cocos2d-x.

๐Ÿงฉ What Youโ€™ll Learn

  • How games are made with C++
  • Popular game development libraries
  • Building a simple console game

โš™๏ธ 1๏ธโƒฃ How C++ Is Used in Games

Most modern game engines use C++ because it gives full control over memory and performance. For example, Unreal Engine (used for games like Fortnite) is fully written in C++.

๐Ÿงฐ 2๏ธโƒฃ Popular Game Libraries for C++

  • SFML (Simple and Fast Multimedia Library) โ€” for 2D games and graphics
  • SDL (Simple DirectMedia Layer) โ€” used for input, sound, and rendering
  • OpenGL โ€” used for 3D graphics
  • Unreal Engine โ€” professional AAA game engine built with C++

๐Ÿ•น๏ธ 3๏ธโƒฃ Example: Number Guessing Game in C++

Letโ€™s start with a small console-based game to practice logic and loops. This game picks a random number, and the player must guess it!

#include <iostream>
#include <cstdlib>     // For rand() and srand()
#include <ctime>       // For time()

using namespace std;

int main() {
    srand(time(0)); // Seed random number generator
    int secretNumber = rand() % 10 + 1; // Random number between 1 and 10
    int guess;
    int tries = 0;

    cout << "๐ŸŽฏ Welcome to the Number Guessing Game!" << endl;
    cout << "I'm thinking of a number between 1 and 10..." << endl;

    do {
        cout << "Enter your guess: ";
        cin >> guess;
        tries++;

        if (guess > secretNumber)
            cout << "Too high! Try again.\n";
        else if (guess < secretNumber)
            cout << "Too low! Try again.\n";
        else
            cout << "๐ŸŽ‰ Congratulations! You guessed it in " << tries << " tries.\n";

    } while (guess != secretNumber);

    return 0;
}
  
โ–ถ๏ธ Try This Game in Browser

๐Ÿ’ก Explanation:

  • srand(time(0)) seeds the random number generator so the number changes each time.
  • rand() % 10 + 1 generates a random number between 1 and 10.
  • A do-while loop repeats until the correct number is guessed.

๐Ÿš€ Next Steps

  • Try expanding the game โ€” add score limits or levels.
  • Learn SFML to make graphical games (draw characters, play sounds, etc.).
  • Build a small 2D game like Pong or Snake.

Keep practicing โ€” every big game started as a simple idea coded line by line.


๐ŸŽฎ Play C++ Console Game (In Browser)

Welcome to the Number Guessing Game! I'm thinking of a number between 1 and 10... Type your guess below ๐Ÿ‘‡

๐Ÿ’ฐ C++ in Finance and Banking

C++ plays a major role in finance, banking, and stock trading systems because of its speed and accuracy. Itโ€™s used to build trading engines, financial modeling systems, and secure transaction platforms.

๐Ÿฆ Why Finance Companies Use C++

  • โšก Speed: C++ executes millions of calculations per second โ€” perfect for trading and risk analysis.
  • ๐Ÿง  Precision: Handles large numbers, interest rates, and currency conversions accurately.
  • ๐Ÿ”’ Security: Gives full control of memory, preventing hacking or data leaks.
  • ๐Ÿ“ˆ Scalability: Can run complex systems like stock exchanges or bank servers efficiently.

๐Ÿ’ก Example: Simple Interest Calculator in C++

#include <iostream>
using namespace std;

int main() {
    double principal, rate, time, interest;

    cout << "๐Ÿ’ฐ Enter principal amount: ";
    cin >> principal;

    cout << "๐Ÿ“Š Enter rate of interest (%): ";
    cin >> rate;

    cout << "โฑ๏ธ Enter time (in years): ";
    cin >> time;

    interest = (principal * rate * time) / 100.0;

    cout << "----------------------------------" << endl;
    cout << "Simple Interest = " << interest << endl;
    cout << "Total Amount = " << principal + interest << endl;
    cout << "----------------------------------" << endl;

    return 0;
}
  

๐Ÿง  Explanation:

  • principal โ†’ The amount borrowed or invested.
  • rate โ†’ The interest rate (in percent).
  • time โ†’ Duration in years.
  • Formula โ†’ (Principal ร— Rate ร— Time) / 100

๐Ÿ’น Try the Finance Game Below

This small simulator shows how your interest grows over time โ€” all in your browser!

๐Ÿ’ฐ Welcome to the Finance Calculator! Enter your values below ๐Ÿ‘‡

๐Ÿค– C++ for Robotics

C++ is the main language used in robotics programming because it can directly control hardware (motors, sensors, and cameras). It runs fast and gives precise control over memory and timing โ€” which is very important for robots.

โš™๏ธ What Robots Use C++

  • ๐Ÿš— Self-driving cars (Tesla, Waymo)
  • ๐Ÿฆฟ Industrial robots (used in factories)
  • ๐Ÿš Drones and flying robots
  • ๐Ÿค– Service robots (that move and talk)

๐Ÿ’ก Why C++ is Used

  • โœ… Real-time control of hardware
  • โœ… High performance for calculations
  • โœ… Works with robotics libraries like ROS (Robot Operating System)
  • โœ… Can combine with Python for AI + movement control

๐Ÿงฉ Example: Simple Robot Simulation

This code shows a simple robot simulation in C++. The robot moves forward, turns, and checks for obstacles.

#include <iostream>
using namespace std;

class Robot {
public:
    void moveForward() {
        cout << "๐Ÿค– Moving forward..." << endl;
    }

    void turnLeft() {
        cout << "โ†ฉ๏ธ Turning left..." << endl;
    }

    void detectObstacle(bool obstacle) {
        if (obstacle) {
            cout << "๐Ÿšง Obstacle detected! Turning left..." << endl;
            turnLeft();
        } else {
            moveForward();
        }
    }
};

int main() {
    Robot r1;
    r1.detectObstacle(false);
    r1.detectObstacle(true);
    r1.detectObstacle(false);
    return 0;
}
  

๐Ÿ’ฌ Output (in console):
๐Ÿค– Moving forward...
๐Ÿšง Obstacle detected! Turning left...
โ†ฉ๏ธ Turning left...
๐Ÿค– Moving forward...

๐Ÿš€ How It Works

  1. Class Robot defines actions like moving and turning.
  2. detectObstacle() checks if something is blocking the way.
  3. The robot decides what to do โ€” just like a real robot brain.

๐Ÿค– C++ for Robotics

C++ is one of the main languages used in robotics programming because it can directly control hardware like motors, sensors, and cameras. It runs fast and gives real-time control โ€” which is very important for robots.

โš™๏ธ What Robots Use C++

  • ๐Ÿš— Self-driving cars (Tesla, Waymo)
  • ๐Ÿฆฟ Industrial robots (factory arms)
  • ๐Ÿš Drones and flying robots
  • ๐Ÿค– Service robots (that move and talk)

๐Ÿ’ก Why C++ is Used

  • โœ… Real-time hardware control
  • โœ… Fast and efficient for calculations
  • โœ… Works with ROS (Robot Operating System)
  • โœ… Can combine with Python for AI and sensors

๐Ÿงฉ Example: Simple Robot Simulation

This example shows a simple robot simulation that moves and reacts to obstacles.

#include <iostream>
using namespace std;

class Robot {
public:
    void moveForward() {
        cout << "๐Ÿค– Moving forward..." << endl;
    }

    void turnLeft() {
        cout << "โ†ฉ๏ธ Turning left..." << endl;
    }

    void detectObstacle(bool obstacle) {
        if (obstacle) {
            cout << "๐Ÿšง Obstacle detected! Turning left..." << endl;
            turnLeft();
        } else {
            moveForward();
        }
    }
};

int main() {
    Robot r1;
    r1.detectObstacle(false);
    r1.detectObstacle(true);
    r1.detectObstacle(false);
    return 0;
}
  
Console Output:

๐Ÿค– C++ for Robotics โ€“ Smart Maze Simulation

In real robotics, C++ helps robots make smart movement decisions when avoiding obstacles. Below is a browser simulation that mimics that logic โ€” the robot detects multiple obstacles and finds a new path every time!

๐Ÿค–
๐Ÿšง
๐Ÿšง
๐Ÿšง
Console Output:

๐Ÿ’ก The Power of C++

C++ is more than just a programming language โ€” itโ€™s the foundation of modern technology. From high-speed financial systems ๐Ÿ’ฐ to advanced robotics ๐Ÿค–, from 3D games ๐ŸŽฎ to operating systems ๐Ÿ’ป, C++ is everywhere.

Learning C++ gives you the power to build software that is fast, reliable, and limitless. Every line of code you write can shape the future of technology.

What You Can Build with C++:

  • ๐Ÿš€ High-performance apps & operating systems
  • ๐ŸŽฎ 3D Games and Game Engines
  • ๐Ÿค– Robotics and AI systems
  • ๐Ÿ’น Financial trading software
  • ๐ŸŒ Compilers, browsers, and large-scale systems

Start Your Journey Today

Every expert once wrote their first #include <iostream>. Keep learning, keep building โ€” and let C++ power your imagination.

๐Ÿง  C++ Master Quiz

Test your knowledge from all the sections youโ€™ve learned โ€” Basics, Game Development, Finance, Robotics, and the Power of C++!

1๏ธโƒฃ What is C++ mainly used for?



2๏ธโƒฃ In game development, what role does C++ play?



3๏ธโƒฃ How is C++ used in finance?



4๏ธโƒฃ In robotics, what does C++ help control?



5๏ธโƒฃ What makes C++ so powerful?