Programming Code Examples

C++ Program Examples | C++ Code Examples48 min read

While learning any programming language, practicing the language with examples will help you to understand the concepts better.

We have collected the List of Frequently asked questions (FAQ code examples) in C++ programming. the list contain C++ language basic and simple source codes and examples. This list of C++ tutorials with examples can be very useful to learn the basic concepts in C++.




Example 1: C++ Program to Print Hello World

To print Hello, World! in C++ programming, just place Hello, World! inside inverted comma (“”) after cout<< as shown in the program given below:

The question is, write a program in C++ to print Hello, World!. Here is its answer:

Example 2: C++ Program to Get Input from User

This C++ program asks from user to enter an integer value or number to receive it and store in a variable say val. Then further displays the entered number on the screen:

Example 3: C++ Program to Print an Integer

To print any integer or number on output in C++ programming, just put the variable that holds the value, after cout<< like:

whatever the value of num is, it gets printed on output. Here is the complete program on printing of an integer value along with some string (or message) before it.

Example 4: C++ Program to Add Two Numbers

Let’s first start with very simple program for the addition of two number. The dry run of this program is given just after the output.

Example 5: C++ Program to Perform Addition Subtraction Multiplication Division

To perform addition, subtraction, multiplication and division of any two numbers in C++ programming, you have to ask from user to enter the two numbers to perform all the basic mathematical operation such as addition, subtraction, multiplication, and division. And display the result on the screen as shown in the program given below.

The subtraction and division operation goes in a way that, the second number gets subtracted from the first one. Similarly, second number divides the first one. For example, if user enters 20 and 10 as first and second number. Then, the subtraction result will be 10, because 10 (the second number) gets subtracted from 20 (the first number). And the division result will be 2, because 10 divides 20.

Example 6: C++ Program to Find Sum of Digits of a Number

To add digits of any number in C++ programming, you have to ask from user to enter the number to add its digits and display the addition result on output screen as shown here in the following program.

Let’s first start while loop. That is, the program given below find and prints the sum of digits of a number using while loop in C++.

The same program is created here using for loop. Unlike while loop, the initialization and update part can also be written under for loop. Therefore, we have initialized the value of sum=0 as first statement of for loop, the second statement is condition checking as done in while loop, and at last, the update part is written as the third statement under for loop. Rest of the things will be same

Example 7: C++ Program to Calculate Average, Percentage Marks

To find average marks in n number of subjects, just add all the marks and divide it by n. For example, to find average mark with marks obtained in three subjects say 10, 20, 30, then it will be:

To find percentage mark, use following formula:

For example, if marks of three subjects are 10, 11, 12 out of 25. That is, the maximum mark is 25. And out of 25, the student got 10, 11, 12 in 3 subjects. Therefore, his/her percentage mark can be calculated as:

To calculate average and percentage marks (in 5 subjects) of a student in C++ programming, you have to ask from user to enter marks obtained in 5 subjects.

Now place the summation result of 5 subject’s mark in a variable say sum and place sum/5 in a variable say avg (average of 5 subjects). Then place sum/500*100 in a variable say perc (percentage marks), then display the result on the screen as shown here in the following program.

Example 8: C++ Program to Calculate Arithmetic Mean

If there are n set of numbers, therefore to find arithmetic mean, we have a formula:

Here am indicates arithmetic mean, whereas n1n2n3, and nn indicates first, second, third, and last number.

For example, if we have 5 set of numbers say 10, 20, 30, 40, 50, then its arithmetic means can be calculated as:

To calculate (or find) arithmetic mean (of numbers) in C++ programming, you have to ask from user to enter the size (how many set of number), then ask to enter all numbers of that size to find and print arithmetic mean.

To calculate arithmetic mean of numbers, first perform addition of all the numbers, then make a variable responsible for the arithmetic mean and place addition/size in a variable say armean (arithmetic mean), then display the result on the output screen as shown here in the following program.

This function does the same job as of previous program. But it is created using function. That is, a function arithmeticMean() takes two arguments, the first one is the array, and second is the size. And returns the arithmetic mean of all numbers stored in the array.

Example 9: C++ Program to Find and Print Sum of First n Natural Numbers

The question is, write a program in C++ that receives the value of n and print the sum of first n natural numbers. Here is its answer:

This program is created using for loop, instead of while.

This is the last program created using a user-defined function named myfun() that takes an integer say n as its argument, then find and return the sum of first n natural numbers.

Example 10: C++ Program to Add n Numbers

To add n numbers in C++ programming, you have to ask from user to enter the value of n (i.e., how many numbers he/she wants to enter), then ask to enter n numbers to perform the addition of all the given numbers and finally display the result on the screen as shown here in the following program.

