'Sum of numbers occurring in the multiplication table of 8. What's wrong with my code? Desirable output is 440, and I'm getting 33204
Sum of numbers occurring in the multiplication table of 8. What's wrong with my code? Desirable output is 440, and I'm getting 33204.
#include <stdio.h>
int
main ()
{
int sum, n, p;
printf ("Sum of numbers occurring in the multiplication table of 8: ");
do
{
p = 8 * n;
sum += p;
n++;
}
while (n <= 10);
printf ("%d", sum);
return 0;
}
Solution 1:[1]
You are using uninitialized variables
int sum, n, p;
that have indeterminate values.
As a result your program has undefined behavior.
You need to initialize them like
int sum = 0, n = 1, p;
Solution 2:[2]
Please initialize n first. Attaching my code for reference here:Code and ouput attached
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Aditya Singh |