C++ Code Examples Tutorial – Complete Guide

The dynamic world of programming is full of diverse languages, each with its own unique strengths and uses. One such language that consistently remains a mainstay is C++. But *what exactly is C++ and why should you learn it?*

What is C++?

C++ is a high-level programming language developed by Bjarne Stroustrup at Bell Labs. It’s an extension of the C programming language, with additional features such as classes, which support the Object-Oriented Programming (OOP) paradigm.

What is C++ Used For?

As a general-purpose programming language, C++ is incredibly versatile. It’s used in many areas that demand efficiency and fine-grained control over system resources, including,

  • Game development,
  • Real-time systems,
  • Embedded systems,
  • Performance-critical applications, and
  • Creating large systems, like browsers or databases.

Why Learn C++?

The importance of learning C++ can’t be overstated. Alongside its wide usage and demand in the industry, it’s known for its efficiency and scalability. Here are some reasons why you might want to learn C++:

  • Performance: C++ lets you have very fine control over system resources and memory management which makes it a powerful choice for performance-critical applications.
  • Object-Oriented Programming (OOP): It offers a rich set of features such as classes, inheritance, and polymorphism that support the OOP paradigm, hence enabling better organization and maintainability of code.
  • Learning Path: C++ provides a solid foundation for learning other programming languages. Once you learn C++, picking up other languages like Java or C# becomes relatively easy.

Now that you understand the relevance of C++, let’s dive into some C++ code examples.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

C++ Basics: Syntax, Variables and Data Types

Let’s start our journey into coding with C++ by discussing some of the basics, including syntax, variables, and data types.

Example: Hello World in C++

To start with, let’s take a look at how we can print “Hello World!” in C++.

#include<iostream>

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

In this snippet, we include the `iostream` library which provides basic input-output services. The `main` function is where our program starts execution, and `std::cout` is used to print onto the console.

Variables and Data Types

Next, let’s explore C++’s variable declaration and different data types.

#include<iostream>

int main() {
    int num = 10;
    float decimalNum = 20.5;
    char letter = 'a';
    bool isTrue = false;

    std::cout << "Integer: " << num << "\n";
    std::cout << "Float: " << decimalNum << "\n";
    std::cout << "Character: " << letter << "\n";
    std::cout << "Boolean: " << isTrue;

    return 0;
}

In C++, it’s important to declare the type of variable before using them. In the above snippet, `num` is of type `int`, `decimalNum` of type `float`, `letter` of type `char`, and `isTrue` of type `bool`.

Operators and Conditional Statements in C++

C++ has a variety of built-in operators and features for controlling program flow including if-else statements and loops. Let’s take a look.

#include<iostream>

int main() {
    int num1 = 10, num2 = 20;

    if(num1 < num2) {
        std::cout<< "num1 is less than num2";
   } else {
        std::cout << "num1 is not less than num2";
    }

    return 0;
}

In the above program, the if statement is used to compare `num1` and `num2`. The body of the if statement will only execute if the condition `num1 < num2` is true. If it's false, the code inside the else block will execute.

Loops in C++

Now that we’ve seen how to use conditionals, let’s move onto loops. C++ provides several loop structures including `for`, `while`, and `do` loops.

Let’s look at an example using a `for` loop to print numbers from 1 to 10.

#include<iostream>

int main() {
    for(int i = 1; i <= 10; i++) {
        std::cout << i << "\n";
    }
    return 0;
}

In this example, our `for` loop begins with `i` equal to 1 and continues until `i` is no longer less than or equal to 10. With each iteration, `i` is incremented by 1.

Let’s explore the `while` loop, which executes a block of code as long as the specified condition is true.

 
#include<iostream>

int main() {
    int i = 1;

    while (i <= 5) {
        std::cout << i << "\n";
        i++;
    }

    return 0;
}

Above, `i` begins at 1 and the loop executes until `i` is no longer less than or equal to 5.

Functions in C++

Functions are an integral part of C++, allowing us to group reusable code into a single place. Here’s a simple example:

#include<iostream>

int add(int a, int b) {
    return a + b;
}

int main() {
    std::cout << "Sum: " << add(5, 10);
    return 0;
}