This program is created using for loop to do the job. The question is, write a program in C++ to find and print the sum of n numbers using for loop. And here is the answer to this question:

The question is, write a program in C++ that find and prints the sum of n given numbers using while loop. The answer to this question is given below:

Example 11: C++ Program to Find Area, Perimeter of Square

To find area of a square, use following formula:

len indicates the length of square. Because all the sides are of equal length in square, therefore get the length of side and square it. That will be the area.

To find perimeter of a square, use following formula:

To calculate area of a square in C++ programming, you have to ask from user to enter the side length of square. With this side length, apply the formula as given above and initialize its value to a variable say area and print its value as output as shown here in the following program.

Example 12: C++ Program to Find Area, Perimeter of Rectangle

The formula to calculate area of a rectangle is given below:

Here, len indicates length and bre indicates breadth of rectangle.

To calculate perimeter of rectangle, use following formula:

Here also, len and bre indicates to length and breadth of the rectangle. Now let’s move on to the program.

The question is, write a program in C++ to find and print area of a rectangle. The program given below is the answer of this question:

Example 13: C++ Program to Find Area, Perimeter of Triangle

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.

Example 14: C++ Program to Find Area, Circumference of Circle

Before starting the program, let’s first get the formula used to find area and circumference of a circle.

To find area of a circle, use this formula:

The value of π is 3.14. And r indicates radius of circle. This formula can also be written as:

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.

Example 15: C++ Program to Calculate Simple Interest

The question is, write a program in C++ to find and print simple interest based on the PR, and T (data) entered by user at run-time. The program given below is the answer to this question:

Example 16: C++ Program to Convert Fahrenheit to Celsius

To convert temperature from Fahrenheit to Celsius in C++ programming, you have to ask from user to enter the temperature in Fahrenheit first. And then convert it into its equivalent value in Celsius with the formula given above.

The question is, write a program in C++ that receives temperature in degree Fahrenheit and prints its equivalent value in degree Celsius.. Here is its answer:

Example 17: C++ Program to Convert Celsius to Fahrenheit

To convert temperature from Celsius (or centigrade) to Fahrenheit in C++ programming, you have to ask from user to enter the temperature in Celsius. And then convert it into its equivalent value in Fahrenheit using the formula given above, as shown in the program given below:

Example 18: C++ Program to Print Prime Numbers

This program prints all prime numbers between 1 to 100 using for loop. The question is, write a program in C++ to print prime numbers from 1 to 100. Here is its answer:

Example 19: C++ Program to Reverse a Number

To reverse a number in C++ programming, then you have to ask from user to enter a number. Now find the reverse of that number, and then print its reverse on output as shown in the program given below:

The question is, write a program in C++ to reverse a number. Here is its answer:

Example 20: C++ Program to Swap Two Numbers

To swap two numbers in C++ programming, you have to ask from user to enter the two numbers. The entered two numbers gets stored in two variables say numOne and numTwo. Now swap both numbers using its variable as shown in the program given below:

Example 21: Program to Make Simple calculator in C++

Write a program and call it calc.cpp which is the basic calculator and receives three values from input via keyboard.

  • The first value as an operator (Op1) should be a char type and one of (+, -, *, /, s) characters with the following meanings:
    • ‘+’ for addition (num1 + num2)
    • ‘-’ for subtraction (num1 – num2)
    • ‘*’ for multiplication (num1 * num2)
    • ‘/’ for division (num1 / num2)
    • ‘s’ for swap
  • Program should receive another two operands (Num1, Num2) which could be float or integer.
  • The program should apply the first given operator (Op1) into the operands (Num1, Num2) and prints the relevant results with related messages in the screen.
  • Swap operator exchanges the content (swap) of two variables, for this task you are not allowed to use any further variables (You should use just two variables to swap).

Example 23: C++ Program to Find LCM and HCF (GCD) of Two Numbers

To find the LCF of two numbers in C++ programming, you have to ask from user to enter the two number. Then find and print its LCM on output as shown in the program given below.

Note – LCM is the Lowest Common Multiple or Least Common Divisor. For example, if there are two numbers say 10 and 12. Then its Least Common Divisor is 60. That is, both numbers 10 and 12 divides 60 without leaving any remainder (or with leaving 0 as remainder).

Unlike LCM, that deals multiple (lowest common), HCM deals with factor (highest common). HCF can be called as Highest Common Factor, or Greatest Common Factor (GCD).

For example, if there are two numbers say 10 and 12, then its highest common factor is 2. That is, 2 is the highest number that divides both the number. 1 also divides both numbers, but 2 is greater, so 2 is HCF of 10 and 12.

