Why am I getting an infinite loop from my code?

#include <stdio.h> int main() { int num; int square; int sum; while (num) { if (num > 0) { scanf("%d", &num); square = num * num; sum = square + sum; printf("%d \n", sum); } } return 0; 

I am trying to create a sum of squares for positive numbers, and when the first negative number is entered, the loop ends. The result should be justified by 10 spaces.

-1
source share
3 answers

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.

+2
source

Using an uninitialized variable results in undefined behavior. Your while loop uses the uninitialized local variable num . num can have any value. If the value is less than 0, the loop will run forever. It will also be cyclic if a value less than 0 is entered using scanf .

For undefined behavior, check strings from standard 6.3.2.1 Lvalues, arrays and function notation

If lvalue denotes an object with automatic storage time that can be declared with a register storage class (its address has never been), and this object is uninitialized (not declared with an initializer and no assignment to it was made earlier for use), the behavior is undefined.

0
source

Hope this can help complete the loop.

 #include <stdio.h> int main() { int num = 0; int sum = 0; while (num >= 0) { scanf("%d", &num); if (num>=0) { sum = ( num * num ) + sum; printf(" %d\n", sum); } } return 0; } 
-2
source

Source: https://habr.com/ru/post/1271080/


All Articles