Tutorials Logic
Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

C++ Important Programs — Fibonacci, Sorting, Search

Classic C++ Programs

These programs cover the most commonly asked C++ problems in interviews and competitive programming. Each demonstrates key language features.

Fibonacci, Factorial, Prime Check
#include <iostream>
using namespace std;

// Iterative Fibonacci
void fibonacci(int n) {
    long long a = 0, b = 1;
    cout << "Fibonacci(" << n << "): ";
    for (int i = 0; i < n; i++) {
        cout << a << " ";
        long long c = a + b;
        a = b;
        b = c;
    }
    cout << endl;
}

// Recursive Fibonacci
long long fibRec(int n) {
    if (n <= 1) return n;
    return fibRec(n-1) + fibRec(n-2);
}

int main() {
    fibonacci(10);  // 0 1 1 2 3 5 8 13 21 34
    cout << "fib(10) = " << fibRec(10) << endl;  // 55
    return 0;
}
#include <iostream>
using namespace std;

long long factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

int main() {
    for (int i = 0; i <= 12; i++) {
        cout << i << "! = " << factorial(i) << endl;
    }
    return 0;
}
#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int n) {
    if (n < 2) return false;
    if (n == 2) return true;
    if (n % 2 == 0) return false;
    for (int i = 3; i <= sqrt(n); i += 2) {
        if (n % i == 0) return false;
    }
    return true;
}

int main() {
    cout << "Primes up to 50: ";
    for (int i = 2; i <= 50; i++) {
        if (isPrime(i)) cout << i << " ";
    }
    cout << endl;
    // 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
    return 0;
}
Palindrome, Reverse String, Anagram
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

bool isPalindrome(const string &s) {
    string rev = s;
    reverse(rev.begin(), rev.end());
    return s == rev;
}

bool isNumPalindrome(int n) {
    int original = n, reversed = 0;
    while (n > 0) {
        reversed = reversed * 10 + n % 10;
        n /= 10;
    }
    return original == reversed;
}

int main() {
    cout << boolalpha;
    cout << isPalindrome("racecar") << endl;  // true
    cout << isPalindrome("hello")   << endl;  // false
    cout << isNumPalindrome(121)    << endl;  // true
    cout << isNumPalindrome(123)    << endl;  // false
    return 0;
}
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

bool isAnagram(string a, string b) {
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
    return a == b;
}

int main() {
    cout << boolalpha;
    cout << isAnagram("listen", "silent") << endl;  // true
    cout << isAnagram("hello",  "world")  << endl;  // false
    cout << isAnagram("triangle", "integral") << endl;  // true
    return 0;
}
Bubble Sort, Binary Search, Matrix Multiplication
#include <iostream>
#include <vector>
using namespace std;

void bubbleSort(vector<int> &v) {
    int n = v.size();
    for (int i = 0; i < n-1; i++) {
        bool swapped = false;
        for (int j = 0; j < n-i-1; j++) {
            if (v[j] > v[j+1]) {
                swap(v[j], v[j+1]);
                swapped = true;
            }
        }
        if (!swapped) break;
    }
}

