C++ Cours

C++ Conditions and Loops

Tutoriel Python 3 pour débutants.

if / else if / else

#include <iostream>
using namespace std;

int main() {
    int score = 85;
    if (score >= 90) {
        cout << "A" << endl;
    } else if (score >= 80) {
        cout << "B" << endl;
    } else {
        cout << "F" << endl;
    }
    return 0;
}

Ternary Operator

int x = 10;
string result = (x % 2 == 0) ? "even" : "odd";
cout << result; // "even"

switch Statement

int day = 3;
switch (day) {
    case 1: cout << "Monday"; break;
    case 2: cout << "Tuesday"; break;
    case 3: cout << "Wednesday"; break;
    default: cout << "Other";
}

for Loop

for (int i = 0; i < 5; i++) {
    cout << "i = " << i << "
";
}

Range-Based for (C++11)

#include <vector>
vector<int> nums = {1, 2, 3, 4, 5};
for (int n : nums) {
    cout << n << " ";
}
// With auto:
for (auto& n : nums) {
    n *= 2;  // modify in-place with reference
}

while and do-while

int count = 0;
while (count < 3) {
    cout << count++ << "
";
}

int x = 10;
do {
    cout << x-- << "
";
} while (x > 0);

break and continue

for (int i = 0; i < 10; i++) {
    if (i == 5) break;      // exit loop
    if (i % 2 == 0) continue; // skip even
    cout << i << " ";  // prints 1 3
}