---
# System prepended metadata

title: Basic Functionality in C++
tags: [c++]

---

# C++ Common functions

Today's Overview: Some Basic functionalities commonly used in C++.
- Conditionals
- Loops
- Arrays
- Strings
- Next_Chapter
-- Function
-- Recursion
-- Structs
-- Class

---

## Conditionals

In `C++`, there are two main types of conditionals: if and switch. 
Most people tend to prefer using if.

### If

Let's start by taking a brief look at the structure of an `if` statement:


```cpp=
if (condition_1) {
    // Code to execute when the condition is true
}
else if (condition_2) {
    // Code to execute when the previous 'if' condition is false and this condition is true
}
else if (condition_3) {
    // Code to execute when the previous 'else if' condition is false and this condition is true
}
else {
    // Code to execute when none of the above conditions are true
}
```

You can see that in the code, the `if` statements are nested, with each level checking a condition one step deeper.

It's worth noting that there can be multiple `else if` statements, but there can only be one `else` statement, and they all must come after an `if` statement to be effective.

If multiple `if` statements are used instead, each `if` statement will be evaluated independently without interfering with each other. Unlike `else if`, where only one condition needs to be true for further evaluation to stop.

Of course, you can also nest if statements inside each other, as shown below:

```cpp=
if (condition_A) {
    if (condition_B) {
        // Code to execute when both conditions are true
    }
}
```

#### Multiple condition evaluation

If logical operators are used wisely, it's possible to evaluate multiple conditions in a single if statement.

```cpp=
//example
#include<iostream>
using namespace std;
int main()
{
    int n;
    cin >> n;
    if(n >= 0 && n % 4 == 0) // n is greater than or equal to 0 and divisible by 4
        cout << n << endl; // When there's only one instruction inside the if statement, curly braces are not required
    return 0;
}
```

### Switch

When you need to execute different code blocks based on different conditions, the switch statement in C++ is a useful tool. The switch statement allows you to select one or more code blocks to execute from a set of possible cases based on the value of an expression. This situation is commonly referred to as multi-branching, and the switch statement is used to achieve this behavior.

Here is the basic structure of a switch statement:

```cpp=
switch (expression) {
    case value1:
        // Execute this code block when expression equals value1
        break;
    case value2:
        // Execute this code block when expression equals value2
        break;
    // There can be more case statements
    default:
        // Execute this code block if the value of expression does not match any of the case values
        break;
}
```

The `expression` in a `switch` statement can be any value that can be used for comparison, such as `int`,`float`, or `char`.

The `value` following each `case` can be a constant value or a constant expression.

When the `expression` matches a `value` following a `case`, the corresponding code block will be executed. Then, the program will exit the switch statement unless the `break` statement is used at the end of the `case` block. Without the `break` statement, the program will continue to execute the next `case` block.

If the `expression` value does not match any of the `values` following the `cases`, the code inside the default block will be executed. The default block is optional, and if it's not present, and if the `expression` value doesn't match any of the `case` values, the switch statement won't execute any code, and the program will continue to the next statement.

The `break` statement is used to end the switch statement and return program control to the code after the switch statement. Without a `break` statement, the program will continue executing the next `case` block in the switch statement, which is referred to as "fall-through" behavior.

## Loops

Loops are very important as they allow your program to repeat a block of code multiple times. In `C++`, there are three main types of loops available: `for`, `while`, and `do-while`. Among these, `for` and `while` loops are commonly used.

### For Loop


The `for` loop is the most commonly used loop in `C++`.
If the number of repetitions is known beforehand, the `for` loop is the preferred choice.

```cpp=
for (initialization; condition; update) {
    // Loop body; the code to be repeated
} // No semicolon after the closing brace.
```

If we want to calculate the sum from 1 to 100, we can use a `for` loop.

```cpp=
int sum = 0;
for (int i = 0; i <= 100; i++) {
    sum += i;
}
```

---

### While Loop

The `while` loop is also commonly used when the number of repetitions is not known beforehand. In such cases, both the `while` loop and the `do-while` loop are considered.

```cpp=
while (condition) {
    loop_body;
    update_increment_decrement;
} // No semicolon after the closing brace.
```

If we want to calculate the sum from 1 to n, we can use a `while` loop.

```cpp=
int n, i = 1, sum = 0;
cin >> n;
while (i <= n) {
    sum += i;
    i++;
}
```

---

### Do-While Loop


