Essential C++ Programming Exercises and Solutions

Computer science3.54 KB

C++ Programming Exercises

This collection contains various C++ algorithms and solutions for common programming tasks.

1. Countdown Sequence

#include <iostream>
using namespace std;
int main() {
    int x, y = 0;
    cin >> x;
    while (x >= 0) {
        cout << y << endl;
        y = y + 1;
        x = x - 1;
    }
}

2. Harmonic Numbers

#include <iostream>
using namespace std;
int main() {
    cout.setf(ios::fixed);
    cout.precision(4);
    double h = 0;
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        h = h + 1.0 / i;
    }
    cout << h << endl;
}

3. Descending Interval

#include <iostream>
using namespace std;
int main() {
    int x, y;
    cin >> x >> y;
    if (x > y) {
        int a = x;
        x = y;
        y = a;
    }
    while (x <= y) {
        cout << y << endl;
        y = y - 1;
    }
}

4. Numbers in an Interval

#include <iostream>
using namespace std;
int main() {
    int x, y;
    cin >> x >> y;
    if (x < y) {
        while (x != y) {
            cout << x << ',';
            x = x + 1;
        }
        cout << x << endl;
    } else {
        if (x == y) cout << x << endl;
        else cout << endl;
    }
}

5. Cubes Sequence

#include <iostream>
using namespace std;
int main() {
    int x, i;
    cin >> x;
    for (i = 0; i < x; i++) {
        cout << i * i * i << ',';
    }
    cout << i * i * i << endl;
}

6. Multiplication Table

#include <iostream>
using namespace std;
int main() {
    int numero;
    cin >> numero;
    for (int i = 1; i <= 10; i++) {
        cout << numero << "*" << i << " = " << numero * i << endl;
    }
}

7. Reverse String

#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main() {
    char ch;
    string cadena, cadenab;
    while ((ch = getchar()) != '\n') {
        cadena += ch;
    }
    for (int i = cadena.length(); i > 0; i--) {
        cadenab += cadena[i - 1];
    }
    cout << cadenab << endl;
}

8. Digit Count

#include <iostream>
using namespace std;
int main() {
    int n, x, d = 0;
    cin >> n;
    x = n;
    if (n == 0) cout << "El nombre de digits de " << n << " es 1." << endl;
    else {
        while (n > 0) {
            d = d + 1;
            n = n / 10;
        }
        cout << "El nombre de digits de " << x << " es " << d << '.' << endl;
    }
}

9. Counting 'a' Characters

#include <iostream>
using namespace std;
int main() {
    char c;
    int n = 0;
    cin >> c;
    while (c != '.') {
        if (c == 'a') {
            n = n + 1;
        }
        cin >> c;
    }
    cout << n << endl;
}

10. Greatest Common Divisor (GCD)

#include <iostream>
using namespace std;
int main() {
    int x, y, a, b;
    cin >> x >> y;
    a = x; b = y;
    while (x != y) {
        if (x > y) x = x - y;
        else y = y - x;
    }
    cout << "El mcd de " << a << " i " << b << " es " << x << "." << endl;
}

Download

PDF Word HTML