Neko

C++ Tutorial - 1

Introduction


For uni, I have to learn C++. So I thought it would be a good idea to write about what I have learned in the past few weeks and make a tutorial for others and myself, so I can come back, see my progress and share my experiences learning. If you have any recommendations please let me know. This is no introduction to programming itself but to C++ in particular. I am using clang++ and cmake, but g++ or everything else will be perfectly fine too.

This tutorial is an overview of C++ for people who learned C++ some time ago or have a little programming experience. However, I will try to make it as easy to understand as possible and there are “good-to-know” boxes with random information.

This this tutorial is not a

  • C tutorial –> if you are interested in C I highly recommend checking out Sapphic-Cafes tutorial or W3Schools
  • start to programming
  • complete guide to C++

1. Hello World

Let’s break down the fundamental “Hello World” program:

#include <iostream>

// main function starts here:
int main(){
  std::cout << "Hello there!" << std::endl;
}
  • #include <iostream>: This line allows us to use input and output functionalities in C++. The iostream library provides the tools for basic input and output operations. With #include NAME_OF_LIB you can include other libraries like the math library #include <cmath>
  • //: this is a comment in C++. They help document code and aren’t executed by the compiler.
  • int main() {}: The main() function is the entry point of a C++ program. It’s where the program begins its execution.
  • std::cout << "Hello there!" << std::endl; : Here, we’re using std::cout to display “Hello there!” on the console. std::endl is used to insert a newline character. In C++, std::endl explicitly denotes the end of a line, ensuring that the output appears immediately.

good-to-know The `std::` prefix is used to indicate that we're using elements (like `cout` and `endl`) from the `std` namespace. Namespaces help avoid naming conflicts by organizing code elements.

One could use the following line:

using namespace std;

This would allow us to not use std:: prefixes. But you should not do it. Explicitly using std:: ensures a clear context of the library elements being used, minimising naming conflicts in larger programs.


You can run the program in a terminal using this for example:

$ clang++ -std=c++17 -o hello_there hello_there.cpp 
$ ./hello_there
Hello there!

2. Types and Variables

In C++, data types include:

  • int: Represents integers, within a certain range depending on the system architecture (e.g., 32-bit or 64-bit). Typically an int is 4 bytes and ranges from -2147483648 to 2147483647
  • bool: Represents Boolean values - true or false.
  • double, float: These represent floating-point numbers with varying precision (double usually has higher precision than float).
  • char: Represents single characters or small integers. Typically 1 byte and ranges from -128 to 127 or 0 to 255.
  • wchar: Because this is char is way too small to store most characters, so wide char has a size of 2 to 4 bytes to represent more characters.
  • std::string: Represents a sequence of characters.

Variable Declaration and Initialization

In C++, declaring variables involves specifying the type and, optionally, assigning an initial value: You declare a variable using

TYPE NAME;

and optional

TYPE NAME = VALUE;

This would look like this:

int meaning_of_life;
meaning_of_life = 42;

bool isCodingFun = true;

double pi = 3.14159;

char grade;
grade = 'A';

std::string greeting = "Hello, World!";

Table of Data Types and Ranges (Optional)

Data Type Description Range
int Integer Typically 4 bytes
bool Boolean true or false
double Double-precision floating-point ±1.7E +/- 308 (15 digits)
float Single-precision floating-point ±3.4E +/- 38 (7 digits)
char Character Typically -128 to 127 or 0 to 255
std::string String Varies based on implementation

It is important to not start the variable name with a capitellatter and not with a number.


good-to-know
  • the underscore writing of variables is called snake_case: e.g. meaning_of_life
  • where as CamleCase is for example: e.g. isCodingFun
It is down to personal preferences what you prefer. I personally like CamleCase more because ot's shorter and easier to write.

Input with std::cin:

Now that we know how to declare a variable we can also save something To receive input from the user, we use std::cin:

std::cout << "Type a number: " << std::endl; 
// this code is shown above the place where the user can type in the terminal
int userInput;
std::cin >> userInput;

But for string, you will want to use getline(cin, VARIABLE_NAME) because std::cin >> VARIABLE_NAME; will just save everything before a space. So “Hello World” becomes “Hello”

std::string name;
std::cout << "What's your name? ";
getline(std::cin, name);
std::cout << std::endl;
std::cout << "Hi, " << name << std::endl;

3. Operations

