1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
1

C++ Tutorial for Beginners

Updated on 18/09/2024440 Views

C++ is one of the most powerful programming languages out there. Why? It is definitely my go-to choice for developing advanced infrastructure or powerful software.

There are many solid programming languages out there but C++ is often significantly faster than Python and Java due to its static typing, compilation into native machine code, and direct control over memory. This makes it ideal for performance-critical applications.

C++ grants low-level access to hardware, making it a favorite for embedded systems, device drivers, or applications where direct hardware interaction is needed. Unlike other programming languages that might be better suited for building native mobile apps or web applications, C++ lets us develop enterprise-level software that works with sensors and hardware such as in factories, laboratories, and production units.

The C++ programming language is the successor of C and is also great for developing applications or models that require multi-level backends. 

I feel that learning C++ is also a great way of mastering object-oriented programming and learning essential OOP concepts. Let us learn the basics of this amazing programming technology with this C++ tutorial and start coding in C++.

Introduction to C++ language

C++ is a very powerful computing technology that is known for its speed, efficiency, and flexibility. This programming language is used in everything from game engines and operating systems to scientific simulations.

C++ fully supports object-oriented programming. This makes it great for building large, complex software systems in a way that's organized, reusable, and easier to maintain. OOP is a programming style that centers around creating 'objects'.

Objects package data (like characteristics) and the code that manipulates that data (like actions) into neat little bundles. Take an object like a car, for instance, and this car would have different parameters for data and code such as:

  • Data: Color, model, fuel level
  • Code: Drive, brake, refuel

Hello World Program in C++ Tutorial

Hello World program in C++

Code:

#include <iostream>

int main() {

    std::cout << "Hello, World!" << std::endl;

    return 0;

}

How do we run this? We first save the code as a .cpp file (e.g., hello.cpp). Then, we need a C++ compiler (OnlineGDB or g++). We can use the command line in our OS or the code editor's tools to compile the above code. Finally, we can run the executable file that is generated after compilation, and you should see "Hello, World!" printed on your console.

