C++ program to Find Factorial of a Number Using Recursion

In the previous article, we have discussed C++ Program to Generate Random Numbers. In this article, we will see C++ program to Find Factorial of a Number Using Recursion.

C++ program to Find Factorial of a Number Using Recursion

  • Write a C++ program to find factorial of a number using recursion.
  • Recursive algorithm to calculate factorial of a number.

In this C++ program, we will find factorial of a number using recursion.

The factorial of a integer N, denoted by N! is the product of all positive integers less than or equal to n.
N! = 1 x 2 x 3 x 4….x (N-2) x (N-1) x N
For Example :

6! = 6 * 5 * 4 * 3 * 2 * 1 = 720.
0! = 1
1! = 1

NOTE : Factorial does not exist for negative numbers and factorial of 0 is 1.
The expression to calculate factorial obeys recursive sub-structure property, hence we can use use recursion to calculate factorial.

Let factorial(N) is a function to calculate the value of N!. To find factorial(N) we can first calculate factorial(N-1) then multiply it with N.

N! = 1 x 2 x 3 x 4....x (N-2) x (N-1) x N
N! = (N-1)! x N
factorial(N) = factorial(N-1) x N

Function factorial(N) reduces the problem of finding N! into sub-problem of finding (N-1)! first and then multiplying it with N to get N!. It keeps on reducing the domain of the problem until N becomes zero.

C++ program to Calculate Factorial of a Number Using Recursion

C++ program to Calculate Factorial of a Number Using Recursion

// C++ program to Calculate Factorial of a Number 
// Using Recursion
#include <iostream>
using namespace std;
   
int getFactorial(int N);
  
int main(){
    int N;
    cout << "Enter a Number\n";
    cin >> N;
   
    cout << "Factorial of " << N << " = " << getFactorial(N);
       
    return 0;
}
   
// Recursive function to find factorial of a number
int getFactorial(int N){
    // Recursion Termination condition
    if(N <= 1){
         return 1;
    }
    return N * getFactorial(N - 1);
}

Output

Enter a Number
5
Factorial of 5 = 120

In above program, we are using a recursive function getFactorial(N) to calculate the factorial of N. If N <= 1, then getFactorial function returns 1, (this is the recursion termination condition) otherwise, it recursively calls itself to calculate factorial of N-1 and multiply it with N to get N!.

Inside main function, we first take a number as input from user using cin ans store it in a variable N. Then we call getFactorial function by passing N as parameter to calculate N!. Above c++ program cannot be used to calculate factorial of large numbers because factorial of such numbers exceeds the range of int data type.

Learn and explore basic C++ Practice Programs that help to enhance your skills & knowledge of the programming language. Get to know how to write simple and clear code on this page.

C++ Program to Generate Random Numbers

In the previous article, we have discussed C++ Program to Make a Simple Calculator. In this article, we will see C++ Program to Generate Random Numbers.

C++ Program to Generate Random Numbers

In this C++ program, we generate N random numbers between 1 to 1000 using rand function. This program takes N as input from user and print N space separated random numbers on screen.

  • The rand function of cstdlib standard library returns a pseudo-random number in the range of 0 to RAND_MAX, where RAND_MAX is a environment dependent value which is the maximum value returned by rand function.
  • To generate random numbers between 1 to 1000, we will evaluate rand()%1000, which always return a value between 0 to 999. We will add 1 to this value to get a number between 1 to 1000.
  • The probability of selection of any number between 1 to 1000 is 1/1000 or 0.001.

C++ Program to Generate Random Numbers using Rand Function

C++ Program to Generate Random Numbers using Rand Function

// C++ program to print N random numbers between 1 to 1000
 
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
 
int main() {
    int n, random;
    cout << "Enter number of random numbers\n";
    cin >> n;
  
    // print n random numbers using rand function
    cout << "Random numbers between 0 to 1000\n";
    while(n--){
        random = rand()%1000 + 1;
        cout << random << " ";
    }
     
    return 0;
}

Output

Enter number of random numbers
7
Random numbers between 0 to 1000
42 764 431 831 335 170 501

