Breaking down a number into digits - C - c

I'm trying to create a program that breaks down a number into its component digits.
The code I've written so far is as follows:
#include <stdio.h>
int main() {
int num;
int digits;
int count = 1;
printf("Insert a positive number: ");
do {
scanf("%d", &num);
} while (num <= 0);
printf("In digits... \n");
// Number in digits
while (num != 0) {
digits = num % 10;
printf("Digit %d --> %d \n", count, digits);
num /= 10;
count++;
}
}
The digits of the number are printed correctly, but in reverse order!
Insert a positive number: 345
In digits...
Digit 1 --> 5
Digit 2 --> 4
Digit 3 --> 3
I can't figure out how to fix this, can anyone help me?

You're printing the number mod 10, which is the last digit, then dividing the number by 10 and repeating until the number is zero. So it prints the digits from right to left.
If you want to print from left to right, you need to print the digit that has the highest power of ten first. Here's a naive way to do that, by first finding the highest power of ten the number has a digit for and then using a for loop to go from that power to one to print the digits from left to right:
void print_digits(int n) {
int mask = 1;
for(int n2 = n; n2; n2 /= 10) mask *= 10; // find the left-most power of ten
for(int i = 1; mask > 1; mask /= 10) // loop over the mask to 1
printf("Digit %d --> %d\n", i++, (n % mask) * 10 / mask);
// print the digit number and increment the digit counter
// extract and print the digit:
// `n % mask` gets rid of everything to the left
// `* 10 / mask` gets rid of everything to the right
}
You could also make a simpler solution using the standard library function sprintf (string print formatted) to put the int into a string and then print from that, like so:
void print_digits(int n) {
char num[11]; // 32-bit int up to 9 digits, possible '-', and \0 -> 11
sprintf(num, "%d", n);
for (int i = 0; num[i]; i++)
printf("Digit %d --> %c\n", i + 1, num[i]);
}
The second might also be a tiny bit more performant due to not involving division, but I'm not certain of that and such minor differences don't matter for a problem like this anyway

Your code prints them in reverse because you are starting with the right-most digit (by taking the modulo by 10) each time, then dividing by 10.
To print from left to right, you could have:
#include <stdint.h>
void print_uint32_digits(uint32_t val)
{
int started = 0; // Flag to say we have started printing digits
// Special case for when val is zero
if (val == 0u)
{
printf("0\n");
return;
}
for (uint32_t divider = 1000000000u; divider != 0u; divider /= 10u)
{
uint32_t num = val / divider;
if (num > 0u || started)
{
printf("%c", num + '0');
started = 1;
val -= (num * divider);
}
}
printf("\n");
}
Some notes - I've used uint32_t because it is unsigned and a nice length. To make it work with plain "ints" would involve handling the case of negative numbers, which is more complex. I don't know if you need to handle negative numbers. (Also, ints on your platform could be 64-bit, so the initial divider would have to be adjusted accordingly.)
The 'started' flag is used to signal when we have output at least one digit, to ensure zeros get printed correctly. Until that flag is set, leading zeros are not printed.

A very simple recursive solution looks like this:
void print_num(int num)
{
if (num < 10)
fputc('0' + num, stdout);
else {
print_num(num/10);
print_num(num%10);
}
}

Related

Write a program, which reads an Integer. Output another integer where the even digits are retained and odd digits are decremented by 1,

