C++ Example Programs with Output
In the ever-evolving landscape of programming languages, C++ stands tall as a versatile and powerful tool for developers. This post contains various C++ example programs, from the very basics to an advanced level.
Hello World Program in C++
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
Hello, World!
The "Hello World" program is a classic introductory example. Here, we include the `<iostream>` header for input and output operations. The `main` function is the entry point of the program, and `cout` is used to output the "Hello, World!" message to the console.
Variables and Data Types Program in C++
#include <iostream>
using namespace std;
int main() {
int age = 25;
float height = 5.9;
char grade = 'A';
cout << "Age: " << age << endl;
cout << "Height: " << height << " feet" << endl;
cout << "Grade: " << grade << endl;
return 0;
}
Age: 25 Height: 5.9 feet Grade: A
This program demonstrates the use of variables and different data types. We declare an integer (`age`), a floating-point number (`height`), and a character (`grade`). The values are assigned, and `cout` is used to display them with appropriate messages.
Arithmetic Operations Program in C++
#include <iostream>
using namespace std;
int main() {
int num1 = 10, num2 = 5;
cout << "Sum: " << num1 + num2 << endl;
cout << "Difference: " << num1 - num2 << endl;
cout << "Product: " << num1 * num2 << endl;
cout << "Quotient: " << num1 / num2 << endl;
return 0;
}
Sum: 15 Difference: 5 Product: 50 Quotient: 2
This program showcases basic arithmetic operations using two numbers. The sum, difference, product, and quotient are calculated and displayed using `cout`.
Conditional Statements (If-Else) Program in C++
#include <iostream>
using namespace std;
int main() {
int num = 7;
if (num % 2 == 0) {
cout << num << " is even." << endl;
} else {
cout << num << " is odd." << endl;
}
return 0;
}
7 is odd.
In this program, an `if-else` statement is used to determine whether a number is even or odd based on the remainder when divided by 2.
Loops (For and While) Program in C++
#include <iostream>
using namespace std;
int main() {
// For loop
cout << "For Loop:" << endl;
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
cout << endl;
// While loop
cout << "While Loop:" << endl;
int j = 5;
while (j > 0) {
cout << j << " ";
--j;
}
return 0;
}
For Loop: 1 2 3 4 5 While Loop: 5 4 3 2 1
The program demonstrates the use of a `for` loop to print numbers from 1 to 5 and a `while` loop to print numbers from 5 to 1.
Arrays and Iteration Program in C++
#include <iostream>
using namespace std;
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int sum = 0;
// Iterating through array
for (int i = 0; i < 5; ++i) {
sum += numbers[i];
}
cout << "Sum of array elements: " << sum << endl;
return 0;
}
Sum of array elements: 15
This program declares an array of integers and calculates their sum using a `for` loop for iteration.
Functions Program in C++
#include <iostream>
using namespace std;
// Function to calculate the square of a number
int square(int x) {
return x * x;
}
int main() {
int num = 4;
cout << "Square of " << num << ": " << square(num) << endl;
return 0;
}
Square of 4: 16
The program defines a function `square` to calculate the square of a number. The function is then called in the `main` function.
Pointers Program in C++
#include <iostream>
using namespace std;
int main() {
int num = 42;
int* ptr = #
cout << "Value of num: " << num << endl;
cout << "Address of num: " << &num << endl;
cout << "Value via pointer: " << *ptr << endl;
cout << "Address stored in pointer: " << ptr << endl;
return 0;
}
Value of num: 42 Address of num: 0x7ffeefbff58c Value via pointer: 42 Address stored in pointer: 0x7ffeefbff58c
This program introduces pointers in C++. The int* ptr declares a pointer variable that stores the address of an integer (&num). The program then prints the value of the variable, its address, the value accessed via the pointer (*ptr), and the address stored in the pointer.
Object-Oriented Programming (OOP) Program in C++
#include <iostream>
using namespace std;
// Class definition
class Circle {
private:
float radius;
public:
// Constructor
Circle(float r) : radius(r) {}
// Member function to calculate area
float calculateArea() {
return 3.14 * radius * radius;
}
};
int main() {
// Creating an object of class Circle
Circle myCircle(5.0);
cout << "Area of the circle: " << myCircle.calculateArea() << endl;
return 0;
}
Area of the circle: 78.5
This program introduces the basics of OOP in C++. A `Circle` class is defined with a private member `radius`, a constructor, and a member function `calculateArea` to find the area.
Inheritance Program in C++
#include <iostream>
using namespace std;
class Shape {
public:
void display() {
cout << "This is a shape." << endl;
}
};
class Circle : public Shape {
public:
void display() {
cout << "This is a circle." << endl;
}
};
int main() {
Circle myCircle;
myCircle.display();
return 0;
}
This is a circle.
This program illustrates inheritance in C++. The Circle class is derived from the Shape class using the public access specifier. The display method is overridden in the Circle class. In the main function, an object of the Circle class is created, and its display method is called.
File Handling Program in C++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Writing to a file
ofstream outputFile("output.txt");
outputFile << "Hello from C++ File Handling!";
outputFile.close();
// Reading from a file
ifstream inputFile("output.txt");
string content;
getline(inputFile, content);
inputFile.close();
cout << "File Content: " << content << endl;
return 0;
}
File Content: Hello from C++ File Handling!
This program demonstrates file handling in C++, writing content to a file and reading it back.
Exception Handling Program in C++
#include <iostream>
using namespace std;
double divide(int a, int b) {
if (b == 0) {
throw "Division by zero is not allowed.";
}
return static_cast<double>(a) / b;
}
int main() {
try {
cout << "Result: " << divide(10, 2) << endl;
cout << "Result: " << divide(8, 0) << endl;
} catch (const char* error) {
cout << "Error: " << error << endl;
}
return 0;
}
Result: 5 Error: Division by zero is not allowed.
This program demonstrates exception handling in C++. The divide function checks for division by zero and throws an exception if encountered. In the main function, the try block calls the divide function with different inputs. If an exception is thrown, the catch block handles the error and prints an error message.
Dynamic Memory Allocation Program in C++
#include <iostream>
using namespace std;
int main() {
int* dynamicArray = new int[5];
for (int i = 0; i < 5; ++i) {
dynamicArray[i] = i * 2;
}
cout << "Dynamic Array: ";
for (int i = 0; i < 5; ++i) {
cout << dynamicArray[i] << " ";
}
delete[] dynamicArray;
return 0;
}
Dynamic Array: 0 2 4 6 8
This program showcases dynamic memory allocation in C++. It uses the new operator to allocate an array of integers on the heap. Values are assigned to the array elements, and then the array is printed. Finally, the delete[] operator is used to free the allocated memory.
Sharing is stylish! Gift your friends this awesome read!