Programming Examples - Function | Learn to Program with C++: Beginner to Expert - Back-End Programming PDF Download

Example 1: C++ Program to Display Prime Numbers Between Two Intervals Using Functions
Example to print all prime numbers between two numbers (entered by the user) by making a user-defined function.

Program: Prime Numbers Between two Intervals

#include <iostream>
using namespace std;
int checkPrimeNumber(int);
int main()
{
    int n1, n2;
    bool flag;
    cout << "Enter two positive integers: ";
    cin >> n1 >> n2;
    cout << "Prime numbers between " << n1 << " and " << n2 << " are: ";
    for(int i = n1+1; i < n2; ++i)
    {
        // If i is a prime number, flag will be equal to 1
        flag = checkPrimeNumber(i);
        if(flag)
        cout << i << " ";
    }
    return 0;
}

// user-defined function to check prime number
int checkPrimeNumber(int n)
{
    bool flag = true;
    for(int j = 2; j <= n/2; ++j)
    {
        if (n%j == 0)
        {
            flag = false;
            break;
        }
    }
    return flag;
}

Output
Enter two positive integers: 12
55
Prime numbers between 12 and 55 are: 13 17 19 23 29 31 37 41 43 47 53

To print all prime numbers between two integers, checkPrimeNumber() function is created. This function checks whether a number is prime or not.
All integers between n1 and n2 are passed to this function.
If a number passed to checkPrimeNumber() is a prime number, this function returns true, if not the function returns false.
If the user enters larger number first, this program will not work as intended. To solve this issue, you need to swap numbers first.

Example 2: C++ Program to Check Prime Number By Creating a Function
You will learn to check whether a number entered by the user is prime or not by passing it to a user-defined function.

Program: Check Prime Number

#include <iostream>
using namespace std;
int checkPrimeNumber(int);
int main()
{
  int n;
  cout << "Enter a positive  integer: ";
  cin >> n;  
  if(checkPrimeNumber(n) == 0)
    cout << n << " is a prime number.";
  else
    cout << n << " is not a prime number.";
  return 0;
}
int checkPrimeNumber(int n)
{
  bool flag = false;
  for(int i = 2; i <= n/2; ++i)
  {
      if(n%i == 0)
      {
          flag = true;
          break;
      }
  }
  return flag;
}
Output
Enter a positive  integer: 23
23 is a prime number.

In this example, the number entered by the user is passed to the checkPrimeNumber() function.
This function returns true if the number passed to the function is a prime number, and returns false if the number passed is not a prime number.
Finally, the appropriate message is printed from the main() function

Example 3: C++ Program to Check Whether a Number can be Express as Sum of Two Prime Numbers
Example to check if an integer (entered by the user) can be expressed as the sum of two prime numbers of all possible combinations with the use of functions.
This program takes a positive integer from user and checks whether that number can be expressed as the sum of two prime numbers.
If the number can be expressed as sum of two prime numbers, the output shows the combination of the prime numbers.

Program: Check Whether a Number can be Expressed as a Sum of Two Prime Numbers

#include <iostream>
using namespace std;
bool checkPrime(int n);
int main()
{
    int n, i;
    bool flag = false;
    cout << "Enter a positive  integer: ";
    cin >> n;
    for(i = 2; i <= n/2; ++i)
    {
        if (checkPrime(i))
        {
            if (checkPrime(n - i))
            {
                cout << n << " = " << i << " + " << n-i << endl;
                flag = true;
            }
        }
    }
    if (!flag)
      cout << n << " can't be expressed as sum of two prime numbers.";
    return 0;
}

// Check prime number
bool checkPrime(int n)
{
    int i;
    bool isPrime = true;
    for(i = 2; i <= n/2; ++i)
    {
        if(n % i == 0)
        {
            isPrime = false;
            break;
        }
    }
    return isPrime;
}
Output
Enter a positive integer: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17


Example 4: C++ program to Find Sum of Natural Numbers using Recursion
Program to find the sum of natural numbers by using a recursive function.
The positive numbers 1, 2, 3... are known as natural numbers. The program below takes a positive integer from the user and calculates the sum up to the given number.
You can find the sum of natural numbers using loops as well. However, you will learn to solve this problem using recursion here
Program: Calculate Sum of Natural numbers using Recursion

