Skip to main content

Control Flow : Practice

Loops 4

Hello 🙌 Today we will practice some more questions on loops. This will be our last exercise. After this, we are ready to solve most of the standard problems on loops and also approach new problems. As we have already done many problems in previous articles, so, I will highly recommend solving these questions without looking at the solution. At least, give them a fair try. ✌️ 😄

Now, Let's start with the questions with our weapon. (A pen and paper)

Problem 1: Check Perfect Number

Write a C++ program to input a number and check whether the number is a Perfect number or not. 

Input

Input any number: 6

Output

6 is 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. 😄

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.

Give it a shot !! ✌️

Intuition

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 try !!

 Try it out yourself here!

Explanation/Steps

  1. Input a number from the user. Store it in some variable say num.
  2. Initialize another variable to store the sum of proper positive divisors, say sum = 0.
  3. Run a loop from 1 to num/2, increment 1 in each iteration. The loop structure should look like for(i=1; i<=num/2; i++).Why iterating from 1 to num/2, why not till num? Because a number does not have any proper positive divisor greater than num/2.
  4. Inside the loop if the current number i.e. i is a proper positive divisor of num, then add it to the sum.
  5. Finally, check if the sum of proper positive divisors equals to the original number. Then, the given number is a Perfect number otherwise not.
Solution
#include <iostream>
using namespace std;
int main()
{
    int i, num, sum = 0;

    /* Input a number from user */
    cout << "Enter any number to check perfect number: ";
    cin >> num;

    /* 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)
    {
        cout << "It is a PERFECT NUMBER";
    }
    else
    {
        cout << "It is NOT a PERFECT NUMBER";
    }

    return 0;
}

Problem 2: Print Perfect Numbers

Write a C++ program to find all Perfect numbers between 1 to n where n is the input given by the user.

Input

Enter the number n: 100

Output

Perfect numbers between 1 to 100: 6, 28

Approach

If you have gone through the previous question i.e. problem 1, this question would be easy to solve as we already know the concept. Give it an honest try without looking at the solution. ✌️😄

Intuition

We have to print perfect numbers between 1 and n. So, we can simply run a loop from 1 to n and print those numbers which are perfect. We already have seen how to check whether a number is perfect or not in Problem 1. Sounds easy Right?

Give it a try, please !! 🙌

 Try it out yourself here!

Explanation/Steps

  1. Input n from the user to find Perfect numbers. Store it in a variable say n.
  2. Run a loop from 1 to n, increment 1 in each iteration. The loop structure should look like for(i = 1; i <= n; i++).
  3. For each iteration inside loop print the value of i if it is a Perfect number.
Solution
#include <iostream>
using namespace std;

int main()
{
    int i, j, n, sum;

    /* Input a number from user to print perfect number */
    cout << "Enter any number to print perfect number from 1 to n: ";
    cin >> n;

    cout << "All Perfect numbers between 1 to n are :\n" << endl;
    
    /* Iterate from 1 to n */
    for(i = 1; i <= n; i++)
    {
        sum = 0;

        /* Check whether the current number i is Perfect number or not */
        for(j = 1; j < i; j++)
        {
            if(i % j == 0)
            {
                sum += j;
            }
        }
 
        /* If the current number i is Perfect number */
        if(sum == i)
        {
            cout << i << " ";
        }
    }

    return 0;
}

Problem 3: Check Strong Numbers

Write a C++ program to input a number from the user and check whether the given number is a strong number or not.

Input

Enter the number: 145

Output

145 is STRONG NUMBER

Approach

To solve this question, we will first see what is a strong number. When we see this term for the first time we don't know what it means. At least I did not know.

What is a Strong Number?

A strong number is a special number whose sum of factorial of digits is equal to the original number.
For example: 145 is a strong number. Since, 1! + 4! + 5! = 145

Intuition

After solving many questions, now we know how to get hold of each digit of a number and also, how to calculate the factorial of the number. We can use the concept to check whether a number is strong or not.

