How to square every digit of a number in C

1 Answer

0 votes
#include <stdio.h>

int SquareDigits(int number) {
    int digit, result = 0, mul = 1;

    while (number > 0) {
        digit = number % 10;
        result += digit * digit * mul;
        mul *= (digit <= 3) ? 10 : 100;
        number /= 10;
    }

    return result;
}

int main() {
    int num = 234;

    num = SquareDigits(num);

    printf("%d", num);

    return 0;
}




/*
run:

4916

*/

 



answered Aug 4, 2023 by avibootz
edited Aug 5, 2023 by avibootz

Related questions

2 answers 122 views
1 answer 124 views
2 answers 158 views
2 answers 168 views
2 answers 157 views
1 answer 117 views
4 answers 227 views
...