#include<iostream>
using namespace std;
int add(int n);
int main()
{
    int n;
    cout << "Enter a positive integer: ";
    cin >> n;
    cout << "Sum =  " << add(n);
    return 0;
}
int add(int n)
{
    if(n != 0)
        return n + add(n - 1);
    return 0;
}
Output
Enter an positive integer: 10
Sum = 55

In this program, the number entered by the user is passed to the add() function.
Suppose, 10 is entered by the user. Now, 10 is passed to the add() function. This function adds 10 to the addition result of 9 (10 - 1 = 9).
Next time, 9 is added to the addition result of 8 (9 - 1 = 8). This goes on until the number reaches 0, when the function returns 0.
Now, every function is returned to calculate the end result: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.


Example 5: C++ program to Calculate Factorial of a Number Using Recursion
Program to find factorial of a non-negative integer (entered by the user) using recursion.
This program takes a positive integer from user and calculates the factorial of that number. Suppose, user enters 6 then,
Factorial will be equal to 1*2*3*4*5*6 = 720
You'll learn to find the factorial of a number using a recursive function in this example.

Program: Calculate Factorial Using Recursion

#include<iostream>
using namespace std;
int factorial(int n);
int main()
{
    int n;
    cout << "Enter a positive integer: ";
    cin >> n;
    cout << "Factorial of " << n << " = " << factorial(n);
    return 0;
}
int factorial(int n)
{
    if(n > 1)
        return n * factorial(n - 1);
    else
        return 1;
}
Output
Enter an positive integer: 6
Factorial of 6 = 720

In the above program, suppose the user inputs a number 6. The number is passed to the factorial() function.

In this function, 6 is multiplied to the factorial of (6 - 1 = 5). For this, the number 5 is passed again to the factorial() function.
Likewise in the next iteration, 5 is multiplied to the factorial of (5 - 1 = 4). And, 4 is passed to the factorial() function.
This continues until the value reaches 1 and the function returns 1.
Now, each function returns the value back to compute 1 * 2 * 3 * 4 * 5 * 6 = 720, which is returned to the main() function

Example 6: C++ Program to Find G.C.D Using Recursion
Example to find the GCD of two positive integers (entered by the user) using recursion in C programming.
This program takes two positive integers from user and calculates GCD using recursion.

Program: Calculate H.C.F using recursion
#include <iostream>
using namespace std;
int hcf(int n1, int n2);
int main()
{
   int n1, n2;
   cout << "Enter two positive integers: ";
   cin >> n1 >> n2;
   cout << "H.C.F of " << n1 << " & " <<  n2 << " is: " << hcf(n1, n2);
   return 0;
}
int hcf(int n1, int n2)
{
    if (n2 != 0)
       return hcf(n2, n1 % n2);
    else
       return n1;
}

Output
Enter two positive integers: 366 60
H.C.F of 366 and 60 is: 6


Example 7: C++ Program to Convert Binary Number to Decimal and vice-versa
In this example, you will learn to convert binary number to decimal, and decimal number to binary manually by creating user-defined functions.

Program 1: C++ Program to convert binary number to decimal

#include <iostream>
#include <cmath>
using namespace std;
int convertBinaryToDecimal(long long);
int main()
{
    long long n;
    cout << "Enter a binary number: ";
    cin >> n;
    cout << n << " in binary = " << convertBinaryToDecimal(n) << "in decimal";
    return 0;
}
int convertBinaryToDecimal(long long n)
{
    int decimalNumber = 0, i = 0, remainder;
    while (n!=0)
    {
        remainder = n;
        n /= 10;
        decimalNumber += remainder*pow(2,i);
        ++i;
    }
    return decimalNumber;
}

Output
Enter a binary number: 1111
1111 in binary = 15

Program 2: C++ Program to convert decimal number to binary

#include <iostream>

#include <cmath>

