Learn C++ Programming: 10 Basic Programs for Beginners

C++ is a programming language that is both powerful and versatile, and it is widely used in the software industry. It is a computer language extension that adds new features and capabilities to the C programming language. C++ is a programming language that blends procedural and object-oriented paradigms, making it ideal for a wide range of applications.

C++ provides complete control over system resources and memory management, enabling efficient and high-performance programming. It allows low-level operations such as direct memory manipulation and gives higher programming tools like pointers and references.

C++'s support for object-oriented programming (OOP) is an important feature. It enables the creation of classes and objects, the encapsulation of data and behavior within them, and the implementation of inheritance and polymorphism. As a result, C++ is ideal for creating large-scale, modular, and maintainable software systems.

C++ also has some added features over its predecessor, C. Exception handling, templates for generic programming, function overloading, operator overloading, and the Standard Template Library (STL), which contains a set of data structures and algorithms, are among these features.

Start your journey here: 10 Basic Programs for Beginners

Write a program to print Hello World in C++.

1. "Hello World" program in C++


Explanation:

  • The #include <iostream> directive includes the necessary header file for input/output operations in C++. This header file provides the functionality for input/output operations, such as displaying text on the console.
  • The int main() function is the entry point of the program. It is the starting point for the execution of the program and must be present in every C++ program.
  • std::cout is the standard output stream object, which is used to display output on the console.
  • The << operator is the insertion operator used to insert data into the output stream.
  • "Hello, World!" is a string literal that represents the text to be displayed on the console.
  • std::endl is used to insert a newline character and flush the output stream.
  • The statement return 0; indicates that the program execution was successful and returns the value 0 to the operating system.

When you run this program, it will display "Hello, World!" on the console. This is a simple and common introductory program that is often used to learn a new programming language.

2. Calculator

Build a simple calculator that can perform basic arithmetic operations like addition, subtraction, multiplication, and division.


Explanation:
  • The code starts with the inclusion of the <iostream> header, which allows for input/output operations in C++.
  • The main() function is the entry point of the program.
  • char op; declares a variable op of type char to store the operator.
  • double num1, num2; declares variables num1 and num2 of type double to store the two numbers.
  • std::cout is used to display output on the console.
  • std::cin is used to accept input from the user.
  • The first std::cout statement prompts the user to enter an operator.
  • The user's input is stored in the op variable using std::cin.
  • The second std::cout statement prompts the user to enter two numbers.
  • The user's inputs are stored in the num1 and num2 variables using std::cin.
  • A switch statement is used to perform the corresponding operation based on the operator entered by the user.
  • If the operator is +, the code adds num1 and num2.
  • If the operator is -, the code subtracts num2 from num1.
  • If the operator is *, the code multiplies num1 and num2.
  • If the operator is /, the code divides num1 by num2.
  • If the operator is none of the above, an error message is displayed.
  • The calculated result is stored in the result variable.
  • The final std::cout statement displays the result on the console.
  • The program returns 0 to indicate successful execution, or 1 if an invalid operator is entered.

3. Guessing Game

Create a program that generates a random number and prompts the user to guess it. Provide feedback on whether the guess is too high or too low until the correct number is guessed.


Explanation:
  • The code starts with the inclusion of <iostream> and <cstdlib> headers, which provide input/output and random number generation functionalities respectively.
  • The main() function is the entry point of the program.
  • srand(time(0)) is used to seed the random number generator with the current time. This ensures that the generated random number is different each time the program is run.
  • int secretNumber = rand() % 100 + 1 generates a random number between 1 and 100 and stores it in the secretNumber variable.
  • int guess is declared to store the user's guess.
  • int attempts is declared to keep track of the number of attempts made by the user.
  • The first std::cout statement displays a welcome message to the user.
  • The do-while loop is used to repeatedly prompt the user for their guess until they guess the correct number.
  • Within the loop, the user is prompted to enter their guess using std::cout.
  • The user's input is stored in the guess variable using std::cin.
  • If the guess is lower than the secretNumber, a message "Too low! Try again." is displayed.
  • If the guess is higher than the secretNumber, a message "Too high! Try again." is displayed.
  • The attempts counter is incremented after each guess.
  • The loop continues until the user's guess matches the secretNumber.
  • After exiting the loop, a congratulatory message is displayed along with the number of attempts made by the user.
  • The program returns 0 to indicate successful execution.
 In this game, the user has to guess a randomly generated number between 1 and 100. They are provided with feedback on whether their guess is too high or too low until they guess the correct number. The program keeps track of the number of attempts made by the user and displays it upon successful guessing.

4. Factorial Finder

Write a program that calculates the factorial of a given number using loops or recursion.


