Essential C++ Programming Examples for Beginners

Addition of Two Numbers

#include <iostream>
int main() {
    int a, b, sum;
    std::cout << "Enter the first number: ";
    std::cin >> a;
    std::cout << "Enter the second number: ";
    std::cin >> b;
    sum = a + b;
    std::cout << "The sum of two numbers = " << sum;
    return 0;
}

Authorized for Voting

#include <iostream>
using namespace std;
int main() {
    int age = 19;
    if(age > 18)
        cout << "You are authorized to vote";
    else
        cout << "You are not authorized to vote";
    return 0;
}

Basic Arithmetic Operations

#include <iostream>
using namespace std;
int main() {
    float a, b;
    float sum, subtraction, multiply, division;
    cout << "Enter the first number: "; cin >> a;
    cout << "Enter the second number: "; cin >> b;
    sum = a + b; cout << "Sum = " << sum << endl;
    subtraction = a - b; cout << "Subtraction = " << subtraction << endl;
    multiply = a * b; cout << "Multiplication = " << multiply << endl;
    division = a / b; cout << "Division = " << division;
    return 0;
}

Multiplication Table of 2

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

Array Implementation

#include <iostream>
using namespace std;
int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    cout << "Array elements are: ";
    for(int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

Positive or Negative Number

#include <iostream>
using namespace std;
int main() {
    int num;
    cout << "Enter the number: "; cin >> num;
    if(num > 0)
        cout << "Given number is positive";
    else
        cout << "Given number is negative";
    return 0;
}

Calculating Geometric Areas

#include <iostream>
using namespace std;
int main() {
    float length, breadth, radius, side;
    cout << "Enter length and breadth of rectangle: "; cin >> length >> breadth;
    cout << "Area of rectangle = " << length * breadth << endl;
    cout << "Enter radius of circle: "; cin >> radius;
    cout << "Area of circle = " << 3.1416 * radius * radius << endl;
    cout << "Enter side of square: "; cin >> side;
    cout << "Area of square = " << side * side;
    return 0;
}

Looping from 0 to 5

#include <iostream>
using namespace std;
int main() {
    for(int i = 0; i <= 5; i++) {
        cout << i << endl;
    }
    return 0;
}

Odd or Even Check

#include <iostream>
using namespace std;
int main() {
    int num;
    cout << "Enter the number: "; cin >> num;
    if(num % 2 == 0)
        cout << "Given number is even";
    else
        cout << "Given number is odd";
    return 0;
}