joy_finder
joy_finder

Reputation: 67

Right angled triangle in C

I was learning C program recently, and had some problem in my written code. Here is below:

include <stdio.h>
include <stdlib.h>

int main(int argc, char *argv[]) 
{

int x, y, z;

printf("Enter value for x: ");
scanf("%d", &x);
if(x < 1)
{
   printf("Invalid value\n");
   exit(1);
}

printf("Enter value for y: ");
scanf("%d", &y);
if(y < 1);
{
   printf("Invalid value\n");
}

printf("Enter value for z: ");
scanf("%d", &z);
if(z < 1);
{
  printf("Invalid value\n");
  exit(1);
}

int lhs = x * x + y * y;
int rhs = z * z;

if(lhs == rhs)
{
    printf("Right angled triangle\n");
}
else
{
    printf("%d is not right angled and equal %d\n", lhs, rhs );
}

As I opened terminal to test my code, I entered x value with and continued with entering y value with 4, then it directly shows invalid value, why did it happen?

Upvotes: 1

Views: 532

Answers (1)

Samuel Dominguez
Samuel Dominguez

Reputation: 318

You have a semicolon immediately after the if (y < 1) (this is also the case with your z check, but the x check is okay).

Remove that semi-colon and it should work.


In more detail, the statement if (y < 1); is equivalent to:

if (y < 1) {
    // do nothing.
}

meaning that the code that follows is unconditional (the braces just create a new scope for executing it which is irrelevant since you're not actually declaring any variables within that scope).

Upvotes: 1

Related Questions