Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

TASK 2 MARKS -LO6A] Write a program that uses nested for loops to calculate side

ID: 3703495 • Letter: T

Question

TASK 2 MARKS -LO6A] Write a program that uses nested for loops to calculate side length c using Pythagoras' Theorem (ab2 -c2) assuming a and b to be integer values starting from 1. Use the fprintf function to list all Pythagorean results that satisfy a 2 1, b 2 1 and cs10. A sample of the formatted results is shown below: Pythagorean results are a-1, b-1, c-1.41 a-1, b-2, c 2.24 a-1, b-3, c 3.16 a-9, b 2, c-9.22 a-9, b-3, C-9.49 a-9, b-4, c 9.85 Also use fprintf to print the number of combinations that satisfy the above restrictions and the sum of all b values of the valid combinations

Explanation / Answer

Solution :

/*

***pythagoras.c: Program to calculate side length c using pythagoras theorem. List all

***pythagorean results that satisfy a>=1, b>=1 and c <=10 in values.txt file

*/

#include <stdio.h>

#include <math.h>

#include <stdlib.h>

int main()

{

FILE *fp; //file pointer

int a,b;

float c=1.0;

fp = fopen("values.txt", "w+"); //store all valid combinations in values.txt

for(a = 1; a <= 9; a++)

{

for(b = 1; b <= 9; b++)

{

if(sqrt((a *a)+ (b * b)) <= 10.0) // check c <= 10

{

c = sqrt(a *a+ b * b); //calculate c

fprintf (fp, "a = %d, b = %d , c = %.2f ",a,b,c);

}

}

}

fclose(fp);

return 0;

}

/////////////////////////////////////////////////////////////////////////

output :

ubuntu@ubuntu:~$ gcc pythagoras.c -o pythagoras -lm
ubuntu@ubuntu:~$ ./pythagoras

a = 1, b = 1 , c = 1.41
a = 1, b = 2 , c = 2.24
a = 1, b = 3 , c = 3.16
a = 1, b = 4 , c = 4.12
a = 1, b = 5 , c = 5.10
a = 1, b = 6 , c = 6.08

................

a = 9, b = 1 , c = 9.06
a = 9, b = 2 , c = 9.22
a = 9, b = 3 , c = 9.49
a = 9, b = 4 , c = 9.85