The code has undefined behavior: when you first test the num value, it is not initialized. If by chance this is not negative, you scan the new value and add its square to the uninitialized variable sum , creating a more undefined behavior, the input value is negative, the next test fails, and the cycle repeats forever.
In accordance with the conversion format %-10d , left alignment with a width of 10 spaces is obtained.
Here is the corrected version:
#include <stdio.h> int main(void) { int num, square, sum = 0; while (scanf("%d", &num) == 1 && num != 0) { square = num * num; sum = square + sum; printf("%-10d\n", sum); } return 0; }
If you want the number to be correct justified in 10x the width, so all output values ββare aligned correctly, use the %10d format instead.
If you enter large numbers or too many elements, you will eventually exceed the range of type int . You can try and increase the range of square and sum variables by making them long long int or even commenting on PeterJ unsigned long long int , and allow the calculation of larger values:
int main(void) { int num; unsigned long long square, sum = 0; while (scanf("%d", &num) == 1 && num != 0) { square = (long long)num * num; sum = square + sum; printf("%21llu\n", sum); } return 0; }
Note that (long long)num * num will be converted to unsigned long long , which has a range of at least positive values.
source share