Find a two digit number with recursion - c

I'm trying to code something in C by using recursion.
The user writes two positive numbers of same length and the program gives him a new number, which is composed like this :
new number unity digit = the smallest digit in the second positive number that the user wrote.
new number ten digit = the biggest digit in the first positive number that the user wrote.
Very simple in fact, here is an example :
5642 and 2371
will give us : 61.
I tried something like this :
#include <stdio.h>
int calcPair(int a, int b){
int number = calcPair(a/10, b/10);
int digit1 = (number/10);
int digit2 = number%10;
if(digit1 < a%10){
digit1 = a%10;
}
if(digit2 > b%10){
digit2 = b%10;
}
return(number);
}
int main()
{
int a, b, number=0;
printf("Please enter two positive number of same length:\n");
scanf("%d", &a);
scanf("%d", &b);
calcPair(a, b);
printf("The two-digit number composed from %d, %d is: %d", a, b, number);
return 0;
}
BUT the program doesn't run at all.. and closes.
Maybe someone can correct me ? Or helping me finding the mistake.
Thanks by advance.

Your recursion can never end. Consider the following line in calcPair:
int number = calcPair(a/10, b/10);
This statement will always be executed unless you make it conditional, such as:
int number;
if((a != 0) || (b != 0))
number = calcPair(a/10, b/10);
Eventually, because you're dividing both numbers by 10, this condition will prove FALSE.

Something like this:
int calcPair(int a, int b){
int number;
if (a < 10 && b < 10) {
number = a*10 + b;
} else {
int digita = a%10;
int digitb = b%10;
number = calcPair(a/10, b/10);
if(digita > number/10){
number = digita*10 + number%10;
}
if(digitb < number%10){
number = (number/10)*10 + digitb;
}
}
return number;
}
Also, a small fix to the main:
int main()
{
int a, b, number=0;
printf("Please enter two positive number of same length:\n");
scanf("%d", &a);
scanf("%d", &b);
number = calcPair(a, b);
printf("The two-digit number composed from %d, %d is: %d", a, b, number);
return 0;
}

I think you can refactor your code to be more expressive of your requirement, with a few helper functions.
int greater(int a, int b)
{
return (a>b);
}
int less(int a, int b)
{
return (a<b);
}
int pickDigit(int n, int (*func)(int, int))
{
int ret = n%10;
n /= 10;
while ( n > 0 )
{
if ( fun(n%10, ret) )
{
ret = n%10;
}
n /= 10;
}
return ret;
}
int getBiggestDigit(int n)
{
return pickDigit(n, greater);
}
int gteSmallestDigit(int n)
{
return pickDigit(n, less);
}
int numDigits(int n)
{
int ret = 0;
while (n > 0 )
{
++ret;
n /= 10;
}
return ret;
}
int calcPair(int a, int b)
{
if ( numDigits(a) != numDigits(b) )
{
// Deal with error.
}
return betBiggestDigit(a)*10+getSmallestDigit(b);
}

Whether or not you are allowed to (you did not specify in OP),
here is a recursive search method using strings :
Strings are just an array of char. because you are interested in distinguishing the individual digits within a larger integer, the char data type will be a sufficient size container to facilitate the comparison.
Using arrays of char (strings) within a recursive function with exit criteria of strlen() > 0 will allow you to walk through each integer, and select the appropriate value (min or max).
This approach uses two recursive functions: getMinDigit() and getMaxDigit(), both returning a char representing the maximum value digit, or minimum value digit of their respective original multi-digit integer. These results are then concatenated, and converted back into a two digit integer.
Here is the example code that given:
5642 and 2371
will give us : 61.
char getMinDigit(char *digit)
{
static char val='9';//largest single digit base 10
int len=0;
if(strlen(digit) > 0)
{
len = strlen(digit);
if(digit[len-1] < val) //test for smallest char in string
{
val = digit[len-1];
digit[len-1] = 0;
getMinDigit(digit);
}
else
{
digit[len-1] = 0;
getMinDigit(digit);
}
}
return val;
}
char getMaxDigit(char *digit)
{
static char val='0'; //smallest single digit base 10
int len=0;
if(strlen(digit) > 0)
{
len = strlen(digit);
if(digit[len-1] > val) //search for largest char in string
{
val = digit[len-1];
digit[len-1] = 0;
getMaxDigit(digit);
}
else
{
digit[len-1] = 0;
getMaxDigit(digit);
}
}
return val;
}
int calcPair(int a, int b)
{
char big[10]={""}, small[10]={""};
char Big, Small;
char result[3]={""};
sprintf(big, "%d", a);
sprintf(small, "%d", b);
Big = getMaxDigit(big); //recursive function
Small = getMinDigit(small); //recursive function
sprintf(result, "%c%c", Big, Small);
return atoi(result);
}
int main(void)
{
int result = calcPair(5642, 2371);
printf("%d", result);
return 0;
//for illustration, hard coded to OP values
//int a, b, number=0;
//printf("Please enter two positive number of same length:\n");
//scanf("%d", &a);
//scanf("%d", &b);
//calcPair(a, b);
//printf("The two-digit number composed from %d, %d is: %d", a, b, number);
//return 0;
}

