-
Integer Problem
I have an assignment I have been working on and I am a little confused. The code works but I am not sure about my IF statement. I tried validating my IF statement against the function multiple but I get an error when compiling. If I take out the =1 and leave it as IF ( multiple (num1, num2) ) it works. How does the IF statement know to either print the first statement or the second statement if you dont validate the function. I hope this make sense.
Code:
#include <stdio.h>
/* Function Prototype */
int multiple( int num1, int num2 );
/* Function main begins program execution */
int main()
{
int counter; /* Variable in which counter will be stored */
int num1; /* Variable in which sidea will be stored */
int num2; /* Variable in which sideb will be stored */
for( counter = 1; counter <= 3; counter ++ ) {
printf( "Enter the first integers: " ); /* Prompt for input */
scanf( "%d", &num1 ); /* Read number1 from user */
printf( "Enter the second integers: " ); /* Prompt for input */
scanf( "%d", &num2 ); /* Read number2 from user */
if ( multiple( num1, num2 ) ) /* WHY NOT IF (MULTIPLE(NUM1,NUM2)) = 1 */
printf( "%d is a multiple of %d\n\n", num2, num1 );
else
printf( "%d is not a multiple of %d\n\n", num2, num1 );
}
return 0; /* Indicates that program ended successfully */
} /* End function main */
/* Multiple function definition */
int multiple( int num1, int num2 )
{
int temp; /* Variable in which temp will be stored */
/* temp will contain the remainder of an integer divide, zero if num1 is a factor of num2 */
temp = num2 % num1;
/* Returns a one or a zero */
if (temp == 0) {
return 1;
}
else {
return 0;
}
} /* End function mutliple */
-
If you want to explicitly write the condition, you could do it this way:
Code:
if ( multiple( num1, num2 ) == 1 )
Boolean expressions in C are as follows: 0 is false, everything else is true. This means that no matter what multiple() returns, it's true unless it returns 0, in which case it'll resolve the expression as false.
multiple(num1,num2) returns 1 when num2 is divisble by num1 by your function definition. The if statement will take that to mean true since it's not 0.
-
Thank you for the explanation