Submersed24 Submersed24 - 2 months ago 9
C Question

C program error - outputting 0

I have been trying to get this to work for days now... I am getting closer and closer to my deadline and I still cannot figure out the error. When I output the code, it prints, but it will not find the amicable pairs(divisor of first == second, and vice versa) Could I please have help on this?

#include <stdio.h>
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>

int sumDivisors( int num );

int sumDivisors( int num )
{
int counter, total;
for( counter = 1; counter < num; counter++ )
{
if( num % counter == 0 )
{
total += counter;
}
}
return ( total );
}

int main( void )
{
int higher, lower, lowx, lowy, x, y, numOfPairs = 0;

printf( "This program finds all amicable numbers within a range. \n" );
printf( "Please enter a lower limit: \n" );
scanf( "%d", &lower );
printf( "Please enter a higher limit: \n" );
scanf( "%d", &higher );


for( lowx = lower; lowx <= higher; lowx++ )
{
for( lowy = lower; lowy <= higher; lowy++ )
{
if( sumDivisors( lowx ) == sumDivisors( lowy ) )
{
numOfPairs++;
printf( "Pair #%d: (%d, %d)\n", numOfPairs, lowx, lowy );
}
}
}

printf( "There are %d amicable pairs from %d to %d\n", numOfPairs, lower, higher );
system("pause");
return ( 0 );
}

Answer

You are not assigning any value to total in your code:

int sumDivisors( int num )
{
  int counter, total;
  for( counter = 1; counter < num; counter++ )
    {
      if( num % counter == 0 )
        {
            total += counter;
        }
    }
  return ( total );
}

so it contains garbage not predictable value!

it should be like: int counter, total = 0;