Skip to main content

Functions : Practice

Functions 2

HelloπŸ™Œ, Today we will be doing more questions on function. Have you solved previous questions in the Functions 1 article?? If yes, then I think now we have a fair enough idea about how to approach problems using functions.

Suggestion: I will highly recommend solving these questions without looking at the solution. At least, give them a fair try. After giving your best shot, you can definitely go through the solution. ✌️ πŸ˜„

Now, Let's start with the questions.

Problem 1

Write a C++ program to input any two numbers(say A and B) from the user. Take 4 sets of input and for every pair of input values print the following output.

A^2+2βˆ—Aβˆ—B+B^2

Input

Enter Input Values : 3 5
Enter Input Values : 2 7
Enter Input Values : 4 1
Enter Input Values : 5 1

Output

64
81
25
36

Approach 1

Let's see how a naive coder will approach this!!

Intuition

We will write the whole code inside the main( ) function and do a lot of repetitive tasks.

Now, Are we ready to write our code? πŸ™Œ

Try it out yourself here!

Solution
#include <iostream>
using namespace std;

int main() {

        int A, B;
        
        cin >> A >> B;
        int C = A * A + 2 * A * B + B * B;
        cout << C << endl;

        cin >> A >> B;
        C = A * A + 2 * A * B + B * B;
        cout << C << endl;
        

        cin >> A >> B;
        C = A * A + 2 * A * B + B * B;
        cout << C << endl;
        
        cin >> A >> B;
        C = A * A + 2 * A * B + B * B;
        cout << C << endl; 
}


Approach 2

Let's see how a pro coder will approach this!!

Intuition

A pro coder will write the function instead of writing the same code again and again for doing the repetitive task.

Now, Are we ready to write our code? πŸ™Œ

Try it out yourself here!

Solution
#include <iostream>
using namespace std;

int EvaluateExpression(int A, int B){
        int C = A * A + 2 * A * B + B * B;
        return C;
}

int main() {

        int A, B, C;
        for (int i = 0; i < 4; i++){
                cin >> A >> B;
                C = EvaluateExpression(A, B);
                cout << C << endl;
        }
    
}


Problem 2

Write a C++ program to check whether a number is prime using functions.

Input

Enter a number: 11

Output

It is a prime number

Approach

Concept of Checking for a Prime number

What is a Prime number?

A prime number is a number that doesn't have any factor apart from 1 and the number itself.

To check if the given number is prime or not, we simply have to check if the number has any factor other than 1 and the number itself or not. To perform the check, we can simply run a loop from 2 to number-1 (exclude 1 and num as they cannot be the prime factors of a number), and divide it by every number. If the remainder is 0 then the number we divided with is the factor of the given number and hence the number is not prime.

Do we really need to run a loop till number-1? We can check only till number/2 to find prime factors of it. This will cover all possible divisors and eliminate redundant checks for larger divisors.

Now, the question seems doable, right !! Please try it on your own.

Intuition

Now let's see how to write the function

  1. First, give a meaningful name to our prime checking function say isPrime() function will check a number for prime.
  2. Next, since our function checks a number for prime condition. Hence, it must accept a number, say isPrime(int num);.
  3. Finally, the function should return a value to the caller, so that the caller can know whether the integer passed to the function is prime or not. For this, we must return a boolean true or false depending on the prime check result.

The function declaration to check the prime number is bool isPrime(int num); .

Now, Are we ready to write our code? πŸ™Œ

Try it out yourself here!

Solution
#include <iostream>
using namespace std;

bool isPrime(int n)
{
    if (n <= 1)
        return false;
 
    // Check from 2 to n-1
    for (int i = 2 ; i <= n / 2 ; i++)
        if (n % i == 0)
            return false;
 
    return true;
}


int main(){
    
    int num;
    /* Input numbers from user */
    cout << "Enter number: ";
    cin >> num;
    
    // Call isPrime() function
    
    if(isPrime(num))
    {
        cout << "It is Prime number";
    }
    else
    {
        cout << "It is not a Prime number";
    }
    
    return 0;
}


Problem 3

Write a C++ program to check whether a number is perfect using functions.

Input

Enter a number: 11

Output

It is a perfect number

Approach

If we know what is perfect number, Can we give it a try? Always spend some time with the question to improve problem-solving skills. πŸ˜„

Concept of Checking for a Perfect number

What is a Perfect Number?

A perfect number is a positive integer that is equal to the sum of its proper positive divisors. A positive proper divisor is a positive divisor of a number, excluding itself.
For example: 6 is the first perfect number
Proper divisors of 6 are 1, 2, 3
Sum of its proper divisors = 1 + 2 + 3 = 6.
Hence 6 is a perfect number.

Do you remember the concept of calculating the factors of a number? (We have covered this in the previous article namely Loops 2) We can use the same to get the positive proper divisors of the number and then, calculate their sum. If the sum equals the number, it is perfect else not.