We’ve defined an `add` function that takes two parameters, `a` and `b`, adds them, and returns the result. In the `main` function, we call `add` with values 5 and 10 and print the sum.

Classes and Objects in C++

Being an Object-Oriented Programming language, classes and objects are fundamental to C++. A Class defines the properties and behaviors (fields and methods) for the objects of that class.

Here’s an example:

#include<iostream>

class Dog {
public:
    std::string name;
    int age;

    void bark() {
        std::cout<< "Woof! My name is " << name;
    }
};

int main() {
    Dog myDog;
    myDog.name = "Buddy";
    myDog.bark();

    return 0;
}

In this example, we’ve defined a `Dog` class with a public field (`name`) and a public method (`bark`). In the main function, we create an object `myDog` of type `Dog`, assign Buddy to it, and call `bark` on `myDog`. This displays “Woof! My name is Buddy”.

Constructors in C++

Constructors are special methods in a class that are automatically called when you create an object of that class. They typically initialize class members. Here’s how we can add a constructor to our `Dog` class:

#include<iostream>

class Dog {
public:
    std::string name;
    int age;

    Dog(std::string n, int a) {
        name = n;
        age = a;
        std::cout << "Dog created: " << name << ", age " << age << "\n";
    }

    void bark() {
        std::cout<< "Woof! My name is " << name << "\n";
    }
};

int main() {
    Dog myDog = Dog("Buddy", 5);
    myDog.bark();

    return 0;
}

In this code, the constructor `Dog(std::string n, int a)` is called when we create a new `Dog` object. It’s used to initialize the `name` and `age` properties.

Pointers in C++

Pointers give you a way to directly manipulate memory. In C++, you can store the memory address of a variable in a pointer and you can access the variable directly by dereferencing the pointer.

Let’s take a look at a simple example:

#include<iostream>

int main() {
    int num = 10;
    int* p = &num;
    
    std::cout << "Value of num: " << *p<< "\n";
    std::cout << "Address of num: " << p;

    return 0;
}

In this code, `&num` is the address of `num`, and `*p` refers to the value at the address stored in `p`.

Arrays in C++

Arrays are used to store multiple values of the same type in a single variable. Here is an example:

#include<iostream>

int main() {
    int nums[5] = {1, 2, 3, 4, 5};

    for(int i = 0; i < 5; i++) {
        std::cout << nums[i] << "\n";
    }

    return 0;
}

Here, `nums` is an array of integers. We iterate over the array with a `for` loop and print each number.

Strings in C++

A string variable holds a sequence of characters. String handling in C++ is more user-friendly than in C.

Here’s an example of how we can use strings:

#include<iostream>
#include<string>

int main() {
    std::string greeting = "Hello World";
    
    std::cout << greeting;
    
    return 0;
}

This program defines a string `greeting` and then prints it.

Where to Go Next: Advancing Your C++ Learning

Now that you’ve had a taste of C++, you’re likely eager to continue expanding your knowledge and skills. At Zenva, we offer a variety of courses to help you on this journey. Whether you’re a beginner just getting started or an experienced programmer looking to refresh your C++ knowledge, we’ve got a course for you.

One of our highly recommended courses is the C++ Programming Academy. This comprehensive program provides an accessible avenue for learning C++ programming through building simple games. The skills gained have wide applicability, and can help open many opportunities in the multibillion-dollar game development market, as well as the broader industry.

Furthermore, we also offer a broad collection of C++ Courses that cater to a range of learning goals and skill levels. Our courses are designed to be flexible and accessible, allowing you to choose the learning materials that best suit your needs.

So why wait? Revolutionize your programming journey with Zenva today. Through our practical, project-based courses, you’ll gain the C++ expertise you need to take the next big step in your coding career. Join us and experience the joy of coding and game creation with our high-quality, engaging content.

Conclusion

C++ is a powerful, high-performance language that continues to shape the landscape of programming today. Its role in shaping operating systems, games, and complex applications renders it a worthy addition to your programming toolbox.

Embarking on the journey to mastering C++ might seem daunting, but remember – every journey begins with a single step. Let Zenva guide you on that journey. Check out our comprehensive C++ Programming Academy where you’ll experience our self-paced, project-based approach. Start your C++ journey with us today and embrace the world of opportunities that awaits.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.