Here is a quick explanation of the above code and its syntax:

  • #include <iostream>: This line includes the iostream header file. This provides the necessary functionalities for input/output operations like cin (standard input) and cout (standard output) used for getting user input and displaying output on the console.
  • int main() {: This defines the main function. Every C++ program must have a main function, it's where our program's execution begins.
  • std::cout << "Hello, World!" << std::endl;: This line does the actual printing:
    • std::cout: The standard output stream object (think of it as the channel to send text to the console).
    • <<: The insertion operator, used to send data to std::cout.
    • "Hello, World!": The text string to be displayed.
    • std::endl: Inserts a newline character, moving the cursor to the next line on the console for future output.
  • return 0;: Indicates the program exited successfully. A return value of 0 traditionally signals "no errors."

Learning C++ Programming for Beginners and C++ Syntax Guide

Let me first teach you the core concepts of C++ before going into its syntax and how to use it. There are 4 foundational concepts that are very crucial for using C++, these are:

1. Classes and Objects

  • Class: Think of a class as a blueprint or design. It defines the data an object will hold (its attributes) and the actions it can perform (its methods).

Example: class Car { /* data and methods go here */ }

  • Object: An instance of a class. It's the real-world thing the blueprint describes.

Example: Car myToyota; // 'myToyota' is an object of the 'Car' class

2. Encapsulation

The bundling of data and the functions that operate on that data within an object is known as encapsulating data. Encapsulation protects data from accidental changes by outside code and promotes organization.

Example: You can't directly change the fuel level of a Car object, you have to use the refuel() method.

3. Inheritance

Inheritance is the creation of new classes (derived classes) from existing ones (base classes). These derived classes then inherit properties and behaviors from their base classes. Inheritance promotes code reusability and helps us in modeling hierarchical relationships (e.g., different types of vehicles can all inherit from a general Vehicle class).

4. Polymorphism

Polymorphism refers to "Many forms.", similarly, polymorphism in C++ and object-oriented programming is the ability of objects of different classes to respond to the same method call in different ways. This makes your code more flexible and adaptable.

Example: Having a drive() method in a base Vehicle class that is implemented differently in Car, Truck, and Motorcycle derived classes.

C++ Programming Examples

Even or Odd

Even or odd program in C++

Code:

#include <iostream>

int main() {

    int number;

    std::cout << "Enter an integer: ";

    std::cin >> number;

    if (number % 2 == 0) {

        std::cout << number << " is even." << std::endl;

    } else {

        std::cout << number << " is odd." << std::endl;

    }

    return 0;

}

Explanation:

  • int number;: This declares an integer variable named number to store the number entered by the user.
  • std::cout << "Enter an integer: ";: This line prints a message to the console asking the user to enter an integer.
  • std::cin >> number;: This line reads the integer value entered by the user and stores it in the number variable.
  • if (number % 2 == 0) { ... } else { ... }: This is an if-else conditional statement. It checks if the remainder (%) when number is divided by 2 is equal to 0. If it is, the number is even; otherwise, it's odd.
    • number % 2 == 0: This condition checks for divisibility by 2. If the remainder is 0, the number is even.
    • The code within the if block: If the condition is true (number is even), this block executes, printing a message saying the number is even.
    • The code within the else block: If the condition is false (number is odd), this block executes, printing a message saying the number is odd.

Calculating Area of a Circle

Calculating area of a circle program in C++

Code:

#include <iostream>

int main() {

    const double PI = 3.14159;

    double radius;

    std::cout << "Enter the radius of the circle: ";

    std::cin >> radius;

    double area = PI * radius * radius;

    std::cout << "The area of the circle is: " << area << std::endl;

    return 0;

}

Explanation:

  • const double PI = 3.14159;: This line declares a constant variable named PI of type double and assigns it the value of pi (3.14159). const makes the value of pi unchangeable throughout the program.
  • double radius;: This declares a double variable named radius to store the radius value entered by the user. double is used for floating-point numbers (numbers with decimals).

Generating Fibonacci Numbers

Generating Fibonacci numbers program in C++

Code:

#include <iostream>

int main() {

    int numTerms;

    std::cout << "Enter the number of Fibonacci terms: ";

    std::cin >> numTerms;

    int first = 0, second = 1, next;

    std::cout << "Fibonacci Series: ";

    for (int i = 1; i <= numTerms; ++i) {

        std::cout << first << ", ";

        next = first + second;

        first = second;

        second = next;

    }

    return 0;

}

Explanation:

  • for (int i = 1; i <= numTerms; ++i): This is the for loop that iterates for the specified number of numTerms.

Here's how it works:

  • Initialization: int i = 1: declares a loop counter variable i and initializes it to 1 (we start counting from the 1st term).
  • Condition: i <= numTerms: The loop continues as long as i is less than or equal to the desired numTerms.
  • Increment: ++i: After each iteration, the value of i is incremented by 1.

Inside the loop:

  • std::cout << first << ", ";: Prints the current value of the variable first (a Fibonacci number) followed by a comma.
  • next = first + second;: Calculates the next Fibonacci number by adding the first and second values, then stores the result in next.
  • first = second;: Updates the value of first. The old value in second becomes the new first for the next loop iteration.
  • second = next;: Updates the value of second. The next number, just calculated, becomes the new second for the next loop iteration.

If you wish to master C++, you can enroll in one of upGrad’s software engineering courses.

The Standard Template Library (STL)

The STL is a vast collection of pre-written, rigorously tested C++ code for common data structures, algorithms, and utilities. The STL relies heavily on templates, allowing it to work with a wide variety of data types without you having to write type-specific code.

Key concepts

A. Containers: These are ways to organize and store collections of data.

There are two types of containers:

  1. Sequence Containers: Store elements in a linear order.
  • vector: Dynamic array (grows/shrinks as needed).
  • list: Doubly linked list (good for insertions/removals in the middle).
  • deque: Double-ended queue (efficient additions/removals at front or back).
  1. Associative Containers: Store elements sorted by a key, allowing for fast lookups.
  • set: Stores unique elements in sorted order.
  • map: Stores key-value pairs (like a dictionary).
  • Container Adaptors: Modified versions of existing containers with specialized behavior (e.g., stack, queue).

B. Algorithms: Pre-written functions for performing operations on data within containers.  

Examples:

  • sort: Sorts elements within a range.
  • find: Searches for an element.
  • transform: Modifies elements according to a provided function.

C. Iterators: The glue between algorithms and containers. Iterators are objects that point to elements within containers, letting algorithms navigate and manipulate the data.

Example of using STL

Using Standard Template Library example in C++

Code:

#include <iostream>

#include <vector>

#include <algorithm>

int main() {

    std::vector<int> numbers = {3, 1, 5, 2, 4};

    std::sort(numbers.begin(), numbers.end());  // Sort the vector

    for (int num : numbers) {

        std::cout << num << " ";

    } 

}

Wrapping Up

According to me, C++ is definitely a programming language you should learn if you need maximum performance and precise control over hardware resources. C++ is also one of the best tools to learn if you want to learn a language with a long lifespan and lasting relevance in computing.

Sign up for a course with upGrad if you wish to learn the inner workings of programming languages and computing technologies.

FAQs

  1. Which tutorial is best for C++ programming?

According to me, learning C++ from upGrad’s computer science courses and programs would be the best. upGrad offers the best C++ tutorial for beginners.

  1. How much time do I need to learn C++?

It takes months to grasp the basics and years to achieve mastery, depending on your dedication and prior programming experience.

  1. What problems is C++ used for?

C++ is used for game development, operating systems, high-performance computing, embedded systems, and applications where speed and resource control are critical.

  1. What are the benefits of learning C++ first?

C++ teaches you low-level concepts and memory management, making it easier to understand how computers work and transition to other languages later.

  1. Which software is used to learn C++?

You'll need a C++ compiler (like g++ or clang++) and a code editor or IDE (Visual Studio, Code::Blocks, or CLion are popular).

  1. Which platform is best for learning C++?

Any modern OS (Windows, macOS, or Linux) is suitable for learning C++ and we can even use online compilers as well.

  1. What is C++ used for mostly?

C++ is primarily known for its use in developing performance-critical applications like games, operating systems, and system-level software.

  1. Which version of C++ is most used?

C++17 and C++20 are gaining popularity now (the latest standards) but older versions (C++11 and C++14) are still widely used in existing projects.

  1. What is the best platform to learn C++ for free?

You can learn C++ online for free through YouTube videos but I would suggest you enroll in a well-curated program such as the ones offered by upGrad.

Rohan Vats

Rohan Vats

Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming eng…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...