C++

C++ Programs Examples with Output43 min read

C++ stands out as a robust and advanced programming language, offering high-level capabilities. Initially designed to introduce object-orientation to the C language, C++ has become a cornerstone in the world of programming.

To truly grasp a programming language, active practice through writing programs is essential. Our collection of C++ programs covers a range of topics, including control statements, loops, classes & objects, functions, arrays, and more. Each program has been meticulously tested and is accompanied by its output.




Explore our comprehensive list of fundamental C++ programs below, designed to accelerate your learning process. Utilize the Online C++ Editor to run and modify programs for a hands-on understanding.

Table of Contents

C++ Basic Examples

Hello World Program in C++: Kickstart your C++ journey with a classic “Hello World!” program. This simple yet foundational program is a standard introductory exercise across various programming languages.

Output:

C++ program to print to console

The C++ standard library, specifically iostream, offers three built-in methods for console output:

cout:

cout is a versatile tool for displaying various messages or data on the console.

In contrast to the C language, there’s no need to specify the data type when using cout.

Output:

Utilize cout to effortlessly print messages and data in your C++ programs. It simplifies the output process by eliminating the need for explicit data type declarations.

clog:

clog is another output stream that can be used for logging information to the console.

It provides a buffered stream, making it suitable for handling log messages.

Output:

When you require a buffered stream for logging purposes, consider employing clog to efficiently manage your log messages.

cerr:

cerr is designed for error messages and behaves similarly to clog with the added benefit of being unbuffered.

It is particularly useful for immediate and unaltered display of error information.

Output:

………………..

C++ basic input output Integer

Unlike C language C++ does not require to specify the type of data for IO (Input/Output) operation. You can directly print any desirable data to the console using cout with the insertion operator (<<). Similarly, for taking input you can use cin with the extraction operator(>>).

Output:

C++ basic input output string

In C++, capturing string input from users is efficiently achieved through the getline method when utilizing the string data type. Alternatively, you can employ cin for string input; however, it halts reading characters upon encountering a space.

Output:

C++ addition of two user given numbers

This example program illustrates how to perform the addition of two numbers provided by the user in C++.

In this program, we prompt the user to input two integer numbers. After receiving the inputs, the program calculates the sum and displays the result on the console.

Output:

C++ swap two numbers using temporary variable

Swapping numbers involves exchanging values between variables. This program demonstrates how to swap two user-provided numbers using a temporary variable.

Logic:

  1. Assign the value of variable a to the variable temp, storing the original value of a.
  2. Assign the value of b to a.
  3. Assign the value stored in temp (original a) to b.

Output:

C++ swap two numbers without temporary variable

Swapping numbers

Swapping numbers means exchanging the values between two or more variables. In this program we are going to swap two numbers without using any temporary variable.

Logic

  1. Store addition of variable a and b (a+b) to variable a.
  2. Now extract b from a and store it to b.
  3. Extract b from a and store it to a.

Now b is holding a’s original value and similarly a is holding b’s original value.

C++ program to calculate area of a circle

The area of a circle is the number of square units within the circle. To calculate the area of a circle the standard formula is: Area = Pi R Square

Area of circle = (A = πr²)

Logic

Here we have taken radius as input from the user, and to calculate the area of the circle we have to multiply the value of pi with the square of the radius.

Value of Pi = (3.14159)

C++ program to calculate simple interest

Simple interest is a simple way to calculate the interest on a loan. Simple interest is determined by multiplying the principal by the daily interest rate multiplied by the number of days elapsed between payments. – Investopedia

Output:

C++ program to calculate compound interest

Compound interest (or compounding interest) is the interest calculated on the principal, including all cumulative interest on deposits or loans in the previous period.

C++ program to find ASCII value of a character

ASCII (American Standard Code for Information Interchange) is the character encoding standard of electronic communication. ASCII codes represent text within computers, telecommunications equipment, and other devices. – Wikipedia

Output:

C++ calculate year week and days from given total days

In this C++ program, we are going to see how we can calculate Year, Week and Days from given total days. We all know that 1 year = 365 (ignoring leap year) and 1 week = 7 days on this basis we can determine the year, week and days from given total no of days.

