Program to split and product the integer in all possible ways in C++

In this tutorial, we will learn how to split the integer into 2 in all possible ways in C++ and the program prints the product of those integers as output.

Input integer is obtained and the possible ways are calculated.

The integer must be split from the left to right direction.

The total number of digits present in the number is calculated using while loop.

This program split and product the integers in all possible ways.




How to calculate the number of digits present in the number in C++

long int num;
cin>>num;
long int temp=num;
int cnt=0;
while(temp!=0){
temp/=10;
cnt++;
}

In the above code,

The variable ‘num’ holds the integer and the variable ‘temp’ also holds the integer.

The while loop is executed until the temp is equal to zero.

The variable ‘cnt’ is initialised with 0 to count the total number of digits present in the integer.

Input:

Enter the number: 2408

code to split and product the integers in all possible ways C++

#include<iostream.h>
#include<math.h>
using namespace std;
int main(){
   long int num;
   cout<<"Enter the number:"<<"\t";
   cin>>num;
   long int temp,flag,cnt=0;
   temp=num;
   flag=num;
  //code to count the number of digits in the integer//
   while(temp!=0){
        temp/=10;
        cnt++;
   }
  //Code to find the possible ways and its products//
  cout<<"From the given number the possible products obtained are :"<<"\n";
   for(int i=cnt-1;i>=1;i--){
       int power=pow(10,i);
       cout<<(num/power)*(flag%power)<<"\t";
   }
}

In the above code,

The integer is obtained and it is stored under the variable names ‘num’ ,’temp’ and ‘flag’.

The while loop is used to count the number of digits present in the number.

The for loop is initialised with the variable i and it starts from cnt-1 and ends upto 1 .

It is executed in the decrement order.

The power is calculated using the pow() method.

The pow() method can be included only when the header file #include<math.h> is included.

The num/power is used to hold certain digits from first based on the power value.

The flag%power calculates the remaining digits which are also based on power value.

Then the products are calculated accordingly.

The same way the entire loop is executed with different power values.

Thus the products are printed simultaneously within the for loop.

OUTPUT 1:

The possible products obtained from the given number are:
816 192 1920

INPUT 2:

Enter the number: 134

OUTPUT 2:

The possible products obtained from the given number are:
34 52

Thus the program splits and prints the product of the integers of the number in all possible ways.

We hope this tutorial helped you to understand how to find all the possible ways of splitting the integer and printing their products as output.

You may also learn:


Leave a Reply

Your email address will not be published. Required fields are marked *