Here is my code:
#include <stdio.h>
#include <math.h>
int main() {
int num, i = 0, new_num = 0, u;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
u = num % 10;
if (u % 2 == 0)
u = u;
if (u % 2 == 1)
u = u - 1;
new_num = new_num + u * pow(10, i);
num = num / 10;
i++;
}
printf("The new number is: %d", new_num);
return 0;
}
Now, when I am doing this in gcc(VS Code), for 2-digit number everything is ok. But for digits more than three I am getting a error. Like Input=23145 Output=22043. But I was expecting output=22044.
Also, if I run the same code in DevC/C++, there is no error.
Can anyone help me out in this?
Your program produces the expected output on my system: 22044 for 23145, but this might depend on the implementation of the pow function.
The reason you get a different output is probably a side effect of a precision issue with the pow() function in your C library: if pow(x, y) is implemented as exp(y * log(x)), the result for integral values of x and y could be very close but inferior to the actual integral value, causing the conversion to int to produce the previous integer. Some C library authors make a special case of integral arguments to avoid this problem, but it is highly recommended to avoid floating point functions for integer arithmetics to prevent such tricky issues.
I would advise some more changes in your code:
test the return value of scanf().
remove the if (u % 2 == 0) u = u; part, it has no effect.
in any case, there should be an else clause to not use the result of the previous case when testing for odd digits.
do not use the floating point function pow(): just keep a multiplier variable and update it in the loop.
the program does not handle negative numbers.
Here is a modified version:
#include <stdio.h>
int main() {
int num, new_num = 0, pow10 = 1;
printf("Enter a number: ");
if (scanf("%d", &num) != 1)
return 1;
while (num != 0) {
int digit = num % 10;
/* decrement odd digits absolute value */
digit -= digit % 2;
new_num = new_num + digit * pow10;
pow10 = pow10 * 10;
num = num / 10;
}
printf("The new number is: %d\n", new_num);
return 0;
}
Note that digit -= digit % 2; will decrement positive odd digits and actually increment negative odd digits, which effectively always decrements the absolute value of odd digits. This way both positive values and negative values are handled correctly.
In my instance of Visual Studio Code, for an input 23145, I indeed find 22044 as an output.
I guess the divergence comes with the cast of pow(10,i). Pow function in C returns a double which is not what you really want here. I strongly advice to not use the pow function for integer arithmetic.
A solution could be :
uint16_t i = 0u;
uint16_t current_digit = 0u, decimal_digit = 1u;
uint16_t new_number = 0u;
uint16_t number = 23145u;
while(number > 0u) {
current_digit = number % 10;
if (current_digit % 2) {
current_digit = current_digit - 1;
}
new_number = new_number + current_digit * decimal_digit;
decimal_digit *= 10u;
number /= 10;
i++;
}
printf("The new number is: %d", new_number);
It seems that the problem is using the function pow that returns a double value.
If you are dealing with integers then it is better to avoid using functions that return doubles due to a possible truncation then a double is converted to an integer.
Also pay attention to that the user can enter a negative number. Your program allows to do that. In this case your program also will produce an incorrect result.
I would write the program the following way
#include <stdio.h>
int main( void )
{
while (1)
{
const int Base = 10;
int num;
printf( "Enter a number (0 - exit): " );
if (scanf( "%d", &num ) != 1 || num == 0) break;
int new_num = 0;
for (int tmp = num, multiplier = 1; tmp != 0; tmp /= Base)
{
int digit = tmp % Base;
if (digit % 2 != 0)
{
digit += ( digit < 0 ? 1 : -1 );
}
new_num = new_num + multiplier * digit;
multiplier *= Base;
}
printf( "The original number is %d and the new number is: %d\n",
num, new_num );
putchar( '\n' );
}
}
The program output is
Enter a number (0 - exit): -123456789
The original number is -123456789 and the new number is: -22446688
Enter a number (0 - exit): 123456789
The original number is 123456789 and the new number is: 22446688
Enter a number (0 - exit): 0
If even for negative digits to add -1 then you should substitute this if statement
if (digit % 2 != 0)
{
digit += ( digit < 0 ? 1 : -1 );
}
for this one
if (digit % 2 != 0)
{
digit = ( digit -1 ) % Base;
}
In this case the program output might look like
Enter a number (0 - exit): -123456789
The original number is -123456789 and the new number is: -224466880
Enter a number (0 - exit): 123456789
The original number is 123456789 and the new number is: 22446688
Enter a number (0 - exit): 0
That is in this case the new value for the negative value -123456789 will be -224466880.