int binarySearch(const vector<int> &v, int target) {
    int lo = 0, hi = v.size() - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (v[mid] == target) return mid;
        if (v[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

int main() {
    vector<int> v = {64, 34, 25, 12, 22, 11, 90};
    bubbleSort(v);
    for (int n : v) cout << n << " ";  // 11 12 22 25 34 64 90
    cout << endl;

    cout << "Index of 25: " << binarySearch(v, 25) << endl;  // 2
    return 0;
}
#include <iostream>
using namespace std;

void multiplyMatrix(int A[][3], int B[][3], int C[][3], int n) {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            C[i][j] = 0;
            for (int k = 0; k < n; k++)
                C[i][j] += A[i][k] * B[k][j];
        }
}

int main() {
    int A[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    int B[3][3] = {{9,8,7},{6,5,4},{3,2,1}};
    int C[3][3];

    multiplyMatrix(A, B, C, 3);

    cout << "A x B:" << endl;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) cout << C[i][j] << "\t";
        cout << endl;
    }
    return 0;
}
GCD, LCM and Armstrong Number
#include <iostream>
using namespace std;

// GCD using Euclidean algorithm
int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

// LCM using GCD
long long lcm(int a, int b) {
    return (long long)a / gcd(a, b) * b;
}

int main() {
    cout << "GCD(48, 18) = " << gcd(48, 18) << endl;  // 6
    cout << "GCD(100, 75) = " << gcd(100, 75) << endl; // 25
    cout << "LCM(4, 6) = "   << lcm(4, 6)   << endl;  // 12
    cout << "LCM(12, 18) = " << lcm(12, 18) << endl;  // 36
    return 0;
}
#include <iostream>
#include <cmath>
using namespace std;

// Armstrong number: sum of digits^n == number
// e.g. 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
bool isArmstrong(int n) {
    int original = n, sum = 0, digits = 0;
    int temp = n;
    while (temp) { digits++; temp /= 10; }
    temp = n;
    while (temp) {
        int d = temp % 10;
        sum += pow(d, digits);
        temp /= 10;
    }
    return sum == original;
}

int main() {
    cout << "Armstrong numbers up to 1000:" << endl;
    for (int i = 1; i <= 1000; i++) {
        if (isArmstrong(i)) cout << i << " ";
    }
    cout << endl;
    // 1 2 3 4 5 6 7 8 9 153 370 371 407
    return 0;
}
Number to Binary, Simple Calculator
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string toBinary(int n) {
    if (n == 0) return "0";
    string result = "";
    bool negative = n < 0;
    if (negative) n = -n;
    while (n > 0) {
        result += (char)('0' + n % 2);
        n /= 2;
    }
    if (negative) result += '-';
    reverse(result.begin(), result.end());
    return result;
}

int fromBinary(const string &bin) {
    int result = 0;
    for (char c : bin) {
        result = result * 2 + (c - '0');
    }
    return result;
}

int main() {
    for (int i : {0, 1, 5, 10, 42, 255}) {
        cout << i << " = " << toBinary(i) << " (binary)" << endl;
    }
    cout << "1010 (binary) = " << fromBinary("1010") << endl;  // 10
    cout << "11111111 = "      << fromBinary("11111111") << endl; // 255
    return 0;
}
#include <iostream>
using namespace std;

int main() {
    double a, b;
    char op;

    cout << "Enter: num op num (e.g. 5 + 3): ";
    cin >> a >> op >> b;

    switch (op) {
        case '+': cout << a << " + " << b << " = " << a + b; break;
        case '-': cout << a << " - " << b << " = " << a - b; break;
        case '*': cout << a << " * " << b << " = " << a * b; break;
        case '/':
            if (b == 0) { cout << "Error: division by zero"; break; }
            cout << a << " / " << b << " = " << a / b;
            break;
        case '%':
            cout << (int)a << " % " << (int)b << " = " << (int)a % (int)b;
            break;
        default:
            cout << "Unknown operator: " << op;
    }
    cout << endl;
    return 0;
}
Pattern Printing "” Pyramid and Diamond
#include <iostream>
using namespace std;

void pyramid(int n) {
    for (int i = 1; i <= n; i++) {
        for (int j = i; j < n; j++) cout << " ";
        for (int j = 1; j <= 2*i-1; j++) cout << "*";
        cout << endl;
    }
}

void diamond(int n) {
    // Upper half
    for (int i = 1; i <= n; i++) {
        for (int j = i; j < n; j++) cout << " ";
        for (int j = 1; j <= 2*i-1; j++) cout << "*";
        cout << endl;
    }
    // Lower half
    for (int i = n-1; i >= 1; i--) {
        for (int j = n; j > i; j--) cout << " ";
        for (int j = 1; j <= 2*i-1; j++) cout << "*";
        cout << endl;
    }
}

void numberTriangle(int n) {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) cout << j << " ";
        cout << endl;
    }
}

int main() {
    cout << "--- Pyramid (n=5) ---" << endl;
    pyramid(5);

    cout << "\n--- Diamond (n=4) ---" << endl;
    diamond(4);

    cout << "\n--- Number Triangle (n=5) ---" << endl;
    numberTriangle(5);

    return 0;
}
Reverse Linked List and Balanced Parentheses
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node *next;
    Node(int d) : data(d), next(nullptr) {}
};

Node* reverse(Node *head) {
    Node *prev = nullptr, *curr = head, *next = nullptr;
    while (curr) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

void print(Node *head) {
    while (head) { cout << head->data << " "; head = head->next; }
    cout << endl;
}

int main() {
    // Build: 1 -> 2 -> 3 -> 4 -> 5
    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);

    cout << "Original: "; print(head);
    head = reverse(head);
    cout << "Reversed: "; print(head);
    // 5 4 3 2 1
    return 0;
}
#include <iostream>
#include <stack>
#include <string>
using namespace std;

bool isBalanced(const string &s) {
    stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') {
            st.push(c);
        } else if (c == ')' || c == ']' || c == '}') {
            if (st.empty()) return false;
            char top = st.top(); st.pop();
            if ((c == ')' && top != '(') ||
                (c == ']' && top != '[') ||
                (c == '}' && top != '{')) return false;
        }
    }
    return st.empty();
}

int main() {
    cout << boolalpha;
    cout << isBalanced("(())")       << endl;  // true
    cout << isBalanced("{[()]}")     << endl;  // true
    cout << isBalanced("([)]")       << endl;  // false
    cout << isBalanced("{")          << endl;  // false
    cout << isBalanced("int a = (b + c) * [d - e];") << endl;  // true
    return 0;
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.