Example 24: C++ Program to Make Simple Calculator

The program given below creates a simple calculator in C++ programming that performs four basic mathematical operations such as addition, subtraction, multiplicatin, and division, depending on the user’s choice.

To do the task of calculator, first receive the choice and then any two numbers (if choice is not to exit). Then use the switch case to identify the choice and perform required things as shown in the program given below:

The question is, write a calculator program in C++. Here is its answer:

Example 25: C++ Program to Count Total Digits in a Number

The question is, write a C++ program that receives a number from user to count and print the total number of digits available in that given number. Here is the answer to this question:

Example 26: C++ Program to Find Sum of First and Last Digit of a Number

The question is, write a program in C++ that receives a number from user as input and print the sum of first and last digit of given number as output. Here is its answer:

Since for loop also contains initialize and update statements along with condition checking. Therefore, just place any initialization say temp=0 or sum=0 and the update statement as num = num/10 like shown in the program given below:

Example 27: C++ Program to Find and Print Product of Digits of a Number

The question is, write a C++ program that receives a number from user and print the product or multiplication of its digit. The program given below is its answer:

Example 28: C Program to show Fibonacci Series

Write a C program , that prints all the Fibonacci numbers , which are smaller than or equal to a number k(k≥2) ,which was entered by the user.

  • The Fibonacci numbers are a sequence of numbers,where then-th number of Fibonacci is defined as:
  • Fib(0)=0,
  • Fib(1)=1,
  • Fib(n)=Fib(n-1)+Fib(n-2) Usage :> Input of k:21 > Fibonacci numbers<=21:01123581321

Solution 1 –

The solution below will answer following questions :
1. Write a program to generate the Fibonacci series in C.
2. Fibonacci series in C using for loop.
3. How to print Fibonacci series in C.
4. Write a program to print Fibonacci series inC.
5. How to find Fibonacci series in C programming.
6. Basic C programs Fibonacci series.

Solution 2 –

If we want to Write a program to generate the Fibonacci series in C using recursion, the follow the solution below :

Solution 3 –

The solution below will answer following questions :
1. Fibonacci series using array in C
2. Fibonacci series program in C language
3. Source code of Fibonacci series inC
4.Write a program to print Fibonacci series in C

Example 29: C++ Program to Find Sum of Squares of Digits of a Number

For example, if given number is 32041, then the result will be calculate as:

The question is, write a C++ program that receives a number from user to find and print the sum of squares of its digits. The program given below is its answer:

Example 30: C++ Program to Interchange the Digits of a Number

To interchange first and last digit of a number in C++ programming, you have to ask from user to enter the number. And then interchange its first and last digit as shown in the program given below:

The question is, write a program in C++ to interchange first and last digit of a number. Here is its answer:

Example 31: C++ program to find Square Root of a Number

In this Example we will learn how to find the square root of a given number using C++.

In the first example we are going to use std::pow function to calculate the square root.

Now In the next example we will learn how to find the square root of a given number using std::sqrt function.

Example 32: C++ Program to Find Cube Root of Number

In this example we will learn C++ Program to Find Cube Root of Number.

In the first example we will use std::pow function to find the cube root of a given number.

In the next example we will use std::cbrt function to find the cube root of a given number.

Example 33: C++ program to find ASCII Code for Characters and numbers

C++ Program Write a Program to Enter Char or Number and Check its ASCII Code

Example 34: C Program to show Fibonacci Series

Write a C program , that prints all the Fibonacci numbers , which are smaller than or equal to a number k(k≥2) ,which was entered by the user.

  • The Fibonacci numbers are a sequence of numbers,where then-th number of Fibonacci is defined as:
  • Fib(0)=0,
  • Fib(1)=1,
  • Fib(n)=Fib(n-1)+Fib(n-2) Usage :> Input of k:21 > Fibonacci numbers<=21:01123581321

Solution 1 –

The solution below will answer following questions :
1. Write a program to generate the Fibonacci series in C.
2. Fibonacci series in C using for loop.
3. How to print Fibonacci series in C.
4. Write a program to print Fibonacci series inC.
5. How to find Fibonacci series in C programming.
6. Basic C programs Fibonacci series.

Solution 2 –

If we want to Write a program to generate the Fibonacci series in C using recursion, the follow the solution below :

Solution 3 – The solution below will answer following questions : 1. Fibonacci series using array in C 2. Fibonacci series program in C language 3. Source code of Fibonacci series inC 4.Write a program to print Fibonacci series in C

Example 36: C++ Program to Check Palindrome Number

In this example we will learn how to Check if the particular number is Palindrome or not.

C++ – PALINDROMIC NUMBERS Example

