Three positive integer numbers a, band c, such that a<b<c form a Pythagorean triplet if c2= a2 +b2 , i. e,, a, b and c form the sides of a right-angled triangle. To select the values of a and b such that a < b and a, b < max, we can use nested for loops as shown below:
Note the use of typecast in the if statement to test whether c contains an integer value or not and in the printf statement. The complete program is given below.
/* Determine and print Pythagorean triplets */ #include<stdio.h> #include<conio.h> #include<math.h> void main() { int max; /* max value of side a or b */ int a, b; /* two sides of a triangle */ printf("Enter max value of sides a, b: "); scanf("%d", &max); for (a = 1; a <= max; a++) { for (b = a; b <= max; b++) { float c = sqrt(a *a+ b * b); /*third side*/ if (c == (int) c) printf ("%2d %2d %2d\n", a, b, (int) c); } } getch(); }