using namespace std;
long long convertDecimalToBinary(int);
int main()
{
    int n, binaryNumber;
    cout << "Enter a decimal number: ";
    cin >> n;
    binaryNumber = convertDecimalToBinary(n);
    cout << n << " in decimal = " << binaryNumber << " in binary" << endl ;
    return 0;
}
long long convertDecimalToBinary(int n)
{
    long long binaryNumber = 0;
    int remainder, i = 1, step = 1;
    while (n!=0)
    {
        remainder = n%2;
        cout << "Step " << step++ << ": " << n << "/2, Remainder = " << remainder << ",
Quotient = " << n/2 << endl;
        n /= 2;
        binaryNumber += remainder*i;
        i *= 10;
    }
    return binaryNumber;
}

Output
Enter a decimal number: 19
Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary


Example 8: C++ Program to Convert Octal Number to Decimal and vice-versa
In this example, you will learn to convert octal number to decimal and decimal number to octal manually by creating a user-defined function

Program 1: Convert Octal Number to Decimal

#include <iostream>
#include <cmath>
using namespace std;
int octalToDecimal(int octalNumber);
int main()
{
   int octalNumber;
   cout << "Enter an octal number: ";
   cin >> octalNumber;
   cout << octalNumber << " in octal = " << octalToDecimal(octalNumber) << " in decimal";
   return 0;
}
// Function to convert octal number to decimal
int octalToDecimal(int octalNumber)
{
    int decimalNumber = 0, i = 0, rem;
    while (octalNumber != 0)
    {
        rem = octalNumber % 10;
        octalNumber /= 10;
        decimalNumber += rem * pow(8, i);
        ++i;
    }
    return decimalNumber;
}

Output
Enter an octal number: 2341
2341 in octal = 1249 in decimal

In the program, the octal number is stored in the variable octalNumber and passed to function octalToDecimal().
This function converts the octal number passed by user to its equivalent decimal number and returns it to main() function.

Program 2: Convert Decimal Number to Octal

#include <iostream>
#include <cmath>
using namespace std;
int decimalToOctal(int decimalNumber);
int main()
{
   int decimalNumber;
   cout << "Enter a decimal number: ";
   cin >> decimalNumber;
   cout << decimalNumber << " in decimal = " << decimalToOctal(decimalNumber) << " in octal";
   return 0;
}
// Function to convert decimal number to octal
int decimalToOctal(int decimalNumber)
{
    int rem, i = 1, octalNumber = 0;
    while (decimalNumber != 0)
    {
        rem = decimalNumber % 8;
        decimalNumber /= 8;
        octalNumber += rem * i;
        i *= 10;
    }
    return octalNumber;
}

Output
Enter an decimal number: 78
78 in decimal = 116 in octal

In the program, the decimal number is stored in the variable decimalNumber and passed to function decimalToOctal().
This function converts the decimal number passed by user to its equivalent octal number and returns it to main() function.

Example 9: C++ Program to Convert Binary Number to Octal and vice-versa
In this example, you will learn to convert binary number to octal, and octal number to binary manually by creating a user-defined function.

Program 1: Program to Convert Binary to Octal
In this program, we will first convert the binary number to decimal. Then, the decimal number is converted to octal.

#include <iostream>
#include <cmath>
using namespace std;
int convertBinarytoOctal(long long);
int main()
{
    long long binaryNumber;
    cout << "Enter a binary number: ";
    cin >> binaryNumber;
    cout << binaryNumber << " in binary = " << convertBinarytoOctal(binaryNumber) << " in octal ";
    return 0;
}
int convertBinarytoOctal(long long binaryNumber)
{
    int octalNumber = 0, decimalNumber = 0, i = 0;
    while(binaryNumber != 0)
    {
        decimalNumber += (binaryNumber) * pow(2,i);
        ++i;
        binaryNumber/=10;
    }
    i = 1;
    while (decimalNumber != 0)
    {
        octalNumber += (decimalNumber % 8) * i;
        decimalNumber /= 8;
        i *= 10;
    }
    return octalNumber;
}

Output
Enter a binary number: 10001
10001 in binary = 21 in octal

The binary number entered by the user is passed to convertBinaryToOctal() function. And, this function converts the number to octal and returns to the main() function

Program 2: Program to Convert Octal to Binary
In this program, the octal number is converted to decimal at first. Then, the decimal number is converted to binary number.