C++ program to print size of different datatypes

This program shows how you can print the size of any data type available in C++ language. To find the size of any data type, C and C++ have one special operator sizeof. It simply calculates and returns the size of any given data type in bytes.

C++ If Else Examples

C++ check whether a character is alphabet or not

In this program, we are going to see whether a user given character is an alphabet or not. To determine the type of character, we have to check it’s ASCII value range.

C++ check whether a character is alphabet, digit or special character

This program is much similar to the previous one but here we are checking whether the given character is an alphabet, digit or a special character.

C++ find largest number among three number using if statement

In this program, we are going to see how to find the largest number among three numbers using if statement.

Logic

Here we have to compare each number with another two numbers, if it is greater than the both then simply print it.

Let’s say A = 11, B = 22 and C = 15

Then steps would be

  1. if A > B and A > C that means A is the largest number.
  2. if B > A and B > C that means B is the largest number.
  3. Similarly if C > A and C > B that means C is the largest number.

C++ find largest number among three number using if else statement

This program is similar to the previous one, with a single modification, here we will use if else statement to find the largest number.

Logic

The logic to find the largest number among the three numbers, we have to compare each number with the other two numbers.

Let three variables be: A = 400, B = 200 and C = 300

  1. if A > B and A > C, then print A.
  2. else if B > A and B > C, then print B.
  3. else print C.

C++ find largest number among three number using nested if else statement

In this program, we are going to find the largest number among three numbers, similar to the previous one, but it is nested if-else version.

Logic

Let three variables be: A = 400, B = 200 and C = 300

The logic goes like this:

  1. if A >= B then check for if A >= C, then print A else print C.
  2. else part: if B >= C then print B else print C.

C++ program to check whether a year is leap year or not

Leap year

A leap year is a calendar year that includes an additional day to synchronize the calendar year with the astronomical or seasonal year. – Wikipedia

Logic

The Logic to check this is quite simple. We only need to check if the given year is multiple of 4 or 400, but it should not be multiple of 100.

C++ program to check whether number is even or odd

Even number

Even numbers are numbers that have a difference of 2 unit or number. In other words, if the number is completely divisible by 2 then it is an even number.

Odd number

Opposite of even numbers, odd numbers are having a difference of 3 unit or number. In other words, if the number is not completely divisible by 2 then it is an odd number.

Logic

To find if a number is even or odd we only need to check if the given number is multiple of 2 or not, If it is multiple of 2 that means it is even number otherwise an odd number.

To check if it is multiple of 2 or not we use modulus operator.

If the expression number % 2 returns 0 that means the number is a multiple of 2. In other words, it is completely divisible by 2.

C++ check whether a number is negative, positive or zero

Positive number

All the numbers greater than 0, but not equal to 0 are positive numbers.

Negative number

Similarly all the number less than 0, but not equal to 0 are negative numbers.

Logic

If the number is greater than zero that means it is positive. If the number is less than zero that means it is negative. If the number is equal to zero that means it is absolute zero.

  1. if number > 0 then print Positive.
  2. if number < 0 then print Negative.
  3. if number == 0 then print Zero.

C++ check whether a character is upper or lowercase alphabet

If the ASCII value of a character lies between 65 (A) to 90 (Z) then it is an uppercase character or if the character’s ASCII value lies between 97 (a) to 122 (z) then it is a lowercase character.

C++ check whether a character is vowel or consonant

There are five vowel characters {a, e, i, o, u}. If the user given character input is one of them that means it is a vowel otherwise it is a consonant.

Logic

Here we have to manually check the given character with all the vowel characters, we cannot use ASCII value range to determine whether it is a vowel or a consonant. The given character can also be in the form of uppercase.

C++ print day name of week from number

In this program, we are going to print day name based on week no. Like – If the user enters 1 that means it is Monday.

Logic

After taking input (Week no) from the user, we have to compare that number with 1 to 7 or we can say comparing that number with a day of a week. So the logic goes like – if the number is equal to 1 then it is Monday, if the number is 2 then it is Tuesday etc… Like that we have to compare with each day of the week.