I am thinking that I would take each digit of the number calculate its factorial and store it in a variable sum. As I do this for each digit of the number, I will keep on updating the sum. At last, I will check if the number is equal to the sum. If they are equal, we can say it is a strong number. Are we thinking the same??

Give it a try !! We can do this ✌️

 Try it out yourself here!

Explanation/Steps

  1. Input a number from the user to check for a strong number. Store this in a variable say num. Copy it to a temporary variable for calculation purposes, say originalNum = num.
  2. Initialize another variable to store the sum of the factorial of digits, say sum = 0.
  3. Find the last digit of the given number num. Store the result in a variable say lastDigit = num % 10.
  4. Find the factorial of lastDigit. Store factorial in a variable say fact.
  5. Add factorial to sum i.e. sum = sum + fact.
  6. Remove the last digit from the num as it is not needed further.
  7. Repeat steps 3 to 6 till num > 0.
  8. After loop check condition for strong number. If sum == originalNum, then the given number is a Strong number otherwise not.
Solution
#include <iostream>
using namespace std;
int main()
{
    int i, originalNum, num, lastDigit, sum;
    int fact;

    /* Input a number from user */
    cout << "Enter any number to check Strong number: ";
    cin >> num;

    /* Copy the value of num to a temporary variable */
    originalNum = num;

    sum = 0;

    /* Find sum of factorial of digits */
    while(num > 0)
    {

        /* Get last digit of num */
        lastDigit = num % 10;

        /* Find factorial of last digit */
        fact = 1;
        for(i = 1; i <= lastDigit; i++)
        {
            fact = fact * i;
        }

        /* Add factorial to sum */
        sum = sum + fact;

        num = num / 10;
    }

    /* Check Strong number condition */
    if(sum == originalNum)
    {
         cout << "It is a STRONG NUMBER";
    }
    else
    {
         cout << "It is NOT a STRONG NUMBER";
    }

    return 0;
}

Problem 4: Print Strong Numbers

Write a C++ program to print all strong numbers between 1 to n where n is the input given by the user.

Input

Enter the number n: 1000

Output

Strong numbers between 1-1000: 
1, 2, 145

Approach

If you have gone through the previous question i.e. problem 3, this question would be fairly easy to solve as we already know the concept and solved many problems on similar lines. Give it an honest try without looking at the solution. ✌️😄

Intuition

We have to print strong numbers between 1 and n. So, we can simply run a loop from 1 to n and print those numbers which are strong. We have already seen how to check whether a number is strong or not in Problem 3. Sounds easy Right?

Give it a try, please !! 🙌

 Try it out yourself here!

Explanation/Steps

  1. Input n to print a strong number from the user. Store it in a variable say end.
  2. Run a loop from 1 to end, increment 1 in each iteration. The structure of the loop should be similar to for(i=1; i<=end; i++).
  3. For each iteration inside loop check i for strong number. Print the value of i if it is a strong number.
Solution
#include <iostream>
using namespace std;

int main()
{
    int i, j, cur, lastDigit, end;
    int fact, sum;

    /* Input a number from user */
    cout << "Enter any number to print Strong number from 1 to that number: ";
    cin >> end;

    cout << "All Strong numbers between 1 to n are:\n";
    
    /* Iterate from 1 to end */
    for(i = 1; i <= end; i++)
    {
        /* Number to check for strong number */
        cur = i;

        sum = 0;

        /* Find the sum of the factorial of digits */ 
        while(cur > 0)
        {
            fact = 1;
            lastDigit = cur % 10;

            /* Find factorial of last digit of current num. */
            for( j = 1; j <= lastDigit; j++)
            {
                fact = fact * j;
            }

            sum += fact; 

            cur /= 10;
        }
        
        /* Print 'i' if it is strong number */  
        if(sum == i)
        {
            cout << i << " ";
        }
    }

    return 0;
}

This was our last exercise for practicing loops. Did you enjoy doing it?? I hope it is a yes 😀 I am confident that now you are comfortable with the loop problems.

"Remember Practice leads to Perfection".

Happy Learning !! 😀 See you in the next article with more interesting concepts.