Home > Software design >  How to store a value of a variable and update it's value inside a loop in C language?
How to store a value of a variable and update it's value inside a loop in C language?

Time:10-31

I am new to programming in C and I am doing some activities for my first year in CS. The following activity consists of calculating the sum of squares of the digits of a user input number and the output should be as follows:

Number: 1234
  n=1234; sum=16
  n=123; sum=25
  n=12; sum=29
  n=1; sum=30
Result: 30

I have got it for the most part, the thing that I don't understand is how to store a value in a variable, update said variable and print the result, all whilst being inside a loop.

This is what I came up with:

int main() {
        
    int num,i,sum=0,result,square;
     
    printf("Calculate the sum of the square of the digits of a number\n" );
    printf("Number:");
    scanf("%d", &num);
    i=0;
    while(num>i)
    {
        sum=num;
        square=sum*sum;
        printf("\nn=%d; sum= %d",num,square);
        num=num/10;
    }
    result=sum;
    printf("\nResult: %d",sum);
    
    return 0;
}

How can I sum the square of the digits all together and print them as the example given?

CodePudding user response:

Write something like the following

int digit = num % 10;
square = digit * digit;
sum  = square;
printf("\n=%d; sum= %d", num, sum );

Pay attention to that the variable i is redundant:

i=0;
while(num>i)

just write

while ( num != 0 )

Also introducing the variable result is redundant and does not make sense because it is used nowhere.

CodePudding user response:

You need a variable, keeping track of the input number (num), a variable keeping track of the sum ('sum') and a variable with the current digit (digit). Every iteration, you can calculate the digit, square it and add it to the sum. The a = b operation is equivalent to a = a b, in case you are wondering. The same is for a /= b. Also a concept you can use (but don't have to), is implicit boolean conversion. When using a comparison (like num != 0 or num > 0) you can replace it with the number itself. In C, 0 equals false and everything else equals true.

#include <stdio.h>

int main() {
    int num, sum = 0;
    printf("Calculate the sum of the square of the digits of a number\n" );
    printf("Number:");
    scanf("%d", &num);
    while (num) { // is equal to num != 0
        int digit = num % 10;
        sum  = digit * digit;
        printf("    n=%d; sum= %d\n", num, sum);
        num /= 10;
    }
    printf("Result: %d\n", sum);
    return 0;
}

EDIT:

Some people prefer to use num != 0 or num > 0, because it is more readable. You should stick to it too for the start, until you are paid to confuse your coworkers.

  • Related