How can I separate an integer into muliple digits?

I have a remainder function that finds that modulo of a number then a divider function to divide that number. My program isn't working the way I need it to. For example if I put in 2502 as my number, I should get the output of : 2 5 0 2.
I need to be able to store the value through each iteration, so for example:
number: 123
123 % 10 = 3 //last digit
Number: 123 / 10 = 12
12 % 10 = 2 //second digit
Number: 12 / 10 = 1
1 % 10 = 1 //first digit
int Rem(int num);
int Div(int num);
int main() {
int num;
printf("Enter an integer between 1 and 32767: ");
scanf("%d", &num);
Rem(num);
Div(num);
printf("%d","The digits in the number are: ");
}
int Rem(int num) {
while(num != 0){
int rem = num % 10;
return rem;
}
}
int Div(int num){
while(num != 0){
int div = num / 10;
return div;
}
}
The idea here is pretty simple, but there are some subtleties. Here's some pseudo code. You'll need to convert to C.
num = 9934; // or get it from input
do {
rem = num % 10; // this gives you the lowest digit
num = num / 10; // divide by 10 to get rid of that lowest digit
print rem;
} while (num != 0);
I use a do ... while loop so the output will be correct if the user enters 0.
If you code this up and run it, you'll notice that it prints the digits in reverse order: 4 3 9 9. So you'll need some way to reverse the digits before you output them. Three possible ways are:
Store the digits in an array, and then reverse the array before outputting.
Push each digit onto a stack. When you're done, pop each digit off the stack and output it.
Write a recursive function. That would eliminate the need for an explicit stack or array.
Also you could convert it to a string and then convert back the elements of that string, but keep '\0' in mind
You can simply use this function , it return the number of digits passing by argument
size_t ft_cnbr(int n)
{
size_t count;
count = 1;
if (n < 0)
{
count++;
n = -n;
}
while (n > 9)
{
n = n / 10;
count++;
}
return (count);
}

Displaying individual number with spacing on printf