Related

Why this function gives me first sums correct and then prints bad sums

Write a program that prints the sum of digits for the entered interval limits. To calculate the sum of
digits form the corresponding function.
#include <stdio.h>
void suma(int a ,int b ){
int s= 0,i;
for(i=a;i<=b;i++){
while(i != 0 ){
int br = i % 10;
s+=br ;
i = i/10;
}
printf("%d\n",s);
}
}
int main(void){
int a,b;
printf("enter the lower limit of the interval: "); scanf("%d",&a);
printf("enter the upper limit of the interval: "); scanf("%d",&b);
suma(a,b);
return 0;
}
when i set a to be 11 and b to be 13 program does first 3 sums but after that it doesent stop.why doesn't it stop. But if i set a to 3 digit number program gives me first sum but then gives me random sums
The reason why your code is not working is because in your while-loop, you are changing the value of i, but i is also used in the for-loop. This results in undefined behaviour. In order to fix this, I would suggest breaking the problem up in two functions. One for calculating the sum of a the digits of a number, and one function that adds these sums in a particular range.
int sumNumber(int number) {
int sum = 0;
while(number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
int suma(int a ,int b){
int totalSum = 0;
for(int i=a;i<=b;i++){
int sum = sumNumber(i);
totalSum += sum;
}
return totalSum;
}
This way, you are not modifying i in the while-loop.
You are mixing up the two loop variables. As arguments are passed by value just a instead of introducing an unnecessary variable. Minimize scope of variables. Check the return value from scanf() otherwise you may be operating on uninitialized variables.
#include <stdio.h>
void suma(int a, int b) {
for(; a <= b; a++) {
int s = 0;
for(int i = a; i; i /= 10) {
s += i % 10;
}
printf("%d\n", s);
}
}
int main(void){
printf("enter the lower limit of the interval: ");
int a;
if(scanf("%d",&a) != 1) {
printf("scanf failed\n");
return 1;
}
printf("enter the upper limit of the interval: ");
int b;
if(scanf("%d",&b) != 1) {
printf("scanf failed\n");
return 1;
}
suma(a,b);
}
and example run:
enter the lower limit of the interval: 10
enter the upper limit of the interval: 13
1
2
3
4
I was unreasonably annoyed by how the code was formatted. Extra white space for no reason including at end of line, missing white space between some operations, variables lumped together on one line.
It's a really good idea to separate i/o from logic as in #mennoschipper's answer. My answer is as close to original code as possible.
i did function like this and it works now
void suma(int a ,int b ){
int s= 0,i;
int x ;
for(i=a;i<=b;i++){
x = i;
while(x != 0 ){
int br = x % 10;
s+=br ;
x = x/10;
}
printf("%d\n",s);
s = 0;
} }

How can assign only the three largest integers from a for loop in C into three separate variables?

I am trying to make a program that takes two user inputs (x and y), checks all numbers in the interval for all prime numbers, and then prints only the three largest prime numbers if available. So far, my code checks all the prime numbers in an interval starting from the largest to the smallest.
My code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primeChecker(divisor+1,dividend);
}
void largestonly(int*counter, int*largest1, int*largest2, int*largest3){
int temp;
temp=*counter;
if (temp>*largest1&&*largest2) ///incomplete attempt
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y,largest1, largest2, largest3, counter, divisor, dividend, i;
divisor=2;
dividend=counter;
inputXY(&x, &y);
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for (i=0; i<=3; i++){
for(counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1) largestonly(&counter, &largest1, &largest2, &largest3);
}
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
I have yet to successfully write a working function that can sort all the integers produced by the for loop in main(). It is the largestonly() function as seen above. In relation to that, my printlargest() function undoubtedly does not work. My idea in here is that if largest1 does not contain any value (or is equal to 0 or some other more appropriate value that I could not think of), the function will only print the two largest prime numbers found. Relatively, if both largest1 and largest2 are empty, only the largest prime number will be printed. If all variables are empty, it should print "No prime numbers found!". I am very lost with what to do with my code at the moment so any type of help will be greatly appreciated. Thank you.
There are a few things to do here.
First, pay attention to the line 21, you call a primeChecker() function that doesn't exist. It will raise an error when compiling.
Second, you don't have to "sort" anything. You only have to store the prime numbers into the variables as they arrive. I noticed you consider largest3 to be the first one that has to be filled (at least it is what can be understood from printlargest()), this gives us the following:
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
Additionally, there is no need to pass the address of counter in the first place, as you won't need to modify it.
Lastly, in the main() function, you don't need a double loop. Think of it this way. If you were to do the exercise mentally, you'd go down the numbers, check if they were primes, and write them down if they satisfy the conditions: being primes and being the first, second or third. You wouldn't need to do it 3 times. Hence:
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
Also, the way you declared your variables without initializing them can sometimes be dangerous. In this case, as largest1, largest2 and largest3 weren't set to 0, you'd have had no chance to trigger any of the printlargest() cases. It may be because you were stuck on a part of your program you thought would also handle that but I still want to point it out, just in case.
EDIT: you could also add a condition in the for loop such that if largest1 is not equal to 0, it exits the loop. It would prevent the program to loop through (potentially) big amount of numbers when you already have everything you need. It would look like this (with the existing for loop, for context):
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
if(largest1 != 0)
break;
}
Hope this clears out the issues you had, feel free to ask anything if necessary, or to point out things I'd have misunderstood in your question.
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primechecker(divisor+1,dividend);
}
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
First, define how you would check for a prime number:
bool is_prime(int num)
{
if (num < 2)
return false;
for (int i = 2; i <= num / i; ++i)
if (num % i == 0)
return false;
return true;
}
Then, define a function that returns the 3 largest prime numbers in a given interval:
void get_max_3_in_range(int lo, int hi, int *max1, int *max2, int *max3)
{
*max1 = 0; // smallest
*max2 = 0;
*max3 = 0; // largest
int round = 0;
for (int i = lo; i <= hi; ++i) {
if (is_prime(i)) {
if (round % 3 == 0) *max1 = i;
if (round % 3 == 1) *max2 = i;
if (round % 3 == 2) *max3 = i;
++round;
}
}
if (*max1 > *max2) swap_int(max1, max2);
if (*max2 > *max3) swap_int(max2, max3);
}
Here is your swap():
void swap_int(int *v1, int *v2)
{
int tmp = *v1;
*v1 = *v2;
*v2 = tmp;
}
Driver program:
int main(void)
{
int x, y;
inputXY(&x, &y);
int max1, max2, max3;
get_max_3_in_range(x, y, &max1, &max2, &max3);
printf("x = %d\ty = %d\n", x, y);
printf("max1 = %d\tmax2 = %d\tmax3 = %d\n", max1, max2, max3);
}
Output:
Enter value of x: 0
Enter value of y: 100
x = 0 y = 100
max1 = 83 max2 = 89 max3 = 97
You can choose what to output in case one or more of the maximums is/are zero. Here, I chose to print them all.
Side note: Your inputXY() is very error-prone. Because if the user enters a string, your code will break. scanf() returns a value that you must check.
Following is a better version:
void inputXY(int *x, int *y)
{
for(;;) {
printf("Enter value of x: ");
if (scanf("%d", x) != 1)
flush_stdin();
else
break;
}
flush_stdin();
for(;;) {
printf("Enter value of y: ");
if (scanf("%d", y) != 1)
flush_stdin();
else
break;
}
}
And flush_stdin() (Never do fflush(stdin)!!) will clear what remained in the buffer, in case the user didn't enter (just) a number:
void flush_stdin(void)
{
scanf("%*[^\n]");
}