In above C++ program, we first take the count of random numbers as input from user and store it in variable “n”. The using a while loop, we call rand function “n” times to generate random number between 1 to 1000 and print it on screen.

Explore various CPP Codes lists that are used in C++ programming to write a sample program. These codes play an important role while learning the programs.

C++ Program to Make a Simple Calculator Using Switch Case Statement

In the previous article, we have discussed C++ Program to Check Leap Year. In this article, we will see C++ Program to Make a Simple Calculator Using Switch Case Statement.

C++ Program to Make a Simple Calculator Using Switch Case Statement

  • Write a C++ program to make a simple calculator for addition, subtraction, multiplication and division using switch case statement.

In this C++ Program, we will make a simple calculator using switch case statement to perform basic arithmetic operations like Addition, Subtraction, Multiplication and Division of two numbers. Before jumping into program, we need a basic understanding of arithmetic operators of C++.

An arithmetic operator is a symbol used to perform mathematical operations in a C++ program. The four fundamental arithmetic operators supported by C++ language are addition(+), subtraction(-), division(/) and multiplication(*) of two numbers.

Operator Description Syntax Example
+ Adds two numbers a + b 15 + 5 = 20
Subtracts two numbers a – b 15 – 5 = 10
* Multiplies two numbers a * b 15 * 5 = 75
/ Divides numerator by denominator a / b 15 / 5 = 3

C++ Program to Make a Simple Calculator using Switch Case Statement

C++ Program to Make a Simple Calculator using Switch Case Statement

// C++ program to make a simple calculator to Add, Subtract, 
// Multiply or Divide using switch...case statement
#include <iostream>
using namespace std;
  
int main() {
    char op;
    float num1, num2;
      
    cout << "Enter an arithemetic operator(+ - * /)\n";
    cin >> op;
    cout << "Enter two numbers as operands\n";
    cin >> num1 >> num2;
  
    switch(op) {
        case '+': 
                cout << num1 << " + " << num2 << " = " << num1+num2;
                break;
        case '-':
                cout << num1 << " - " << num2 << " = " << num1+num2;
                break;
        case '*':
                cout << num1 << " * " << num2 << " = " << num1*num2;
                break;
        case '/':
                cout << num1 << " / " << num2 << " = " << num1/num2;
                break;
        default: 
                printf("ERROR: Unsupported Operation");
    }
      
    return 0;
}

Output

Enter an arithemetic operator(+ - * /)
+
Enter two numbers as operands
2 8
2 + 8 = 10
Enter an arithemetic operator(+ - * /)
*
Enter two numbers as operands
3 7
3 * 7 = 21

In above program, we first take an arithmetic operator as input from user and store it in a character variable op. Our calculator program only support four basic arithmetic operators, Addition(+), Subtraction(-), Multiplication(*) and Division(/). Then we take two integers operands as input from user and store it in variable num1 and num2.

We are using switch case statement for selecting appropriate arithmetic operation. Based on the operator entered by the user(+, -, * or /), we perform corresponding calculation and print the result on screen using cout.

If the arithmetic operator entered by the user doesn’t match with ‘+’, ‘-‘, ‘*’ or ‘/’ then default case block will print an error message on screen.

We know that C++ is an object oriented programming language. The advanced C++ Topics are enumerated constants, multi-dimensional arrays, character arrays, structures, reading and writing files and many more. Check the complete details of all those from this article.

C++ Program to Print Pascal Triangle

In the previous article, we have discussed C++ Program to Print Floyd Triangle. In this article, we will see C++ Program to Print Pascal Triangle.

C++ Program to Print Pascal Triangle

  • Write a C++ program to print pascal triangle.

In this C++ program we will print a Pascal Triangle. Pascal Triangle is a right pyramid of binomial coefficients. Nth row of pascal triangle contains N binomial coefficients. Here is the formulae to find the value of nth element of rth row of pascal triangle.
Pascal_triangle

A pascal triangle of 5 rows :

      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

Algorithm to print Pascal triangle
Let N be the number of rows in pascal triangle.

  • We will use nested for loop to print pascal triangle. One iteration of Outer for loop will print one row of triangle.
  • In Kth row of pascal triangle, first we have to print N-K white spaces.
  • After white spaces we will print K space seperated binomial coefficients.
  • At the end of every row, we will print a newline character.