Arithmetic Operators

  • +: Addition 5+5=10
  • -: Subtraction 4-2=2
  • *: Multiplication 4*2=8
  • /: Division 42/2 = 21
  • %: Modulo (Remainder after division) 42%2 = 0
  • ++a, a++, a--, --a: Increment and Decrement Operators
  • +=, -=, *=, /=, %=: Compound Assignment Operators

Increment and Decrement Operators:

  • ++a (pre-increment): This operator increments the value of a before using its updated value in an expression.
  • a++ (post-increment): This operator increments the value of a but uses its original value in an expression and then updates a.
  • a-- (post-decrement): This operator decrements the value of a but uses its original value in an expression and then updates a.
  • --a (pre-decrement): This operator decrements the value of a before using its updated value in an expression.
int a = 5;
int b = a--; // b is assigned the value of 'a' before it's decremented by 1
// b = 5
// a = 4
int c = ++b; // c is assigned the value of 'a' after it's incremented by 1
// a = 5
// c = 5

Compound Assignment Operators

  • +=: Adds the value on the right side to the variable on the left side and assigns the result to the variable on the left side. Equivalent to a = a + b;
  • -=: Equivalent to a = a - b;
  • *=: Equivalent to a = a * b;
  • %=: Equivalent to a = a % b;

For example:

int a = 10;
a += 5; // equivalent to a = a + 5;
// a = 15

a *= 2; // equivalent to a = a * 2;
// a = 30

a %= 7; // equivalent to a = a % 7;
// a = 2

These operators offer a concise way to perform an operation and update the value of a variable in one step, commonly used in loops, calculations, and assignments in programming.

Logical Operators

  • &&: Logical AND
  • ||: Logical OR
  • ^: Logical XOR (Exclusive OR)
  • !: Logical NOT (Negation)

instead of &&, || and ! you can also just type and, or, not which I prefer because it makes the code more readible

4. Control Flow (if-else and loops)

Control flow structures in C++ dictate how a program progresses through conditional statements and loops:

Conditional Statements

  • if, else if, else: Used for decision-making based on conditions.

Example:

int x = 10;
if (x > 0) {
    // Do something
} else if (x < 0) {
    // Do something else if x<0
} else {
    // Do this if none of the above conditions are met
}

Looping Constructs

  • for: Executes a block of code repeatedly for a specified number of times.

Example:

for (int i = 0; i < 5; ++i) {
    // Do something repeatedly for 5 times
}
  • while: Executes a block of code as long as the specified condition is true.

Example:

int count = 0;
while (count < 10) {
    // Do something while the count is less than 10
    ++count;
}
  • do-while: Executes a block of code at least once, and then repeats it as long as the specified condition is true.

Example:

int num = 5;
do {
    // Do something
    --num;
} while (num > 0);

These control flow structures allow programmers to implement decision-making and repetition within their programs, enabling dynamic and adaptive behaviour.

Wrapping it Up

Armed with the fundamentals of C++ covered in this tutorial, and a sprinkle of insights from StackOverflow, you’re now equipped to craft straightforward programs like the one demonstrated below:

#include <iostream>
#include <string>
#include <algorithm> // for std::transform
#include <cctype>    // for std::tolower

int main() {
    // Declare variables
    bool rightAnswer = false;
    std::string answer;

    // While the answer is not a correct one
    while (!rightAnswer) {
      // Prompt the user and get input
        std::cout << "Hello there!" << std::endl;
        std::getline(std::cin, answer);
        
        // Convert the user's input to lowercase for case-insensitive comparison
        std::transform(answer.begin(), answer.end(), answer.begin(), 
        [](unsigned char c) { return std::tolower(c); });

       // Check if the answer matches predefined correct responses
        if (answer == "general kenobi") {
            // Display message for correct response
            std::cout << "You are a bold one *coughs in cyber*" << std::endl;
            
            // Set the flag to exit the while loop
            rightAnswer = true;
        }
        else if (answer == "beebop") {
          // Display message for another correct response
            std::cout << "Come closer, little friend" << std::endl;
            // If it is a right answer set variable to true so the while loop ends
            rightAnswer = true;
        } else{
          // We do nothing otherwise
          // You wouldn't need an 'else' here if you want to ignore other inputs
        }
    }
    return 0; // The End
}

Find the code here

In this program, the message “Hello there!” is continuously displayed in the terminal until an answer of “General Kenobi” or the older - but still accepted code - “Beebop” is provided. Harnessing these foundational concepts of variables, control flows, and user input handling, we are now prepared to dive deeper into more complex C++ functionalities in upcoming tutorials. Keep exploring and coding!

Additional Ressources


Next Tutorial >>>Part #2>>>