Why is this program giving the result 0 or garbage value although all the conditions have been met?

Why is this program giving the result 0 or garbage value although all the conditions have been met ?
As i read it is okay to write the if...else without the else clause.
// Program to find the largest of three given numbers
#include <stdio.h>
int main()
{
int a, b, c, big;
printf("Enter three given numbers : ");
scanf("%d%d%d", &a, &b, &c);
// if (1>2) (1>3) (2>3)
if (a > b) // 1>2
{
if (a > c)
big = a;
else
big = c;
}
printf("The largest numnber is = %d",big);
return 0;
}
To make it more clear this if statement
if (a > b) // 1>2
{
if (a > c)
big = a;
else
big = c;
}
may be rewritten like
if (a > b) // 1>2
{
//.. unimportant
}
provided that a is not greater than b. That is in this case the sub-statement of the if statement that represents the compound statement will not get the control. And as a result the variable big will not be initialized.
Your program could look the following way
#include <stdio.h>
int main( void )
{
int a = 0, b = 0, c = 0, big;
printf( "Enter three numbers: " );
scanf( "%d %d %d", &a, &b, &c );
if ( !( a < b ) && !( a < c ) )
{
big = a;
}
else if ( !( b < c ) )
{
big = b;
}
else
{
big = c;
}
printf( "The largest number is = %d\n", big );
return 0;
}
Pay attention to that the user can enter for example three numbers equal each other.
You are missing the branch where this is false:
if (a > b)
big will then be left uninitialized and have an indeterminable value.
To catch all combinations using only two comparisons, you could do like this:
if (a > b) big = a;
else big = b;
if(c > big) big = c;
A more general form:
int arr[...] = {filled with values};
big = arr[0];
for(size_t i = 1; i < sizeof arr / sizeof *arr; ++i) {
if(arr[i] > big) big = arr[i];
}
My two cents for the simplest solution:
#include <stdio.h>
int main()
{
int big, b, c; // only need 3 variables
printf("Enter three given numbers : ");
// should check this return value
scanf_s("%d%d%d", &big, &b, &c); // assume first value entered is largest
if (b > big) big = b; // b larger? reassign
if (c > big) big = c; // c larger? reassign
// big is now the largest number entered
printf("biggest number is %d\n", big);
return 0;
}
Logically your programm is not correct. After if you should use else.
In your programm, when you input numbers {1,2,3}, big is never initialized. However if you input {3,2,1} it will output correct result.
#include <stdio.h>
int main()
{
int a, b, c, big;
printf("Enter three given numbers : ");
scanf_s("%d%d%d", &a, &b, &c);
if (a > b)
{
if (a > c)
big = a;
else
big = c;
printf("The largest numnber is = %d", big);
}
else
printf("The largest numnber is not detected");
return 0;
}