C++ Program to Print Pascal Triangle

C++ Program to Print Pascal Triangle

// C++ program to print Pascal triangle
 
#include <iostream>
using namespace std;
    
//Function to calculate factorial of a number 
int getFactorial(int N){
    if(N < 0){
     // Invalid input
        return -1;
    }
     
    int nFactorial = 1, i;
    //  N! = N*(N-1)*(N-2)*(N-3)*.....*3*2*1
    for(i = 1; i <= N; i++){
        nFactorial = nFactorial * i;
    }    
    return nFactorial;
}
    
int main() {  
    int row, rows, i, value;
    
    cout << "Enter Number of Rows of Pascal Triangle\n";  
    cin >> rows;  
    
    for(row = 0; row < rows; row++) {  
        // Print Spaces for every row  
        for(i = row; i <= rows; i++)  
            cout << "  ";  
    
        for(i = 0; i <= row; i++) {  
            value = getFactorial(row)/(getFactorial(i)*getFactorial(row-i));  
            cout << "  " << value;  
        }  
        cout << endl;  
    }  
    
    return 0;  
}

Output

Enter Number of Rows of Pascal Triangle
5
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

In above program, we first take the number of rows in pascal triangle using for loop. Then using for loops we will print the pascal triangle as per above mentioned algorithm. Here we write a getFactorial function which returns the factorial of a number. We are calling this function to calculate binomial coefficients.

Discover a comprehensive collection of C++ Program Examples ranging from easy to complex ones and get help during your coding journey.

C++ Program to Print Floyd Triangle

In the previous article, we have discussed C++ Program to Find Area and Perimeter of Parallelogram. In this article, we will see C++ Program to Print Floyd Triangle.

C++ Program to Print Floyd Triangle

In this C++ program we will print a Floyd Triangle of N rows. A Floyd’s triangle is a right angled triangle of natural numbers arranged in increasing order from left to right such that Nth row contains N numbers.

A floyd’s triangle of 6 rows :

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

In this program, we first take number of rows of Floyd’s triangle as input from user and store it in a variable rows. Then using two for loops we will print N consecutive natural numbers in Nth row. Here outer for loop prints one row in every iteration where as inner for loop prints numbers of one row. Between any two consecutive numbers in a line we will print a space character.
Here we are using for loop but same program can be rewritten using while loop or do while loop.

C++ Program to Print Floyd Triangle

C++ Program to Print Floyd Triangle

// C++ program to print Floyd's triangle
 
#include <iostream>
using namespace std;
  
int main() {
    int i, j, rows, counter;
  
    cout << "Enter the number of rows of Floyd's triangle\n";
    cin >> rows;
  
    // Print Floyd's triangle
    for (counter = 1, i = 1; i <= rows; i++) {
     // Print ith row 
        for (j = 1; j <= i; j++) {
            cout << counter++ << " ";
        }
        cout << endl;
    }
      
    return 0;
}

Output

Enter the number of rows of Floyd's triangle
4
1
2  3
4  5  6
7  8  9 10

Want to get a good grip on all concepts of C++ programming language? Just click on Important C++ Programs with Solutions and kickstart your learnings with coding.

C++ Program to Find Area and Perimeter of Parallelogram

In the previous article, we have discussed C++ Program to Find Area and Circumference of a Circle. In this article, we will see C++ Program to Find Area and Perimeter of Parallelogram.

C++ Program to Find Area and Perimeter of Parallelogram

In this C++ program, we will calculate perimeter and area of parallelogram. Before jumping to C++ program, let’s first discuss about parallelogram and it’s properties.

A parallelogram is quadrilaterals(having four sides) with opposite sides parallel and equal in length. Opposite angles of a parallelogram are also equal.
Properties of Parallelogram

  • Opposite angles of a parallelogram are equal.
  • Diagonals of a parallelogram divides each other in two equal half.
  • Opposite sides of a parallelogram are parallel and equal in length.
  • The sum of any two adjacent angles of a parallelogram are 180 degrees.

C++ Program to Find Area of Parallelogram