im writing a code which will show the result is to display the individual digits and the decimal equivalent.
For e.g., if n is 6 and the number entered is 110011, the printout will be
1 1 0 0 1 1
The decimal equivalent is 51
I have already sourced and edited a code, however it shows
"110011 110011 110011 110011 110011 110011" instead of
"1 1 0 0 1 1".
#include <math.h>
void main()
{
int num, binary, decimal = 0, base = 1, remainder, n, digits;
printf("Please enter the number of digits:\n");
scanf("%d", &n);
printf("Please enter the %d digits:\n",n);
scanf("%d", &num);
binary = num;
while (n > 0)
{
remainder = num % 10;
decimal = decimal + remainder * base;
num = num / 10 ;
base = base * 2;
printf("%d ", binary);
n--;
}
printf("\nIts decimal equivalent is = %d \n", decimal);
}
The value in the variable binary becomes a copy of the value in the variable num in the following line.
binary = num;
Since it is never changed afterwards, it will always remain the same value, a copy of the value in num at the time when it was copied (see the code line above).
Your loop is executed n times (in your example six times).
Each time through the loop, the same copied value is printed in the following code line.
So the original value will be printed six times in your example.
printf("%d ", binary);
You did not actually ask a question (which is really recommended here at StackOverflow).
So I answered the question "Why is the same value printed six times?"
You probably want to now ask the next question, "How do get the desired result?"
That question is much harder to answer, because your code is quite far away from achieving that.
You would have to determine the binary digits one by one and in the right order.
You do determine the digits one by one, around the following line in your code.
remainder = num % 10;
But that is the wrong order, it gives you the digits from least signifying to most signifying. Try with an input of "100011" to see what I mean.
To be more precise I have to say that I guess that you want the digits from most to least, but maybe not, in that case it is easier: print remainder instead of binary.
If I am right and you do want most to least, then you have to make some way of reversing the digits. You could use a stack, an array, recursion or different (more complicated ) math involving to determine the number of digits first.
The reason you're getting this output is because each call for printf("%d ", binary); prints the entirety of the 'binary' variable onto the screen, and that variable contains the number as opposed to individual digits of that number.
The easiest way of accessing specific digits of a number is by first dividing it by some power of 10, then getting mod10 of that number, e.g.:
int number = 6543;
int lastDigit = number % 10;
int secondLastDigit = (number / 10) % 10;
int thirdLastDigit = (number / 100) % 10;
This works because dividing integers in C causes any fraction parts to be ommitted, thus if you divide 6543/10 (as in the example), you will not get 654.3, but 654.
You could create a function which will return a number's digit from any position like so:
int digitAt(int num, int pos)
{
// Divide num by 10^(pos - 1) to "shift" the number to the right
num /= pow(10, pos - 1);
// Return the last digit after the divisions
return num % 10;
}
The above function returns digits starting from the right (pos 1 = last digit, pos 2 = second last digit)!
To make this function more intuitive you could for example flip the number horizontally before dividing (123 becomes 321).
I went on a little tangent, back to the original topic. To achieve the functionality you want, you could write your code like this (just the while loop):
while (n > 0)
{
remainder = num % 10;
decimal = decimal + remainder * base;
num = num / 10 ;
base = base * 2;
int binaryDigit = (binary / pow(10, n - 1)) % 10;
printf("%d ", binaryDigit);
n--;
}
Now, the reason you don't have to worry about your digits being read backwards (like in the previous function example) is because conveniently, your iterator, n, is already going in reverse direction ('from n to 0' as opposed to 'from 0 to n'), so you're reading the leftmost digits before the rightmost ones.
Hope that helped.
[EDIT] As pointed out in the replies, using pow() in integer operations may lead to undesired results. My bad. There are plenty of ways to achieve an integer power of 10 though, a function like
int powerOf10(int exp)
{
int num = 1;
while (exp > 0) {
num *= 10;
exp--;
}
return num;
}
should do the job.
The problem is that you do:
printf("%d ", binary);
but binary is the same value all the time, i.e. it's never changing so you get the original value printed again and again.
If you changed it to:
printf("%d ", remainder);
things would be "a bit better" as the binary pattern would be printed but in reversed order. So that's not the solution.
So instead you can collect the values in the loop and store them in a string to be printed after the loop. Like:
int main()
{
int num, decimal = 0, base = 1, remainder, n;
printf("Please enter the number of digits:\n");
scanf("%d", &n);
int idx = 2*n-1;
char *str = malloc(2*n); // Allocate memory for the string
str[idx--] = 0; // and zero-terminate it
printf("Please enter the %d digits:\n",n);
scanf("%d", &num);
while (n > 0)
{
remainder = num % 10;
decimal = decimal + remainder * base;
num = num / 10 ;
base = base * 2;
str[idx--] = '0' + remainder; // Put the "binary" (i.e. '0' or '1') char in the string
if (idx>0) str[idx--] = ' '; // Put a space in the string
n--;
}
printf("%s", str); // Print the string
printf("\nIts decimal equivalent is = %d \n", decimal);
free(str); // Free the string
return 0;
}

Validating card credit numbers