Example 37: C++ Program for random number generator

Random number generator using C++

Example 38: C++ Examples – Bubble sort in C++ code example

Example 39: C++ Program to Check Leap Year

In the Julian Calendar, Leap Year (LY) occurs every year divisible by 4. Normally February has 28 days but in a leap year February has 29 days.

In this lesson we will learn how to write a C++ program to check if the giver year is leap year or not.

Example 40: C++ program for Calculation of the surface Area and volume of cone

Write a program that calculates the volume of a solid cone.The formula is: volume=(PI x radius² x height)/3
Read in the values for the parameters height and radius(as floating point numbers).
Then the program should calculate the volume considering the following restriction :radius and height must be greater than0
If the user types in a correct value for one of the variables ,the program should print out an error message and quit.Otherwise,it displays the result.

Example 41: Write a C++ program to Solve Quadratic equation

Write a program that calculates the real solution of the quadratic equation ax²+bx+c=0
Read in the values for the parameters a,b,c(type float).
Then the program should calculate the solution considering the following circumstances:
a=0andb=0=>Not a valid equation
a=0 and b≠0 => x=-c/b
b² -4ac < 0 => Not a Real Solution
b² -4ac >0 => x1= (-b+√(b² -4ac))/2a , x1= (-b -√(b² -4ac))/2a
Hint:The c++ function for √x is sqrt(x).
To use this function you need to includemath.has a header file#include<math.h>

Example 42: C++ Program to find the Factorial using recursive function

Example 43: C++ program to convert a string into upper-case or lower-case

Here we will learn c++ program in order to convert a string into upper case or lower case.

Example 44: C++ program to concatenate strings

Here we will learn how to write a program to Concatenate strings.

Example 45: Write a C++ program to 1. Initialize Matrices 2. Print Matrices 3. Multiply Matrices 4. Transpose of 2nd Matrix 5. Move Row and Column of 2nd Matrix 6. Quit

Write a program that shows a menu such as figure 2.1 and does the following described tasks for entered number between 1 and 6.

The instruction menu:1. Initialize Matrices2. Print Matrices3. Multiply Matrices4. Transpose of 2nd Matrix5. Move Row and Column of 2nd Matrix6. QuitPlease enter your requested instruction (1..6)?Note that to do the specific task related to each menu user should press relevant number. (e.g. ‘2’ for print task or ‘4’ for transpose operation). The description of tasks is as follows:

1. Initialize:In this step, your program should get dimensions for two matrices from input and initials these matrices randomly based on the entered dimensions. Note that your program should initialize matrices with different numbers in each time of execution. The first matrix should be square matrix. A square matrix is a matrix with the same number of rows and columns. Note that user can re-initialize matrices (and of course dimensions) by using the first command during the executionPlease enter the number of rows and columns for the first square matrix? 3Please enter the number of rows for the second matrix? 4Please enter the number of columns for the second matrix? 6

2. Print:In this step, your program should print the content of two matrices in the screen as showed in the figure 2.3. The “Print” operation could be requested after each step to see the changes which have been made during the execution of different instructions. It means that you do not need to show the results of each operation in the screen, user has to request instruction number ‘2’ to see the actual content of matrices.Content of the first Matrix (3*3):1 3 59 7 898 6 51Content of the second Matrix (4*6):34 73 83 23 98 2081 92 68 28 34 76-65 78 -12 67 1 12389 -61 67 43 17 843. Multiplication:In this step, your program should multiplies two matrices A and B (C=A*B).

4. Transpose:In this step, your program should calculate transpose of the second matrix. Wikipediadefined transpose of a matrix as follows:“In linear algebra, the transpose of a matrix A is another matrix AT created by any one of thefollowing equivalent actions: reflect A over its main diagonal (which runs top-left to bottom-right) to obtain AT write the rows of A as the columns of AT write the columns of A as the rows of AT visually rotate A 90 degrees clockwise, and mirror the image in a vertical line toobtain ATFormally, the (i,j) element of AT is the (j,i) element of A. [AT]ij = [A]jiIf A is an m × n matrix then AT is an n × m matrix.”

5. Move row and column:In this step, your program should get two numbers (m, n) and first movesthe row number m of the second matrix to the end of the matrix and then moves the columnnumber n of the matrix to the end of the matrix

6. Quit:In this step, the execution should be ended. Note that your program shouldn’t be finished inother steps. It means that user can request multiple executions of different steps before requesting the “Quit” operation.

Points:User needs to initiate matrices at least once by requesting step ‘1’ at the beginning of an execution.Therefore you should prevent the user for requesting other steps before step ‘1’ just once at thebeginning of an execution.

Solution-