How do I print ordinal indicators in a C program? Can't print numbers with 'st', 'nd', 'rd'. (Beginner)

#include <stdio.h>
main()
{
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
if(i==1) //for 1st
printf("1st value : ");
else if (i<=2) //2nd
printf("2nd value : ");
else if (i<=3) //3rd
printf("3rd value : ");
else //else print th ordinal
printf("%dth value : ", i);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
A program to take out the average of n numbers.
Now, this code does what it should, but if the size of the array goes beyond 20, it prints 21th, 22th, 23th and so on, which is wrong. I can't think of how to fix this problem. Any help would be great. I am new to programming, so pardon my ignorance.
There isn't a standard function that does that. You can write one, or use mine:
ordinal.c
#include "ordinal.h"
#include <stdio.h>
static const char *const suffixes[4] = { "th", "st", "nd", "rd" };
enum { NUM_SUFFIXES = sizeof(suffixes) / sizeof(suffixes[0]) };
static unsigned suffix_index(unsigned n)
{
unsigned x;
x = n % 100;
if (x == 11 || x == 12 || x == 13)
x = 0;
else if ((x = x % 10) > 3)
x = 0;
return x;
}
char *fmt_ordinal(char *buffer, size_t buflen, unsigned n)
{
unsigned x = suffix_index(n);
int len = snprintf(buffer, buflen, "%u%s", n, suffixes[x]);
if (len <= 0 || (size_t)len >= buflen)
return 0;
return(buffer);
}
ordinal.h
/* returns buffer or 0 on failure (implausible unless buffer too small) */
extern char *fmt_ordinal(char *buffer, size_t buflen, unsigned n);
Some of that is overkill on its own, but the source file also contains scn_ordinal() which scans ordinal numbers with greater or lesser strictness, and the header declares it.
int main(void)
{
char buffer[15];
/* Test fmt_ordinal() */
for (unsigned i = 0; i < 35; i++)
printf("%2u => %4s\n", i, fmt_ordinal(buffer, sizeof(buffer), i));
return 0;
}
You can mod by 10 to get the last digit. Then based on that you can use "st", "nd", "rd", or "th". You'll also need special cases for 11, 12, and 13.
if ((i % 10 == 1) && (i % 100 != 11))
printf("%dst value : ", i);
else if ((i % 10 == 2) && (i % 100 != 12))
printf("%dnd value : ", i);
else if ((i % 10 == 3) && (i % 100 != 13))
printf("%drd value : ", i);
else
printf("%dth value : ", i);
I played with this a bit and this was my minimal 'lookup' except, sadly, for the expense of the modulo division. I wasn't fussed about values above 99.
if( i > 20 ) i %= 10; // Change 21-99 to 1-10.
if( i > 3 ) i = 0; // Every other one ends with "th"
// 0 1 2 3
suffix = &"th\0st\0nd\0rd"[ i * 3 ]; // Acknowledge 3byte regions.
You can use 'suffix' as a pointer to a normal null terminated string.
It is okay to be a beginner, no need to apologize. You can solve your problem using a combination of a SWITCH statement and the modulus operator (%). The modulus operator takes two numbers (n1 % n2) and returns the remainder when n1 is divided by n2.
You will want to construct an array of ordinals, like this:
char *ordinalList[] = { "st", "nd", "rd", "th" };
This will allow you to simply reference this array to append the correct ordinal to a number. The next step is to create an algorithm to determine which array index should be referenced. To do this, you can make a new function and call it in your "main".
char *determineOrdinal (char **ordinalList, int numValue)
{
if (3 < numValue && numValue < 21)
return ordinals[3];
switch (numValue % 10) {
case 1 : return ordinalList[0];
break;
case 2 : return ordinalList[1];
break;
case 3 : return ordinalList[2];
break;
default: return ordinalList[3];
break;
}
You can pass a number into this function as the numValue argument. Your "main" function might look something like this:
#include <stdio.h>
int main(void)
{
char *ordinalList[] = { "st", "nd", "rd", "th" };
char *currentdOrdinal;
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
currentdOrdinal = determineOrdinal (ordinalList, i)
printf("%d%s value : ", i, currentdOrdinal);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
I think that code should work for you. I hope this helps.

C program on part of algorithm which focus on finding Armstrong-like number

I have a problem with C program. The idea of it is similar to Armstrong number checking. Say if the input number is 123. Program needs to check if condition, for example 123=1^1+2^2+3^3 is true. I know how to add digits,but have a problem with powers. It is obvious that I need a loop for powers from 1 to the number of digits. In Armstrong number algorithm you have similar power on every digit. For example 153=1^3+5^3+3^3. Here is what I have so far:
#include<stdio.h>
int main()
{
int n,d,s=0,o,i,k;
printf("n=");scanf("%d",&n);
d=n;
while(d!=0)
{
o=d%10;
s=s+o;
d=d/10;
k++
}
printf("sum:%d",s);
printf("number of digits:%d",k);
return 0;
}
Thanks for the answers.
You need first get the lenth of number, which is used to determine how many times you need to get into loop to calculate each bit.
For example, number 123, you first need to know the number is 3 bits len, then you can mutilply number 3 three times, number 2 twice, and number 1 once.
I use a temporary string to achieve this
here is codeļ¼Œ a little bit alteration on yours
#include <stdio.h>
#include <string.h>
#define MAX_NUM_LEN 16
int main()
{
char tmp_num[MAX_NUM_LEN] = {0};
int len,n,d,s=0,o,i,tmp_len, tmp_o;
printf("n=");scanf("%d",&n);
sprintf(tmp_num, "%d", n);
len = strlen(tmp_num);
tmp_len = len;
d=n;
while(d!=0)
{
o=d%10;
for (tmp_o = 1, i = tmp_len; i > 0; i--)
tmp_o *= o;
s=s+tmp_o;
d=d/10;
tmp_len--;
}
printf("sum:%d\n",s);
printf("number of digits:%d\n",len);
return 0;
}
results:
According of what I've understood I think this is what the OP is looking for:
int power(int base, int exp)
{
if (base == 0) return 0;
int result=1;
while (exp-- > 0) result*=base;
return result;
}
void calculate(int number)
{
int d=number;
int tmpnumber=number;
int n=0;
while (d > 0)
{
n++;
d /=10;
}
printf("Number of digits: %d\n", n);
int k=0;
int sum=0;
while (n--)
{
// get digits from left to right
d=number / power(10, n);
k++;
sum+=power(d, k);
number %= power(10, n);
printf("%d^%d=%d\n", d, k, power(d, k));
}
printf("\n%5d %5d", tmpnumber, sum);
}
int main(int argc,char *argv[])
{
int value;
while (TRUE)
{
printf("Enter value (0 = Quit): ");
scanf("%d", &value);
if (value <= 0) return 0;
calculate(value);
printf("\n");
}
}

Resources