I've been trying to create a program that can check if a credit card number is valid or not based on Hans Peter Luhn's algorithm. However, I can only get it to work for some inputs.
// Loop through every digit in the card number
for ( int i = 0; i < intlen (num); ++i )
{
nextDigit = getDigit (num, i);
// If every other number...
if ( i % 2 )
{
nextDigit *= 2;
// ...times by two and add the individual digits to the total
for ( int j = 0; j < intlen (nextDigit); ++j )
{
total += getDigit (nextDigit, j);
}
}
else
{
total += nextDigit;
}
}
When I use the AMEX card number 378282246310005 it works fine and tells the user it's valid. However, once I try the VISA card number 4012888888881881 it says it's invalid. I tried to do a sanity check and do it manually to see if my program was wrong but I deduced the same result. These card number were taken from the Paypal test credit card numbers page so I know they are valid.
So what am I doing wrong?
To clarify the details by the program, if total modulo 10 == 0 then the card number is valid.
Functions called:
// Function to return length (number of digits) of an int
int intlen (long long n)
{
int len = 1;
// While there is more than 1 digit...
while ( abs (n) > 9 )
{
// ...discard leading digits and add 1 to len
n /= 10;
++len;
}
return len;
}
// Function to return a digit in an integer at a specified index
short getDigit (long long num, int index)
{
// Calculating position of digit in integer
int pos = intlen (num) - index;
// Discard numbers after selected digit
while ( pos > 1 )
{
num /= 10;
--pos;
}
// Return right-most digit i.e. selected digit
return num % 10;
}
You'll want to change i % 2 to i % 2 == intlen (num) % 2 or similar; you should double every second digit, but starting from the right; i.e. excluding the final check digit:
From the rightmost digit, which is the check digit, moving left, double the value of every second digit; …
The reason the AMEX number you tried validated anyway is because it's an odd number of digits; the same digits get doubled regardless of whether you skip from the front or the back.
While I was looking at this to find the bug, I re-wrote the program to make it a bit simpler. As a side-effect this will be much faster.
We need to grab digits from the right anyway. We don't even need to count the digits; just keep pulling off the right-most digit until the number becomes 0. If the number starts out as 0, the checksum is trivially 0 and the code is still correct.
I grabbed all the numbers from the test page. This seems to be correct, except for one number: 76009244561 (listed as "Dankort (PBS)" in the test page). I tried this number with the Python code from the Wikipedia page, and again this number is rejected. I don't know why this number is different from the others.
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
bool check_one(long long num)
{
int checksum = 0;
int i = 1;
for (int i = 1; num; num /= 10, ++i)
{
int d = num % 10;
if (i % 2 == 0)
{
// even digit: double and add digits of doubled value
d *= 2;
if (d < 10)
{
// only one digit: we doubled a 0-4 so number is 0-8
checksum += d;
}
else
{
// two digits: we doubled a 5-9 so number is 10-18
checksum += (d % 10);
checksum += (d / 10);
}
}
else
{
// odd digit: just add
checksum += d;
}
}
return (checksum % 10) == 0;
}
static long long const valid_nums[] =
{
378282246310005,
371449635398431,
378734493671000,
5610591081018250,
30569309025904,
38520000023237,
6011111111111117,
6011000990139424,
3530111333300000,
3566002020360505,
5555555555554444,
5105105105105100,
4111111111111111,
4012888888881881,
4222222222222,
76009244561,
5019717010103742,
6331101999990016,
};
static size_t len_valid_nums = sizeof(valid_nums) / sizeof(valid_nums[0]);
static long long const non_valid_nums[] =
{
378282246310006, // add 1 to valid
371449635398432,
378734493671001,
5610591081018205, // swap last two digits
30569309025940,
38520000023273,
601111111111111, // delete last digit
601100099013942,
353011133330000,
};
static size_t len_non_valid_nums =
(sizeof(non_valid_nums) / sizeof(non_valid_nums[0]));
main()
{
bool f;
for (int i = 0; i < len_valid_nums; ++i)
{
long long num = valid_nums[i];
f = check_one(num);
if (!f)
{
printf("Number %lld considered invalid but should be valid\n", num);
}
}
for (int i = 0; i < len_non_valid_nums; ++i)
{
long long num = non_valid_nums[i];
f = check_one(num);
if (f)
{
printf("Number %lld considered valid but should be invalid\n", num);
}
}
}