#include <iostream>
#include <cmath>
using namespace std;
long long convertOctalToBinary(int);
int main()
{
    int octalNumber;
    cout << "Enter an octal number: ";
    cin >> octalNumber;
    cout << octalNumber << " in octal = " << convertOctalToBinary(octalNumber) << "in binary";
    return 0;
}
long long convertOctalToBinary(int octalNumber)
{
    int decimalNumber = 0, i = 0;
    long long binaryNumber = 0;
    while(octalNumber != 0)
    {
        decimalNumber += (octalNumber) * pow(8,i);
        ++i;
        octalNumber/=10;
    }
    i = 1;
    while (decimalNumber != 0)
    {
        binaryNumber += (decimalNumber % 2) * i;
        decimalNumber /= 2;
        i *= 10;
    }
    return binaryNumber;
}

Output
Enter an octal number: 54
54 in octal = 101100

The octal number entered by the user is passed to convertOctalToBinary() function. And, this function converts the number to binary and returns the main() function

Example 10: C++ program to Reverse a Sentence Using Recursion
This program takes a sentence from user and reverses that sentence using recursion. This program does not use string to reverse the sentence or store the sentence.

Program: Reverse a sentence using recursion.

#include <iostream>
using namespace std;
void reverse(const string& a);
int main()
{
    string str;
    cout << " Please enter a string " << endl;
    getline(cin, str);
    reverse(str);
    return 0;    
}
void reverse(const string& str)
{
    size_t numOfChars = str.size();
    if(numOfChars == 1)
       cout << str << endl;
    else
    {
       cout << str[numOfChars - 1];
       reverse(str.substr(0, numOfChars - 1));
    }
}

Output
Enter a sentence: margorp emosewa
awesome program

In this program, the user is asked to enter a string which is stored in the string object str.
Then, the reverse() function is called which is a recursive function. In the first function call, reverse() prints the last character of the string (numOfChars - 1), -1 because array starts with 0.
Then, substr() gives the string upto the 2nd last character, which is passed again to the reverse() function.
In the next reverse() call, the 2nd last character is printed because the string contains one less character from the last. After this, one character from the last is cut-off from the string again and passed to the reverse() function.
This goes until the length of the string equals 1, when the final character (or the first character) is printed and the loop ends.

Example 11: C++ Program to Calculate Power Using Recursion
This program calculates the power of a number using recursion where base and exponent is entered by the user
Program: Program to Computer Power Using Recursion

#include <iostream>
using namespace std;
int calculatePower(int, int);
int main()
{
    int base, powerRaised, result;
    cout << "Enter base number: ";
    cin >> base;
    cout << "Enter power number(positive integer): ";
    cin >> powerRaised;
    result = calculatePower(base, powerRaised);
    cout << base << "^" << powerRaised << " = " << result;
    return 0;
}
int calculatePower(int base, int powerRaised)
{
    if (powerRaised != 0)
        return (base*calculatePower(base, powerRaised-1));
    else
        return 1;
}

Output
Enter base number: 3
Enter power number(positive integer): 4
3^4 = 81

This technique can only calculate power if the exponent is a positive integer.

The document Programming Examples - Function | Learn to Program with C++: Beginner to Expert - Back-End Programming is a part of the Back-End Programming Course Learn to Program with C++: Beginner to Expert.
All you need of Back-End Programming at this link: Back-End Programming
73 videos|7 docs|23 tests
73 videos|7 docs|23 tests
Download as PDF
Explore Courses for Back-End Programming exam
Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Viva Questions

,

study material

,

practice quizzes

,

Free

,

Previous Year Questions with Solutions

,

past year papers

,

Exam

,

MCQs

,

shortcuts and tricks

,

Programming Examples - Function | Learn to Program with C++: Beginner to Expert - Back-End Programming

,

Important questions

,

video lectures

,

Programming Examples - Function | Learn to Program with C++: Beginner to Expert - Back-End Programming

,

ppt

,

mock tests for examination

,

pdf

,

Programming Examples - Function | Learn to Program with C++: Beginner to Expert - Back-End Programming

,

Summary

,

Sample Paper

,

Extra Questions

,

Semester Notes

,

Objective type Questions

;