Explanation:
  • The code begins with the inclusion of the <iostream> header for input/output operations.
  • The factorial() function is defined to calculate the factorial of a given number using recursion.
  • In the factorial() function, there is a base case that checks if n is either 0 or 1. In such cases, the function returns 1 as the factorial of 0 or 1 is 1.
  • If n is not 0 or 1, the function recursively calls itself with the argument n - 1 and multiplies it with n to calculate the factorial of n.
  • The main() function is the entry point of the program.
  • A variable number is declared to store the user's input.
  • The user is prompted to enter a number using std::cout.
  • The user's input is stored in the number variable using std::cin.
  • The factorial() function is called with the number as an argument, and the result is stored in the result variable.
  • The calculated factorial is displayed on the console using std::cout.
  • The program returns 0 to indicate successful execution.
In this program, the user enters a number, and the factorial of that number is calculated using recursion. The factorial of a number n is the product of all positive integers from 1 to n. The program uses a recursive approach to calculate the factorial by breaking it down into smaller subproblems. The result is then displayed on the console.

5. Fibonacci Series

Generate and print the Fibonacci series up to a given number of terms.


Explanation:
  • The code begins with the inclusion of the <iostream> header for input/output operations.
  • The fibonacci() function is defined to generate the Fibonacci series using recursion.
  • In the fibonacci() function, there is a base case that checks if n is less than or equal to 1. In such cases, the function returns n itself as the Fibonacci series starts with 0 and 1.
  • If n is greater than 1, the function recursively calls itself with the arguments n - 1 and n - 2 to generate the subsequent terms of the Fibonacci series.
  • The main() function is the entry point of the program.
  • A variable terms is declared to store the number of terms in the Fibonacci series to be generated.
  • The user is prompted to enter the number of terms using std::cout.
  • The user's input is stored in the terms variable using std::cin.
  • The for loop is used to iterate i from 0 to terms - 1.
  • Within the loop, the fibonacci() function is called with i as an argument to generate the Fibonacci number at that position.
  • Each Fibonacci number is displayed on the console using std::cout.
  • The program returns 0 to indicate successful execution.
In this program, the user enters the number of terms they want in the Fibonacci series. The program generates the Fibonacci series using recursion, where each term is the sum of the two preceding terms. The generated series is then displayed on the console.

6. Temperature Converter

Create a program that converts temperature from Celsius to Fahrenheit or vice versa based on user input.


Explanation:
  • The code begins with the inclusion of the <iostream> header for input/output operations.
  • Two conversion functions, celsiusToFahrenheit() and fahrenheitToCelsius(), are defined to convert temperatures between Celsius and Fahrenheit.
  • celsiusToFahrenheit() function takes a temperature in Celsius as an argument and converts it to Fahrenheit using the conversion formula.
  • fahrenheitToCelsius() function takes a temperature in Fahrenheit as an argument and converts it to Celsius using the conversion formula.
  • The main() function is the entry point of the program.
  • A variable choice is declared to store the user's choice for the conversion type.
  • A variable temperature is declared to store the temperature value entered by the user.
  • The available conversion options are displayed to the user using std::cout.
  • The user is prompted to enter their choice using std::cin.
  • The user's choice is stored in the choice variable using std::cin.
  • The user is prompted to enter the temperature using std::cout.
  • The user's input is stored in the temperature variable using std::cin.
  • A variable convertedTemperature is declared to store the converted temperature value.
  • An if-else statement is used to perform the conversion based on the user's choice.
  • If the user chooses 1, the temperature is converted from Celsius to Fahrenheit using the celsiusToFahrenheit() function, and the result is displayed on the console.
  • If the user chooses 2, the temperature is converted from Fahrenheit to Celsius using the fahrenheitToCelsius() function, and the result is displayed on the console.
  • If the user enters an invalid choice, an error message is displayed.
  • The program returns 0 to indicate successful execution.
In this program, the user can select either Celsius to Fahrenheit conversion or Fahrenheit to Celsius conversion. The program takes the user's choice and temperature as inputs and performs the conversion accordingly. The converted temperature is then displayed on the console.

7. Palindrome Checker

Develop a program that checks if a given string is a palindrome (reads the same forwards and backwards).


Explanation:
  • The code begins with the inclusion of the <iostream>, <string>, and <algorithm> headers.
  • The isPalindrome() function is defined to check whether a given string is a palindrome or not.
  • The function takes a constant reference to a string (str) as an argument.
  • A copy of the input string is created as reversedStr.
  • The std::reverse() function from the <algorithm> header is used to reverse the characters in reversedStr.
  • The function returns a boolean value indicating whether the original string (str) is equal to the reversed string (reversedStr).
  • The main() function is the entry point of the program.
  • A variable word of type std::string is declared to store the user's input word.
  • The user is prompted to enter a word using std::cout.
  • The user's input is stored in the word variable using std::cin.
  • The isPalindrome() function is called with the word as an argument, and the result is stored in the palindrome variable.
  • An if-else statement is used to check whether the input word is a palindrome.
  • If palindrome is true, the input word is a palindrome, and a corresponding message is displayed.
  • If palindrome is false, the input word is not a palindrome, and a corresponding message is displayed.
  • The program returns 0 to indicate successful execution.
