2. Basic Input/Output Program
In C++, interacting with the user through input & output is a fundamental task. This program shows how to read input from the user & display output back to the console.
Code for a basic input/output program in C++:
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
cout << "Hello, " << name << "! You are " << age << " years old." << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Enter your name: Riya
Enter your age: 24
Hello, Riya! You are 24 years old.
In this code :
- #include <string>: This line includes the string header file, which provides support for working with strings in C++.
- string name; & int age;: These lines declare variables to store the user's name & age respectively.
- cout << "Enter your name: ";: This line prompts the user to enter their name.
- getline(cin, name);: This statement reads a line of input from the user & stores it in the name variable. The getline() function reads until a newline character is encountered.
- cout << "Enter your age: ";: This line prompts the user to enter their age.
- cin >> age;: This statement reads an integer value from the user & stores it in the age variable.
- cout << "Hello, " << name << "! You are " << age << " years old." << endl;: This line displays a greeting message to the user, using the provided name & age.
When you run this program, it will ask you to enter your name & age. After providing the input, it will display a personalized greeting message.
This program showcases basic input/output operations in C++ using cin for input & cout for output. It also shows how to work with different data types like strings & integers.
3. Simple Calculator Program
A calculator is a practical application that allows users to perform basic arithmetic operations. This program creates a simple calculator that can add, subtract, multiply, or divide two numbers based on the user's choice.
Code for the simple calculator program in C++:
C++
#include <iostream>
using namespace std;
int main() {
double num1, num2;
char operation;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
double result;
switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
cout << "Error: Division by zero!" << endl;
return 1;
}
break;
default:
cout << "Error: Invalid operation!" << endl;
return 1;
}
cout << num1 << " " << operation << " " << num2 << " = " << result << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Enter first number: 4
Enter second number: 5
Enter operation (+, -, *, /): *
4 * 5 = 20
In this code :
- double num1, num2; & char operation;: These lines declare variables to store the two numbers & the operation to be performed.
- cout << "Enter first number: "; & cin >> num1;: These lines prompt the user to enter the first number & read it from the console.
- cout << "Enter second number: "; & cin >> num2;: These lines prompt the user to enter the second number & read it from the console.
- cout << "Enter operation (+, -, *, /): "; & cin >> operation;: These lines prompt the user to enter the desired operation & read it from the console.
- The switch statement checks the entered operation & performs the corresponding arithmetic operation using the +, -, *, or / operators.
- If the operation is division & the second number is zero, an error message is displayed & the program exits with a non-zero status.
- If an invalid operation is entered, an error message is displayed & the program exits with a non-zero status.
- Finally, the program displays the result of the arithmetic operation.
This calculator program demonstrates how to use basic arithmetic operators, handle user input, & make decisions based on the input using a switch statement. It also includes error handling for division by zero & invalid operations.
4. Temperature Conversion Program
Temperature conversion is a common task that converts a temperature value from one unit to another, such as Celsius to Fahrenheit or vice versa. This program allows the user to enter a temperature in Celsius and convert it to Fahrenheit.
Code for the temperature conversion program in C++:
C++
#include <iostream>
using namespace std;
double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
int main() {
double celsius;
cout << "Enter temperature in Celsius: ";
cin >> celsius;
double fahrenheit = celsiusToFahrenheit(celsius);
cout << celsius << " degrees Celsius = " << fahrenheit << " degrees Fahrenheit" << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Enter temperature in Celsius: 45
45 degrees Celsius = 113 degrees Fahrenheit
In this code :
- The celsiusToFahrenheit function takes a temperature in Celsius as input and returns the equivalent temperature in Fahrenheit. The conversion formula is (celsius * 9/5) + 32.
- In the main function, the double celsius; line declares a variable to store the temperature in Celsius.
- cout << "Enter temperature in Celsius: "; & cin >> celsius;: These lines prompt the user to enter the temperature in Celsius and read it from the console.
- double fahrenheit = celsiusToFahrenheit(celsius);: This line calls the celsiusToFahrenheit function to convert the Celsius temperature to Fahrenheit and stores the result in the fahrenheit variable.
- Finally, the program displays the original temperature in Celsius and the converted temperature in Fahrenheit.
5. Factorial Calculation Program
Calculating the factorial of a number is a common programming exercise. The factorial of a non-negative integer n is the product of all positive integers from 1 to n. For example, the factorial of 5 (denoted as 5!) is calculated as 5 * 4 * 3 * 2 * 1 = 120.
Code for a program that calculates the factorial of a number in C++:
C++
#include <iostream>
using namespace std;
int calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
int main() {
int number;
cout << "Enter a non-negative integer: ";
cin >> number;
if (number < 0) {
cout << "Error: Factorial is not defined for negative numbers!" << endl;
return 1;
}
int factorial = calculateFactorial(number);
cout << "Factorial of " << number << " is " << factorial << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Enter a non-negative integer: -7
ERROR!
Error: Factorial is not defined for negative numbers!
In this code :
- The calculateFactorial function takes an integer n as input and calculates its factorial using recursion. If n is 0 or 1, the function returns 1 since the factorial of 0 and 1 is defined as 1. Otherwise, the function recursively calls itself with n - 1 and multiplies the result by n.
- In the main function, the int number; line declares a variable to store the input number.
- cout << "Enter a non-negative integer: "; & cin >> number;: These lines prompt the user to enter a non-negative integer and read it from the console.
- The if statement checks if the entered number is negative. If it is, an error message is displayed, and the program exits with a non-zero status.
- int factorial = calculateFactorial(number);: This line calls the calculateFactorial function to calculate the factorial of the entered number and stores the result in the factorial variable.
- Finally, the program displays the original number and its factorial.
Note: The factorial of a number can grow very large quickly, so this program may not work correctly for large input values due to integer overflow. To handle larger factorials, you can use data types like long long or unsigned long long, or even consider using a library like boost::multiprecision for arbitrary-precision arithmetic.
6. Palindrome Checker Program
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. For example, "racecar", "A man, a plan, a canal, Panama!", and "12321" are all palindromes.
Here's a C++ program that checks whether a given string is a palindrome:
C++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isPalindrome(string str) {
// Remove non-alphanumeric characters and convert to lowercase
str.erase(remove_if(str.begin(), str.end(), [](char c) { return !isalnum(c); }), str.end());
transform(str.begin(), str.end(), str.begin(), ::tolower);
// Check if the string is equal to its reverse
return equal(str.begin(), str.begin() + str.size() / 2, str.rbegin());
}
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
if (isPalindrome(str)) {
cout << "The string is a palindrome." << endl;
} else {
cout << "The string is not a palindrome." << endl;
}
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Enter a string: Hello
The string is not a palindrome.
In this code :
- The isPalindrome function takes a string str as input and returns a boolean value indicating whether the string is a palindrome.
- Inside the function, the first step is to remove all non-alphanumeric characters from the string and convert the remaining characters to lowercase. This is done using the erase and remove_if functions from the <algorithm> library, along with a lambda function that checks if a character is alphanumeric using the isalnum function.
- Next, the transform function is used to convert all characters in the string to lowercase using the ::tolower function.
- Finally, the function checks if the string is equal to its reverse. This is done using the equal function, which compares the first half of the string with the reverse of the second half. If they are equal, the string is a palindrome.
- In the main function, the string str; line declares a variable to store the input string.
- cout << "Enter a string: "; & getline(cin, str);: These lines prompt the user to enter a string and read it from the console using getline to allow for strings with spaces.
- The program calls the isPalindrome function with the entered string and checks the returned boolean value. If it is true, it prints "The string is a palindrome." Otherwise, it prints "The string is not a palindrome."
7. Number Guessing Game
A number guessing game is a simple yet engaging program where the computer generates a random number, and the user tries to guess it. The program provides feedback to the user, indicating whether their guess is too high or too low, and continues until the user correctly guesses the number.
Here's a C++ program that implements a number guessing game:
C++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0)); // Seed the random number generator
int secretNumber = rand() % 100 + 1; // Generate a random number between 1 and 100
int guess;
int numGuesses = 0;
cout << "Welcome to the Number Guessing Game!" << endl;
cout << "I'm thinking of a number between 1 and 100." << endl;
do {
cout << "Enter your guess: ";
cin >> guess;
numGuesses++;
if (guess < secretNumber) {
cout << "Too low! Try again." << endl;
} else if (guess > secretNumber) {
cout << "Too high! Try again." << endl;
} else {
cout << "Congratulations! You guessed the number in " << numGuesses << " guesses!" << endl;
}
} while (guess != secretNumber);
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Enter your guess: 91
Too high! Try again.
Enter your guess: 78
Too high! Try again.
Enter your guess: 65
Too high! Try again.
Enter your guess: 34
Too low! Try again.
Enter your guess: 69
Too high! Try again.
Enter your guess: 90
Too high! Try again.
In this code :
- The program starts by seeding the random number generator using srand(time(0)). This ensures that each time the program runs, it generates a different sequence of random numbers.
- int secretNumber = rand() % 100 + 1;: This line generates a random number between 1 and 100 using the rand() function and the modulo operator %. The generated number is stored in the secretNumber variable.
- The program initializes the guess variable to store the user's guess and the numGuesses variable to keep track of the number of guesses made.
- It displays a welcome message and informs the user that the program is thinking of a number between 1 and 100.
- The program enters a do-while loop that continues until the user correctly guesses the number.
- Inside the loop, it prompts the user to enter their guess using cout and cin, and increments the numGuesses counter.
- The program compares the user's guess with the secret number using conditional statements:
- If the guess is less than the secret number, it displays "Too low! Try again."
- If the guess is greater than the secret number, it displays "Too high! Try again."
- If the guess matches the secret number, it displays a congratulatory message along with the number of guesses made.
- The loop continues until the user correctly guesses the number.
Note: This program demonstrates the use of random number generation using rand(), user input/output using cin and cout, and conditional statements with if-else and do-while loop.
8. Basic File I/O Program
File input/output (I/O) is an essential aspect of programming that allows you to read from and write to files. In C++, you can use the <fstream> library to perform file I/O operations.
Here's a basic C++ program that demonstrates reading from and writing to a file:
C++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename = "example.txt";
string data;
// Writing to a file
ofstream outputFile(filename);
if (outputFile.is_open()) {
cout << "Enter data to write to the file (press Enter without input to finish):" << endl;
while (getline(cin, data) && !data.empty()) {
outputFile << data << endl;
}
outputFile.close();
cout << "Data written to the file successfully." << endl;
} else {
cout << "Unable to open the file for writing." << endl;
}
// Reading from a file
ifstream inputFile(filename);
if (inputFile.is_open()) {
cout << "Contents of the file:" << endl;
while (getline(inputFile, data)) {
cout << data << endl;
}
inputFile.close();
} else {
cout << "Unable to open the file for reading." << endl;
}
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Unable to open the file for writing.
Unable to open the file for reading.
In this code :
- The program starts by including the necessary headers: <iostream> for input/output, <fstream> for file I/O, and <string> for string manipulation.
- It declares a string variable filename to store the name of the file and a string variable data to store the data read from or written to the file.
- For writing to a file:
- It creates an ofstream object named outputFile and opens the file specified by filename.
- It checks if the file is successfully opened using the is_open() function.
- If the file is open, it prompts the user to enter data to write to the file.
- It uses a while loop with getline(cin, data) to read input from the user until an empty line is entered.
- Inside the loop, it writes each line of data to the file using outputFile << data << endl;.
- After writing the data, it closes the file using outputFile.close() and displays a success message.
- If the file cannot be opened, it displays an error message.
- For reading from a file:
- It creates an ifstream object named inputFile and opens the file specified by filename.
- It checks if the file is successfully opened using the is_open() function.
- If the file is open, it displays a message indicating that it will print the contents of the file.
- It uses a while loop with getline(inputFile, data) to read each line of data from the file.
- Inside the loop, it prints each line of data to the console using cout << data << endl;.
- After reading the data, it closes the file using inputFile.close().
- If the file cannot be opened, it displays an error message.
Note : This program demonstrates basic file I/O operations in C++. It shows how to open a file for writing using ofstream, write data to the file, and close the file. It also shows how to open a file for reading using ifstream, read data from the file, and close the file.
9. Array Manipulation Program
Arrays are a fundamental data structure in C++ used to store collections of elements of the same type. This program demonstrates basic array manipulation operations, such as initializing an array, accessing elements, and modifying array contents.
Here's a C++ program that showcases array manipulation:
C++
#include <iostream>
using namespace std;
const int SIZE = 5;
void printArray(const int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int numbers[SIZE];
// Initialize the array with user input
cout << "Enter " << SIZE << " integers:" << endl;
for (int i = 0; i < SIZE; i++) {
cin >> numbers[i];
}
cout << "Original array: ";
printArray(numbers, SIZE);
// Multiply each element by 2
for (int i = 0; i < SIZE; i++) {
numbers[i] *= 2;
}
cout << "Array after multiplying each element by 2: ";
printArray(numbers, SIZE);
// Find the sum and average of the elements
int sum = 0;
for (int i = 0; i < SIZE; i++) {
sum += numbers[i];
}
double average = static_cast<double>(sum) / SIZE;
cout << "Sum of the elements: " << sum << endl;
cout << "Average of the elements: " << average << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Enter 5 integers:
5 7 19 87 65
Original array: 5 7 19 87 65
Array after multiplying each element by 2: 10 14 38 174 130
Sum of the elements: 366
Average of the elements: 73.2
In this code :
- The program starts by defining a constant SIZE with a value of 5 to represent the size of the array.
- It defines a helper function printArray that takes an array and its size as parameters and prints the elements of the array.
- In the main function, it declares an integer array numbers of size SIZE.
- It prompts the user to enter SIZE integers and uses a for loop to read the user input and store it in the numbers array.
- It calls the printArray function to print the original contents of the array.
- Using a for loop, it multiplies each element of the array by 2, modifying the array in place.
- It calls the printArray function again to print the modified array.
- It calculates the sum of the elements using a for loop and accumulates the sum in the sum variable.
- It calculates the average of the elements by dividing the sum by SIZE and stores the result in the average variable. The static_cast<double> is used to perform explicit type conversion from integer to double.
- Finally, it prints the sum and average of the elements.
Frequently Asked Questions
What is the purpose of the #include statements in C++?
The #include statements are used to include header files in a C++ program. Header files contain declarations of functions, classes, and variables that can be used in the program.
What is the difference between cin and getline for reading input?
cin is used to read input from the console, but it stops reading when it encounters a whitespace character. getline, on the other hand, reads an entire line of input, including whitespace characters, until a newline character is encountered.
What is the significance of the return 0; statement in the main function?
The return 0; statement in the main function indicates that the program has executed successfully without any errors. It is a convention to return 0 from the main function to signify successful program termination.
Conclusion
In this article, we wrote 10 basic C++ programs that shows fundamental concepts & techniques. From the classic "Hello, World!" program to array manipulation, these examples provide a great help in understanding or writing C++ code. We learned how to handle input/output, perform arithmetic operations, use control flow statements, define & call functions, work with strings & arrays, & perform file I/O. By practicing these programs, new coders can gain confidence in their C++ programming skills & build a strong foundation for more advanced topics.