To calculate the area of parallelogram we need length of Base and Height.

  • Base : We can choose any side of a parallelogram as base to calculate area of parallelogram.
  • Height : Height of a parallelogram is the perpendicular distance between the base and it’s opposite side.

Area of Parallelogram
The area of a parallelogram can be calculated by multiplying Base and Height.

Area of Parallelogram = B X H
Where,

  • B is the length of base of parallelogram.
  • H is the length of height of parallelogram.

C++ Program to Find Area of Parallelogram
C++ Program to Find Area of Parallelogram

// C++ Program to calculate area of Parallelogram
 
#include <iostream>
using namespace std;
  
int main(){
    float base, height, area;
    cout << "Enter the base and height parallelogram\n";
    cin >> base >> height;
     
    // Area of parallelogram = base X height 
    area = base * height;
    cout << "Area of parallelogram : " << area;
      
    return 0;
}

Output

Enter the base and height parallelogram
8 5
Area of parallelogram : 40

C++ Program to find Perimeter of parallelogram

The perimeter of a parallelogram can be calculated by adding the length of all four sides of parallelogram. As we know the length of opposite sides of parallelogram are equal, we can add any two adjacent sides of parallelogram and then multiply it with 2 to get perimeter of parallelogram.

Perimeter of parallelogram

Perimeter of Parallelogram = 2X(S1 + S2)
Where, S1 and S2 are length of adjacent sides of parallelogram.
C++ Program to find Perimeter of parallelogram

// C++ Program to calculate perimeter of Parallelogram
 
#include <iostream>
using namespace std;
  
int main(){
   float side1, side2, perimeter;
   cout << "Enter the length of adjacent sides of parallelogram\n";
   cin >> side1 >> side2;
   // Perimeter of parallelogram = 2X(side1 + side2)
   perimeter = 2*(side1 + side2);
   cout << "Perimeter of parallelogram : " << perimeter;
 
   return 0;
}

Output

Enter the length of adjacent sides of parallelogram
10 4
Perimeter of parallelogram : 28

The comprehensive list of C++ Programs Examples covered in our pages are very useful for every beginners and experienced programmers. So, make use of these C++ Coding Exercises & hold a grip on the programming language.

C++ Program to Find Area and Circumference of a Circle

In the previous article, we have discussed C++ Program to Store Information of an Employee in Structure. In this article, we will see C++ Program to Find Area and Circumference of a Circle.

C++ Program to Find Area and Circumference of a Circle

In this C++ program, we will calculate circumference and area of circle given radius of the circle.

The area of circle is the amount of two-dimensional space taken up by a circle. We can calculate the area of a circle if you know its radius. Area of circle is measured in square units.

Area of Circle = PI X Radius X Radius.
Where, Where PI is a constant which is equal to 22/7 or 3.141(approx)
C++ Program to Find Area and Circumference of a Circle

C++ Program to Find Area of Circle

C++ Program to Find Area of Circle

// C Program to calculate area of a circle
 
#include <iostream>
using namespace std;
  
#define PI 3.141
  
int main(){
    float radius, area;
    cout << "Enter radius of circle\n";
    cin >> radius;
    // Area of Circle = PI x Radius X Radius
    area = PI*radius*radius;
    cout << "Area of circle : " << area;
      
    return 0;
}

Output

Enter radius of circle
7
Area of circle : 153.909

In above program, we first take radius of circle as input from user and store it in variable radius. Then we calculate the area of circle using above mentioned formulae and print it on screen using cout.

C++ Program to Find Circumference of Circle

Circumference of circle is the length of the curved line which defines the boundary of a circle. The perimeter of a circle is called the circumference.
We can compute the circumference of a Circle if you know its radius using following formulae.

Circumference or Circle = 2 X PI X Radius
We can compute the circumference of a Circle if you know its diameter using following formulae.

Circumference or Circle = PI X Diameter
C++ Program to Find Circumference of Circle

// C Program to calculate circumference of a circle
 
#include <iostream>
using namespace std;
  
#define PI 3.141
  
int main(){
    float radius, circumference;
    cout << "Enter radius of circle\n";
    cin >> radius;
    // Circumference of Circle = 2 X PI x Radius
    circumference = 2*PI*radius;
    cout << "Circumference of circle : " << circumference;
      
    return 0;
}