Hint: Can a number have any proper positive divisor ( positive divisor of a number, excluding itself) greater than num/2? No.

Now, Give it a shot !! ✌️

Now, We just have to write the function for the above concept, right !! Please try it on your own.

Intuition

Now let's see how to write the function

  1. First, give a meaningful name to our prime checking function say isPerfect() function will check a number for perfect number.
  2. Next, since our function checks a number for perfect condition. Hence, it must accept a number, say isPrime(int num);.
  3. Finally, the function should return a value to the caller, so that the caller can know whether the integer passed to the function is perfect or not. For this, we must return a boolean true or false depending on the perfect check result.

The function declaration to check the prime number is bool isPerfect(int num); .

Now, Are we ready to write our code? πŸ™Œ

Try it out yourself here!

Solution
#include <iostream>
using namespace std;

bool isPerfect(int num)
{
    int i, sum = 0;


    /* Calculate sum of all proper divisors */
    for(i = 1; i <= num / 2; i++)
    {
        /* If i is a divisor of num */
        if(num % i == 0)
        {
            sum += i;
        }
    }

    /* Check whether the sum of proper divisors is equal to num */
    if(sum == num && num > 0)
    {
        return true;
    }
    
    return false;
}


int main(){
    
    int num;
    /* Input numbers from user */
    cout << "Enter number: ";
    cin >> num;
    
    // Call isPerfect() function
    
    if(isPerfect(num))
    {
        cout << "It is a Perfect number";
    }
    else
    {
        cout << "It is not a Perfect number";
    }
    
    return 0;
}


Problem 4

Write a C++ program to check whether a number is armstrong using functions.

Input

Enter a number: 371

Output

It is a armstrong number

Approach

To solve this question, we will first see what is an Armstrong number. When we see this term for the first time we don't know what it means. At least I did not know. πŸ˜„

Concept of Checking for a Armstrong Number

What is an Armstrong Number?

An Armstrong number is a n-digit number that is equal to the sum of the nth power of its digits.

For example –
6 = 61 = 6
371 = 33 + 73 + 13 = 371

Try to break down this problem into steps.

  1. First, calculate the number of digits. Let's say it is n.
  2. Then one by one get the digits and calculate the power of the digit with the exponent as the total number of digits(which is n). After this update the sum.
  3. Finally, can we now check whether the number is Armstrong or not by equating the sum that we have calculated in the previous step with the number?

One function that you may require while solving this question is pow( ).

The pow( ) function returns the result of the first argument raised to the power of the second argument. This function is defined in the cmath header file. In C++, pow(a, b) = a ^b.

Please give it a try now. ✌️

Now, We just have to write the function for the above concept, right !! Please try it on your own.

Intuition

Now let's see how to write the function

  1. First, give a meaningful name to our Armstrong checking function say isArmstrong() function will check a number for an Armstrong number.
  2. Next, since our function checks a number for the Armstrong condition. Hence, it must accept a number, say isArmstrong(int num);.
  3. Finally, the function should return a value to the caller, so that the caller can know whether the integer passed to the function is an Armstrong or not. For this, we must return a boolean true or false depending on the Armstrong check result.

The function declaration to check the prime number is bool isArmstrong(int num); .

Now, Are we ready to write our code? πŸ™Œ

Try it out yourself here!

Solution
#include <iostream>
#include <cmath>
using namespace std;

bool isArmstrong(int num)
{
    int originalNum, lastDigit, sum;
    int digits = 0;
    sum = 0;

    /* Copy the value of num for processing */
    originalNum = num;

    /* Find total digits in num */
    if (num == 0){ 
        digits = 1;     
    }
    
    while (num != 0) { 
        num = num / 10; 
        ++digits; 
    }
    
    // Copy the value of originalNum to num
    //As num has been modified while calculating number of digits */
    num = originalNum;

    /* Calculate sum of power of digits */
    while(num > 0)
    {
        /* Extract the last digit */
        lastDigit = num % 10;

        /* Compute sum of power of last digit */
        sum = sum + pow(lastDigit, digits); //In C++, pow(a, b) = a ^ b.

        /* Remove the last digit */
        num = num / 10;
    }

    /* Check for Armstrong number */
    if(originalNum == sum)
    {
        return true;
    }

    return false;
}


int main(){
    
    int num;
    /* Input numbers from user */
    cout << "Enter number: ";
    cin >> num;
    
    // Call isArmstrong() function
    
    if(isArmstrong (num))
    {
        cout << "It is an Armstrong number";
    }
    else
    {
        cout << "It is not an Armstrong number";
    }
    
    return 0;
}


How was this exercise? Did you enjoy doing the questions?? I am assuming a positive response. (Am I very optimistic XD πŸ˜…)

I think now you must be comfortable with solving problems through functions.

"Remember Practice leads to Perfection".

Happy Learning !! πŸ˜€See you in the next article with more interesting concepts.