In this program, the user enters a word, and the program checks whether the word is a palindrome or not. A word is considered a palindrome if it reads the same forwards and backwards. The program reverses the input word and compares it with the original word. If both are equal, the word is a palindrome, and if not, it is not a palindrome. The result is then displayed on the console.

8. Prime Number Checker

 Write a program that determines whether a given number is prime or not.


Explanation:
  • The code begins with the inclusion of the <iostream> header for input/output operations.
  • The isPrime() function is defined to check whether a given number is prime or not.
  • The function takes an integer (number) as an argument.
  • The function first checks if the number is less than or equal to 1. If so, it returns false as prime numbers are greater than 1.
  • A for loop is used to iterate from 2 to the square root of the number (i * i <= number).
  • Within the loop, the function checks if the number is divisible by i. If it is, the number is not prime and the function returns false.
  • If the loop completes without finding any divisors, the number is prime and the function returns true.
  • The main() function is the entry point of the program.
  • A variable number of type int is declared to store the user's input number.
  • The user is prompted to enter a positive integer using std::cout.
  • The user's input is stored in the number variable using std::cin.
  • The isPrime() function is called with the number as an argument, and the result is stored in the prime variable.
  • An if-else statement is used to check whether the input number is prime.
  • If prime is true, the input number is prime, and a corresponding message is displayed.
  • If prime is false, the input number is not prime, and a corresponding message is displayed.
  • The program returns 0 to indicate successful execution.
In this program, the user enters a positive integer, and the program checks whether the number is prime or not. A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. The program uses a loop to iterate from 2 to the square root of the number and checks if any of these values divide the number. If a divisor is found, the number is not prime. Otherwise, it is considered prime. The result is then displayed on the console.


9. File Encryption/Decryption

 Implement a program that encrypts and decrypts a file using a simple encryption algorithm like Caesar cipher.


Explanation:
  • The code begins with the inclusion of the <iostream>, <fstream>, and <string> headers.
  • Two functions, encryptFile() and decryptFile(), are defined to perform file encryption and decryption, respectively.
  • The encryptFile() function takes a filename as input, opens the file in binary mode for reading (std::ifstream), and creates a new file with the extension ".encrypted" for writing (std::ofstream).
  • Inside the function, each character in the input file is read and XORed with 127 to encrypt it. XORing the character with 127 is a simple encryption technique.
  • The encrypted characters are written to the output file.
  • The decryptFile() function takes a filename as input, opens the encrypted file in binary mode for reading, and creates a new file with the original name (without the ".encrypted" extension) for writing.
  • Inside the function, each character in the encrypted file is read and XORed with 127 to decrypt it. XORing the character with 127 again retrieves the original character.
  • The decrypted characters are written to the output file.
  • The main() function is the entry point of the program.
  • A variable filename of type std::string is declared to store the user's input filename.
  • The user is prompted to enter the filename using std::cout.
  • The user's input is stored in the filename variable using std::cin.
  • The user is prompted to choose an option for encryption or decryption using std::cout.
  • The user's choice is stored in the choice variable using  std::cin

10. Student Grade Calculator

Design a program that calculates the average grade of students based on their marks and provides a corresponding letter grade.


Explanation:
  • The code begins with the inclusion of the <iostream> header for input/output operations.
  • The main() function is the entry point of the program.
  • A variable numSubjects of type int is declared to store the number of subjects.
  • A variable totalMarks of type double is initialized to 0.0 to store the sum of marks.
  • The user is prompted to enter the number of subjects using std::cout.
  • The user's input is stored in the numSubjects variable using std::cin.
  • A for loop is used to iterate over each subject.
  • Inside the loop, a variable marks of type double is declared to store the marks for each subject.
  • The user is prompted to enter the marks for each subject using std::cout.
  • The user's input is stored in the marks variable using std::cin.
  • The marks for each subject are added to the totalMarks variable.
  • After the loop completes, the average grade is calculated by dividing the totalMarks by the numSubjects.
  • The total marks and average grade are displayed on the console using std::cout.
  • The program returns 0 to indicate successful execution.
In this program, the user enters the number of subjects and their corresponding marks. The program then calculates the total marks and the average grade for the given subjects.

Post a Comment (0)
Previous Post Next Post