Output

Enter radius of circle
7
Circumference of circle : 43.974

In above program, we first take radius of circle as input from user and store it in variable radius. Then we calculate the circumference of circle using above mentioned formulae and print it on screen using cout.

Are you fed up with browsing all concepts related to C++ Programming Programs? Not anymore because all the basic and complex Programs for C++ are covered on our main page just tap on the link available here & save your time to practice more.

C++ Program to Store Information of an Employee in Structure

In the previous article, we have discussed C++ Program to Add Two Distances in Inch and Feet Using Structures. In this article, we will see C++ Program to Store Information of an Employee in Structure.

C++ Program to Store Information of an Employee in Structure

  • Write a C++ program to store data of an Employee in a structure variable.

In this C++ program, we will store the information of an Employee in a structure variable and then display it in screen. We want to store following information for an employee Name, Salary, Employee Code and Department. Here is a sample employee record :

Name : Jason Donald
Salary : 53463
Employee Code : 1234
Department : CSE

To store the information of employee, we will define an Employee structure containing all required information of employee.

struct Employee {
    char name[50];
    int salary;
    int employeeCode;
    char dept[5];
};

Then we will create a variable of Employee structure, let’s say emp. Then to access the members of emp, we will use member access operator or dot(.) operator.

C++ Program to Store Information of an Employee in a Structure

C++ Program to Store Information of an Employee in a Structure

// C++ program to store data of an employee in a structure variable
#include <iostream>
using namespace std;
 
struct Employee {
    char name[50];
    int salary;
    int employeeCode;
    char dept[5];
};
 
int main() {
    Employee e;
     
    cout << "Enter name of employee : ";
    cin.getline(e.name, 50);
    cout << "Enter department : ";
    cin.getline(e.dept, 5);
    cout << "Enter salary of employee : ";
    cin >> e.salary;
    cout << "Enter employee code : ";
    cin >> e.employeeCode;
     
    // Printing employee details 
    cout << "\n*** Employee Details ***" << endl;
    cout << "Name : " << e.name << endl << "Salary : " << e.salary << endl;
    cout << "Employee Code : " << e.employeeCode << endl << "Department : " << e.dept;
    return 0;
}

Output

Enter name of employee : Jason Donald
Enter department : CSE
Enter salary of employee : 53463
Enter employee code : 1234

*** Employee Details ***
Name : Jason Donald
Salary : 53463
Employee Code : 1234
Department : CSE

In above program, we first declare a variable of type Employee as

Employee e;

Then we ask user to enter details of employee i.e Name, department, salary and department and store it in corresponding fields of structure variable e.Finally we print the information of variable e on screen using court.

Points to remember about Structures in C++

  • Structure in C++ programming language is a user defined data type that groups logically related information of different data types into a single unit.
  • Keyword struct is used to declare a structure.
  • We can declare any number of member variables inside a structure.
  • We can access the member of structure either using dot operator(.) or arrow operator(->) in case of structure pointer.

Print Hello World, Multiply two Numbers, Add Two Numbers, etc. are some of the basic-level Programs in C++. Want to practice advanced C++ Programs? Go with the available links & gain more coding knowledge.

C++ Program to Add Two Distances in Inch and Feet Using Structures

In the previous article, we have discussed C++ Program to Add Two Complex Numbers Using Structure. In this article, we will see C++ Program to Add Two Distances in Inch and Feet Using Structures.

C++ Program to Add Two Distances in Inch and Feet Using Structures

  • Write a C++ program to add two distances in inch and feet using structure variable.

In this C++ program, we will add two distances in inch and feet system using a user defined structure. We created a custom structure name “Distance” which contains two member variables feet and inch.

struct Distance{
    int feet;
    float inch;
};

We will use variable of structure Distance, to store the distance in inch and feet. Here is the feet to inch conversion equation:

1 feet = 12 inches.

C++ Program to Add Two Distances in Inch and Feet

C++ Program to Add Two Distances in Inch and Feet

// C++ program to add two distances in inch feet using structure
#include <iostream>
using namespace std;
 