Extracting individual digits from a long in C

I'm doing a homework assignment for my course in C (first programming course).
Part of the assignment is to write code so that a user inputs a number up to 9 digits long, and the program needs to determine whether this number is "increasing"/"truly increasing"/"decreasing"/"truly decreasing"/"increasing and decreasing"/"truly decreasing and truly increasing"/"not decreasing and not increasing". (7 options in total)
Since this is our first assignment we're not allowed to use anything besides what was taught in class:
do-while, for, while loops, else-if, if,
break,continue
scanf, printf ,modulo, and the basic operators
(We can't use any library besides for stdio.h)
That's it. I can't use arrays or getchar or any of that stuff. The only function I can use to receive input from the user is scanf.
So far I've already written the algorithm with a flowchart and everything, but I need to separate the user's input into it's distinct digits.
For example, if the user inputs "1234..." i want to save 1 in a, 2 in b, and so on, and then make comparisons between all the digits to determine for example whether they are all equal (increasing and decreasing) or whether a > b >c ... (decreasing) and so on.
I know how to separate each digit by using the % and / operator, but I can't figure out how to "save" these values in a variable that I can later use for the comparisons.
This is what I have so far:
printf("Enter a positive number : ");
do {
scanf ("%ld", &number);
if (number < 0) {
printf ("invalid input...enter a positive integer: ");
continue;
}
else break;
} while (1);
while (number < 0) {
a = number % 10;
number = number - a;
number = number / 10;
b = a;
}
Why not scan them as characters (string)? Then you can access them via an array offset, by subtracting the offset of 48 from the ASCII character code. You can verify that the character is a digit using isdigit from ctype.h.
EDIT
Because of the incredibly absent-minded limitations that your professor put in place:
#include <stdio.h>
int main()
{
int number;
printf("Enter a positive number: ");
do
{
scanf ("%ld", &number);
if (number < 0)
{
printf ("invalid input...enter a positive integer: ");
continue;
}
else break;
} while (1);
int a = -1;
int b = -1;
int c = -1;
int d = -1;
int e = -1;
int f = -1;
int g = -1;
int h = -1;
int i = -1;
while (number > 0)
{
if (a < 0) a = number % 10;
else if (b < 0) b = number % 10;
else if (c < 0) c = number % 10;
else if (d < 0) d = number % 10;
else if (e < 0) e = number % 10;
else if (f < 0) f = number % 10;
else if (g < 0) g = number % 10;
else if (h < 0) h = number % 10;
else if (i < 0) i = number % 10;
number /= 10;
}
/* Printing for verification. */
printf("%i", a);
printf("%i", b);
printf("%i", c);
printf("%i", d);
printf("%i", e);
printf("%i", f);
printf("%i", g);
printf("%i", h);
printf("%i", i);
return 0;
}
The valid numbers at the end will be positive, so those are the ones you validate to meet your different conditions.
Since you only need to compare consecutive digits, there is an elegant way to do this without arrays:
int decreasing = 2;
int increasing = 2;
while(number > 9)
{
int a = number % 10;
int b = (number / 10) % 10;
if(a == b)
{
decreasing = min(1, decreasing);
increasing = min(1, increasing);
}
else if(a > b)
decreasing = 0;
else if(a < b)
increasing = 0;
number /= 10;
}
Here, we walk through the number (by dividing by 10) until only one digit remains. We store info about the number up to this point in decreasing and increasing - a 2 means truly increasing/decreasing, a 1 means increasing/decreasing, and a 0 means not increasing/decreasing.
At each step, a is the ones digit and b is the tens. Then, we change increasing and decreasing based on a comparison between a and b.
At the end, it should be easy to turn the values of increasing and decreasing into the final answer you want.
Note: The function min returns the smaller of its 2 arguments. You should be able to write your own, or replace those lines with if statements or conditionals.
It's stupid to ask you to do loops without arrays --- but that's your teacher's fault, not yours.
That being said, I would do something like this:
char c;
while (1) {
scanf("%c", &c);
if (c == '\n') /* encountered newline (end of input) */
break;
if (c < '0' || c > '9')
break; /* do something to handle bad characters? */
c -= '0';
/*
* At this point you've got 0 <= c < 9. This is
* where you do your homework :)
*/
}
The trick here is that when you type numbers into a program, you send the buffer all at once, not one character at a time. That means the first scanf will block until the entire string (i.e. "123823" or whatever) arrives all at once, along with the newline character ( '\n' ). Then this loop parses that string at its leisure.
Edit For testing the increasing/decreasing-ness of the digits, you may think you need to store the entire string, but that's not true. Just define some additional variables to remember the important information, such as:
int largest_digit_ive_seen, smallest_digit_ive_seen, strict_increasing_thus_far;
etc. etc.
Let us suppose you have this number 23654
23654 % 10000 = 2 and 3654
3654 % 1000 = 3 and 654
654 % 100 = 6 and 54
54 % 10 = 5 and 4
4
This way you can get all the digits. Of course, you have to know if the number is greater than 10000, 1000, 100 or 10, in order to know the first divisor.
Play with sizeof to get the size of the integer, in order to avoid a huge if...else statement
EDIT:
Let us see
if (number>0) {
// Well, whe have the first and only digit
} else if (number>10) {
int first_digit = number/10;
int second_digit = number % 10;
} else if (number>100) {
int first_digit = number/100;
int second_digit = (number % 100)/10;
int third_digit = (number % 100) % 10;
} ...
and so on, I suppose
// u_i is the user input, My homework asked me to extract a long long, however, this should also be effective for a long.
int digits = 0;
long long d_base = 1;
int d_arr[20];
while (u_i / d_base > 0)
{
d_arr[digits] = (u_i - u_i / (d_base * 10) * (d_base * 10)) / d_base;
u_i -= d_arr[digits] * d_base;
d_base *= 10;
digits++;
}
EDIT: the extracted individual digit now lives in the int array d_arr. I'm not good at C, so I think the array declaration can be optimized.
Here's a working example in plain C :
#include <stdio.h>
unsigned long alePow (unsigned long int x, unsigned long int y);
int main( int argc, const char* argv[] )
{
int enter_num, temp_num, sum = 0;
int divisor, digit, count = 0;
printf("Please enter number\n");
scanf("%d", &enter_num);
temp_num = enter_num;
// Counting the number of digits in the entered integer
while (temp_num != 0)
{
temp_num = temp_num/10;
count++;
}
temp_num = enter_num;
// Extracting the digits
printf("Individual digits in the entered number are ");
do
{
divisor = (int)(alePow(10.0, --count));
digit = temp_num / divisor;
temp_num = temp_num % divisor;
printf(" %d",digit);
sum = sum + digit;
}
while(count != 0);
printf("\nSum of the digits is = %d\n",sum);
return 0;
}
unsigned long alePow(unsigned long int x, unsigned long int y) {
if (x==0) { return 0; }
if (y==0||x==1) { return 1; }
if (y==1) { return x; }
return alePow(x*x, y/2) * ((y%2==0) ? 1 : x);
}
I would suggest loop-unrolling.
int a=-1, b=-1, c=-1, d=-1, e=1, f=-1, g=-1, h=-1, i=-1; // for holding 9 digits
int count = 0; //for number of digits in the given number
if(number>0) {
i=number%10;
number/=10;
count++;
}
if(number>0) {
h=number%10;
number/=10;
count++;
}
if(number>0) {
g=number%10;
number/=10;
count++;
}
....
....
/* All the way down to the storing variable a */
Now, you know the number of digits (variable count) and they are stored in which of the variables. Now you have all digits and you can check their "decreasing", "increasing" etc with lots of if's !
I can't really think of a better soltion given all your conditions.

Resources