To check whether the given number is mono-digit or not

Question:
Write a program to check the number is mono-digit or not.
Conditions:
- The programmer is allowed to add and subtract the consecutive digits (starting from left).
- And you are allowed to do only one operation on a digit.
- You cannot perform any operation on a resultant digit of the previous operation.
- Your code should also find if a given number cannot be converted to a mono digit number.
Logic:
- Get the input as a string and convert it into an integer array.
- Then check for three possibilities for a mono digit to occur.
- The first element is a mono digit.
- Addition of first and second element is a mono digit.
- Subtraction of first and second element is a mono digit.
- These possibilities calculated and stored in c[0].
- And check the conditions as we mentioned above:
- A single digit is equal to c[0].
- Addition of two consecutive digits is equal to c[0].
- Subtraction of two consecutive digits is equal to c[0].
- If any mono digit occurs means print which is stored in array c.
- And also shows the occurrence non-mono digit.
Program:
[code lang=”c”]
#include<stdio.h>
int main()
{
int i,j=0,b[20],k=0,c[20],m=1,n=0,l=0;
char a[20];
printf("enter the number:");
gets(a); //get the input as a string
i=strlen(a); //length of string
while(a[j]!=’\0’) //convert the string to integer
{
b[j]=a[j]-48; //stores converted value into integer array
j++;
}
for(k=0;k<3;k++) //check three possibilities
{
if(k==0) //checks with first element
{
c[0]=b[0];
m=1,n=0;
}
else if(k==2) //checks with addition of first and second element
{
c[0]=b[0]+b[1];
m=2,n=0;
}
else //checks with subtraction of first and second element
{
c[0]=b[0]-b[1];
m=2,n=0;
}
check: //check is the label
for(j=m;j<i;j++)
{
n++; //increments the monodigit array position
if(c[0]==b[j]) //single digit is equal to c[0]
{
c[n]=b[j]; //store the monodigit value into array
m=j+1; //increments the index by one
goto check;
}
else if(c[0]==b[j]+b[j+1]) //addition of two consecutive are equal to c[0]
{
c[n]=b[j]+b[j+1];
m=j+2;
goto check;
}
else if(c[0]==b[j]-b[j+1]) //subtraction of two consecutive are equal to c[0]
{
c[n]=b[j]-b[j+1];
m=j+2;
goto check;
}
else //breaks from loop when all conditions fails
{
l++;
break;
}
}
if(m>i-1) //prints the monodigit
{
printf("\nGiven number is monodigit:");
for(j=0;j<n+1;j++)
{
printf("%d ",c[j]);
}
}
}
if(l==3) //prints when three possibilities fails
{
printf("It is not monodigit");
}
return 0;
}
[/code]
You might also like:
Sum Of Digits Of A Number Until The Sum Is A Single Digit