C++ Loop Examples

C++ program to print all odd numbers from 1 to N

Odd number

Opposite of even numbers, odd numbers are having a difference of 3 unit or number. In other words, if the number is not completely divisible by 2 then it is an odd number.

Logic

The logic for printing odd numbers are pretty simple and straight forward, we only need to check if the number is not divisible by 2. If the number is not divisible by 2, then we have to print it.

C++ program to calculate sum of first N odd numbers

Odd number

The Opposite of even numbers. Odd numbers have a difference of 3 unit or number. In other words, if the number is not completely divisible by 2 then it is an odd number.

C++ program to print all even numbers from 1 to N

Even number

Even number are numbers that have a difference of 2 unit or number. In other words, if the number is completely divisible by 2 then it is an even number.

C++ program to calculate sum of first N even numbers

Even number

Even numbers are numbers that have a difference of 2 unit or number. In other words, if the number is completely divisible by 2 then it is an even number.

C++ program to print first N natural numbers using for loop

Natural number

Natural numbers are numbers that are common and clearly in nature. As such, it is a whole, nonnegative number.

Logic

To print the first N natural number we only have to run one single loop from 1 to N.

After taking input (num) from user start one loop from 1 to num, and then inside the loop simply print the current variable “i”.

C++ program to calculate sum of first N natural numbers

Natural number

Natural numbers are numbers that are common and clear in nature. As such, it is a whole, non-negative number.

Logic

To print the sum of first N natural numbers, we need to run one loop from 1 to N, and each time inside the loop we have to add / sum value of “i” (current number) into one temporary variable.

Once the loop is over, outside of the loop we have to print a temporary variable containing the sum of natural numbers.

C++ program to print all prime numbers between 1 to N

Prime number

A prime number is an integer greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.

Logic

To print all the prime numbers up to N, we start one loop from 2 to N and then inside the loop we check current number or “num” is prime or not. To check if it is prime or not we again need one nested loop. It is not an efficient way to check prime number but it is simpler to understand the basic of looping in C++.

C++ program to find sum of prime numbers between 1 to N

Prime number

A prime number is an integer greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.

Logic

To print the sum of all prime numbers up to N we have to iterate through each number up to the given number and check if the number is a prime or not if it is a prime number then simply sum it or add it in one temporary variable.

Once the outer loop is completed we have to print that temporary variable containing the sum of primes.

C++ program to find all factors of a number

Factor

A factor is an integer that can be divided evenly into another number or in other words factors of a number are numbers that multiply to form a product.

Logic

To print all the factors of a particular number we have to iterate through all the smaller numbers up to the given number. If the user given number is completely divisible by any number then it is a factor of that number.

C++ program to print alphabets from a to z

In this program, we are going to see how we can print alphabets in C++. The program is pretty simple and straight forward. Here ASCII value of the characters comes into the picture, we use the ASCII value of starting and end character to run the loop.

Logic

ASCII value of small letter “a” is 97 and for “z” it is 122, so we run the loop from 97 to 122 and then inside the loop we have to print the current character.

C++ program to check whether a given number is perfect number or not

Perfect number

A perfect number is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.

Logic

To check if the number is perfect or not we have to run one loop from 1 to N and sum all the numbers between 1 to N, if the sum is equal to N then it is a perfect number.

C++ program to check whether a given number is Armstrong number or not

Armstrong number

An Armstrong number is a number that is equal to the sum of the digits that rise to the total number of digits of the power. Some Armstrong numbers are: 0, 1, 2, 3, 153, 370, 407, 1634, 8208, etc.

Know more about Armstrong number – Wikipedia

Logic

After taking input from the user, we have to calculate the total number of digits in the given number. Here we are using log10 method of math library to achieve this. After doing that we have to run one loop until the value of user given number “num” does not reach 0 or becomes less than zero.

Now inside the loop each time we have to find the last digit of user given number and then calculate the power of that number with total no of digits in the “num”, round off the result and store it in one temporary variable “sum” once the loop is finished we have to check if the value of variable sum is equivalent to user given number, if yes, then it is an Armstrong number.