The `do-while` loop is also used when the number of repetitions is not known beforehand. However, the `do-while` loop follows a "do first, then check" approach. This loop is the least used among the three loops in C++.
```cpp=
do {
    loop_body;
    update_increment_decrement;
} while (condition); // Don't forget the semicolon
```

If we want to calculate the sum from 1 to n, we can also use a `do-while` loop.

```cpp=
int n, i = 1, sum = 0;
cin >> n;
do{
    sum += i;
    i++;
} while (i <= n)
```

---

### break

`break` is indeed a commonly used construct, especially in conjunction with loops.

When we achieve a certain condition inside a loop that fulfills our requirement, we can use `break` afterward. This will immediately exit the loop, preventing unnecessary time or memory consumption and avoiding potential infinite loops. Let's use the `while` loop as an example:

```cpp=
int ans = 0;
unsigned int a;
for (int i = 0; i < 100000; i++) {
    cin >> a;
    ans += a;
    if (ans > 100) {
        cout << "answer is more than 100\n";
        break;
    }
}
```

Here, we want to check if ans exceeds 100. If it does, there's no point in continuing because ans will always exceed 100 regardless of any further operations. In this case, we can directly use `break`.

---

### Continue


`continue` is less commonly used compared to "break," but it's still important to learn.

`continue` will skip the remaining part of the current iteration of the loop and proceed to the next iteration. 

---

## Array


Arrays are containers that allow you to store multiple data of the same data type in a single variable. They are used to avoid declaring multiple variables for similar types of data. Arrays are commonly used in conjunction with loops.

Declare an array:

```cpp=
int arr[4]; // Declare an array named arr with 4 slots of type int.
```

At this point, the array contains uninitialized values (garbage values). We can choose to initialize the array at the time of declaration or assign values to it in subsequent code. Here, I'll demonstrate the method of initializing the array at the time of declaration:

```cpp=
int arr[4] = {4, 3, 2, 1}; // Declare and initialize an array named arr with 4 elements: 1, 2, 3, 4.
```

| arr   | arr[0] | arr[1] | arr[2] | arr[3] |
| ----- | ------ | ------ | ------ | ------ |
| value | 4      | 3      | 2      | 1      |

### Array and Loop

Remember that `for` each iteration of the for loop, the parameters change accordingly. If we correlate this pattern with the indices of an array, we can efficiently traverse through every element of the array with just a few lines of code.
example:

```cpp=
int arr[100];
for(int i = 0; i < 100; i++) {
    arr[i] = i + 1;
}
//arr[0] = 1, arr[1] = 2 ... arr[99] = 100
```


### Multidimensional Arrays

When there is more than one set of square brackets after a variable, we can create a multidimensional array. Here's an example of how to declare one:

```cpp=
int arr[2][3]; // Declare a 2x3 array.
```



| arr       | arr[x][0] | arr[x][1] | arr[x][2] |
| --------- | --------- | --------- | --------- |
| arr[0][y] |           |           |           |
| arr[0][y] |           |           |           |

---

## String

Strings have the following characteristics:

- The string type supports character arrays with variable lengths.
- It provides a large number of functions.
- It belongs to the `C++` STL container library.
- Programs using strings must first include the function library `#include <string>`.

Define a string and initialize it:

```cpp=
string str1;                 // str1 will be an empty string
cout << str1 << '\n';        //

string str2 = "NCCU";       // Initialize str2 with a copy of the string literal
cout << str2 << '\n';        // NCCU

string str3("NCCU");        // Initialize str3 with a copy of the string literal
cout << str3 << '\n';        // NCCU

string str4(str3);           // Initialize str4 with a copy of str3
cout << str4 << '\n';        // NCCU

string str5(5, 'f');         // Initialize str5 with 5 'f's
cout << str5 << '\n';        // fffff
```

In practice, you'll mostly use the first and second methods.

Read in a string:

```cpp=
string str1, str2, str3;
cin >> str1;                 // Reads a whitespace-separated or newline-terminated string into str1
getline(cin, str2);          // Reads an entire line of text into str2 
cin.get(str3);               // Reads a single character into str3
```

### String Arrays

Because strings can be accessed like arrays, you can also use subscripts to obtain specific values. In fact, strings are arrays of characters.

```cpp=
string str = "NCCU";
cout << str[0] << '\n'; // 'N'
cuot << str[2] << '\n'; // 'C'
```