Search code examples
cinitializationdeclarationdo-while

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

  • 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;