C++ program to check whether a number is palindrome or not

Palindrome

A palindrome is anything that reads the same backward and forward. In other words after reversing any number, word or phrase if it remains the same as original then it is a palindrome.

Logic

To check whether a number is a palindrome number or not we have to reverse it first. After reversing it we compare the reversed number with the original number. If both the numbers are similar then it means the number we have is a palindrome number.

C++ program to check whether a number is prime number or not

Prime number

A prime number is an integer which is greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.

Logic

The logic to check a number is prime or not is really simple. We only need to check if the given number is completely divisible by any other smaller number or not, but not by 1 and itself.

After taking input from the user, we have to run one loop up to half of the given number. Now the reason for running one loop up to half of the given number is because we know, a number can only be divisible by a number which is lesser than its half.

Inside the loop we have to check if the given number “num” is completely divisible by current number “i” or not, If yes then set the value of the variable i to num and terminate the loop here, if no then continue the loop.

Once the loop is completed or terminated control comes out of the loop, here we have to check if the value of the variable i is equivalent to the given number or not. If yes then it is not a Prime number otherwise it is a prime number.

C++ program to count number of digits in a given integer

Count number of digits in a given integer

To count the number of digits in a number we have to divide that number by 10 until it becomes 0 or less than 0. If you divide any number by 10 and store the result in an integer then it strips the last digit. So we have to apply the same logic here also.

Logic

After taking the input from the user, run one while loop that runs until the user given number becomes 0. Inside the loop for each iteration increase the counter variable by one and divide the user given number by 10 and store it in the same variable again.

Notice here we are using /= operator that performs division and stores the result in the same variable again.

Once the loop is over we have to print counter variable “count” containing the total number of digits.

C++ program to find product of digits in a number

Product of digits in a number

This program is closely similar to this one: Count number of digits in a given integer. The only difference here is instead of counting the total number of digits we are multiplying each digit by another one until the user given number becomes 0 or less than 0.

Logic

First of all, we are declaring one variable product with value 1, we are going to use this variable to store the product of all digits, now after taking input from the user, inside the while loop, we have to extract each digit by performing modulo operation.

The modulo operation returns the remainder after dividing a number by another number. If we perform modulo operation with 10 on any number it will return the last most digit, we have to multiply and store the result into the variable product.

After that remove the last most digit from the number and perform the same again until the number becomes 0 or less than 0. Once the loop is completed simple print the variable product containing the product of all digit.

C++ program to find sum of all digits in a number

Sum of digits in a number

This program is much similar to this one: Find product of digits in a number. The only difference is instead of multiply we have to perform addition here.

Logic

First of all, we are declaring one variable sum with value 0, we are going to use this variable to store the sum of all digits, now after taking input from the user, inside the while loop, we have to extract each digit by performing modulo operation.

The modulo operation returns the remainder after dividing a number by another number. If we perform modulo operation with 10 on any number it will return the last most digit, we have to add it into variable sum and store the result again in variable sum.

After that remove the last most digit from the number and perform the same again until the number becomes 0 or less than 0. Once the loop is completed simply print the variable sum containing the sum of all digit.

C++ program to calculate factorial of a number

Factorial

A factorial is a product of an integer and all the integers below it. In other words, factorial (!) Is the product of all integers from 1 to n.

For example:

If N = 5, then 5! is 5 x 4 x 3 x 2 x 1 = 120

Logic

First of all, we declare one temporary variable fact with value 1, now we are going to use this variable to store factorial.

After taking input from the user, we need to start one loop from 1 to N, and inside the loop we multiply current number “i” with variable fact and then store the result again in fact variable until the loop terminates. Once the loop is over we have to print the fact variable containing factorial of a given number (N).

C++ program to find HCF of two user given numbers

HCF

The greatest common divisor of two or more numerical values is called the highest common factor (HCF). In other words, the largest number that can completely divide two or more numbers is the highest common factor.

Logic