// Structure storing distance in inch and feet
struct Distance{
    int feet;
    float inch;
};
 
int main() {
 Distance d1, d2, d3;
  
    cout << "Enter first distance as [feet inch]\n";
    cin >> d1.feet >> d1.inch;
 
    cout << "Enter second distance as [feet inch]\n";
    cin >> d2.feet >> d2.inch;
 
    // Adding d1 and d2 and storing the sum in d3
    d3.feet = d1.feet + d2.feet;
    d3.inch = d1.inch + d2.inch;
 
    // NOTE : 12 inch = 1 feet
 // If feet > 12 then feet = feet%12 and inch++  
    if(d3.inch > 12){
        d3.feet++;
        d3.inch = d3.inch - 12;
    } 
 
    cout << "Total distance = " << d3.feet << " feet, " << d3.inch <<" inches";
    return 0;
}

Output

Enter first distance as [feet inch]
5 7
Enter second distance as [feet inch]
3 8
Total distance = 9 feet, 3 inches

In this program, we first ask user to enter two distances in inch-feet system and store it in Distance variable d1 and d2. To find the sum of d1 and d2, we add the inch and feet member of both structure variables and store it in inch and feet members of d3 respectively. If the value of inch is greater than 12 than we convert it to feet.

Learn and explore basic C++ Practice Programs that help to enhance your skills & knowledge of the programming language. Get to know how to write simple and clear code on this page.

C++ Program to Add Two Complex Numbers Using Structure

In the previous article, we have discussed C++ Program to Calculate Difference Between Two Time Periods Using Structure. In this article, we will see C++ Program to Add Two Complex Numbers Using Structure.

C++ Program to Add Two Complex Numbers Using Structure

  • Write a C++ program to find sum of two complex numbers using structure.

In this C++ program, we will add two complex numbers using a user defined structure. A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers and i is the imaginary unit, which satisfies the equation i2 = -1.

In complex number a + bi, a is the real part and b is the imaginary part.

For Example :

5 + 7i, -3 -2i, 2 - 6i

How to Add Two Complex Numbers.

Let Sum(x + iy) is the sum of C1 and C2
Sum = C1 + C2
(x + iy) = (a + ib) + (c + id)
(x + iy) = (a + c) + i(b + d)
x = (a + c) and,
y = (b + d)
We will create a custom structure name “complex” which contains two member variables realPart and imaginaryPart.

struct Complex {
   int realPart;
   int imaginaryPart;
};

We will use variables of structure Complex, to store complex numbers.

C++ Program to Find Sum of Two Complex Numbers Using Structure

C++ Program to Find Sum of Two Complex Numbers Using Structure

// C++ program to add two complex numbers using structure and function
#include <iostream>
using namespace std;
  
/* Structure to store complex number in the form of x + yi, 
 * realPart = x and imaginaryPart = y;
 */
struct Complex {
   int realPart;
   int imaginaryPart;
};
   
int main() {
   Complex c1, c2, sum;
   
   cout << "Enter value of A and B  where A + iB is first complex number\n";
   cin >> c1.realPart >> c1.imaginaryPart;
     
   cout << "Enter value of A and B  where A + iB is second complex number\n";
   cin >> c2.realPart >> c2.imaginaryPart;
     
   /* (A + Bi) + (C + Di) = (A+C) + (B+D)i */
   sum.realPart = c1.realPart + c2.realPart;
   sum.imaginaryPart = c1.imaginaryPart + c2.imaginaryPart;
      
   if(sum.imaginaryPart >= 0 )
      cout << sum.realPart << " + " << sum.imaginaryPart<<"i";
   else
      cout << sum.realPart << " - " << sum.imaginaryPart<<"i";
     
   return 0;
}

Output

Enter value of A and B  where A + iB is first complex number
2 5
Enter value of A and B  where A + iB is second complex number
7 4
9 + 9i

In this program, we take two complex numbers as input from user in the form of A + iB and store in structure variable c1 and c2. We will add real parts of input complex numbers to get the real part of sum complex and add imaginary part of input complex numbers to get imaginary part of sum complex number.

Explore various CPP Codes lists that are used in C++ programming to write a sample program. These codes play an important role while learning the programs.