Search code examples
clogical-operatorsrelational-operators

OR and less than operators not working as intended C language


I'm doing an exercise of a book called programming in C language, trying to solve exercise 7.9 and so my code works perfectly until I add a conditional statement for the function to only accept variables greater than 0

I have tried changing it in many ways but nothing seems to work

// Program to find the least common multiple
#include <stdio.h>

int main(void)
{
 int lcm(int u, int v);

 printf("the least common multiple of 15 and 30 is: %i\n", lcm(15, 30));

 return 0;
 }
// Least common multiple
int lcm(int u, int v)
{
 int gcd(int u, int v);

 int result;

 if (v || u <= 0)
 {
    printf("Error the values of u and v must be greater than 0");
    return 0;
 }

 result = (u * v) / gcd(u, v);
 return result;
}
// Greatest common divisor function
int gcd(int u, int v)
{
 int temp;
 while (v != 0)
 {
    temp = u % v;
    u = v;
    v = temp;
 }
 return u;
 }

I expect the output of lcm(15, 30) to be 30, but I keep getting an error, if a delete de if statement inside the lcm function it works fine, but I want the program to return an error if for example I use (0, 30)


Solution

  • if (v || u <= 0) is not saying "if v is less than or equal to zero OR if u is less than or equal to zero", like I believe you think it is. It's actually saying "if v is not zero, OR u is less than or equal to zero".

    The operation a || b tests if a evaluates to non-zero, and if it doesn't, then it tests if b evaluates to non-zero. If either a or b is non-zero, then the expression is true.

    In C, equality and relational operators like ==, !=, <, >, <= and >= produce the result 1 if the relation is true, and 0 if it is false, allowing you to use them in conditional expressions.

    The correct conditional is:

    if (v <= 0 || u <= 0)