Let declare one temporary variable hcf by 1, we are going to use this variable to store HCF.

Here we are calculating HCF of two user given numbers, after taking both the numbers (num1, num2) from the user, we have to find out which number is smaller, we store the minimum one in the variable min.

Now we start one loop from 1 to min (Minimum between both numbers), and inside the loop, we have to check if both the numbers are completely divisible by current number “i” or not. If yes then we update temporary variable hcf by current number “i”, otherwise continue with the loop.

Once the loop is over simply print the variable hcf containing the highest common factor of num1 and num2.

C++ program to find LCM of two user given numbers

LCM

The least / lowest common multiple (LCM) of two or more than two numbers is the smallest number (not zero) which is a multiple of all of the numbers.

Logic

Let declare one temporary variable lcm by 1, we are going to use this variable to store LCM.

Here we are calculating LCM of two user given numbers, after taking both the numbers (num1, num2) from the user, we have to find out the maximum number, we store the maximum one in variable max and also assign the value of max to the variable i.

Now we start one infinite loop while(1), inside the loop we have to check if both the numbers can completely divide max value. If yes then we terminate the loop with break statement and assign current value of “i” to lcm, otherwise, continue the loop.

Once the loop is over, simply print the variable lcm containing the lowest common multiple of num1 and num2.

C++ program to calculate power of a number using for loop

Power of a number

The power of a number represents the number of times to use that number in a multiplication. Usually, power is represented with a base number and an exponent.

Logic

Let’s declare one temporary variable power with value 1, we have used the data-type long long so that it can hold a big long value.

To calculate the power of a number we need a base and an exponent value, we are taking these two values from the user, after taking input (base, exponent) from the user we start one loop from 1 to exponent.

Inside the loop, for every iteration, we multiply the base by power (base * power) and store the result again in variable power until the loop is completed.

Once the loop is over, simply print the variable power containing the resultant power value of a given number.

C++ program to find reverse of any number

n this program, we are going to see how we can reverse any user given number. Reversing any word, phrase or number is pretty simple if we treat it as a string data. We can simply iterate through each character in reverse order and then append it to one temporary variable. But here we are only dealing with numbers and for numbers, there is a better approach.

Logic

First of all, we have to declare one temporary variable reverse with value 0, we will use this variable to store the reverse of the number.

After taking input from the user, we have to assign the input to one temporary variable temp, Now to reverse a number we have to extract each digit of that number one by one. To extract digits we can use % (modulo) operator. If we perform modulo operation with 10 on any number it will return the last most digit.

Now after extracting the digit, we have to append it to our temporary variable reverse, but we cannot directly append the digit on it. To append the digit, first, we need to multiply 10 on existing reversed value and then perform addition with the extracted digit.

At the end remove the last most digit and repeat the same again until the value of temp becomes 0 or less than 0.

Once the loop is finished simply print the variable reverse.

C++ program to print multiplication table of a any given number

In this program, we are going to see how we can print the multiplication table of any user given input number.

Logic

Printing multiplication table of any number is quite simple and an easy task. After taking input (num) from the user we have to start one loop from 1 to 10, and then inside the loop simply multiply num by current number “i” and print it.

Area of Triangle with Base & Heigth

This program finds area of a triangle based on its base and height value. The question is, write a program in C++ to find area of a triangle with base and height entered by user at run-time. Here is its answer.

Perimeter of Triangle with 3 Sides

Now let’s create a program to find the perimeter of a triangle using values of its three sides given by user at run-time:

Find Area of Circle

To calculate area of any circle in C++ programming, you have to ask from user to enter the radius of circle, place the radius in a variable say rad and then initialize 3.14*rad*rad in a variable that holds the value of area of circle, as shown here in the following program.

Find Circumference of Circle

The question is, write a program in C++ to find circumference of a circle. The answer to this question is:

Program to find area of a trapezoid in C++

we will learn how to calculate or find the area of a trapezoid in C++.

A trapezoid is a quadrilateral with two parallel sides and the other two sides which are not parallel. The parallel sides are called bases and the other two sides are called legs.

Leave a Comment