Solved Examples · Example 21
Q.Write a C program to accept two floating point numbers and complete their ratio. If the ratio is greater than zero then it should exchange the contents of the numbers.
The textbook presents this worked program, transcribed exactly as printed (including its printed errors):
#include<stdio.h>
void main()
{
float a, b, ratio, temp;
printf("Enter a and b\n");
scanf("%f%f", &a, &b);
ratio=a/b;
printf("Ratio =%f\n", ratio);
if (ratio>0);
{ /* block begins */
temp=a;
a=b;
b=temp
}
/*End of if*/
printf("a=%f, b=%f\n", a,b);
}
/*End of main()*/
Sample output printed in the textbook:
Enter the value of a and b
19.0
36.0
Ratio = 0.527777
a = 36.000000, b = 19.000000
#include<stdio.h>
void main()
{
float a, b, ratio, temp;
printf("Enter a and b\n");
scanf("%f%f", &a, &b);
ratio=a/b;
printf("Ratio =%f\n", ratio);
if (ratio>0);
{ /* block begins */
temp=a;
a=b;
b=temp
}
/*End of if*/
printf("a=%f, b=%f\n", a,b);
}
/*End of main()*/
Enter the value of a and b
19.0
36.0
Ratio = 0.527777
a = 36.000000, b = 19.000000
Karnataka PUCTextbookLongImportance★★★★★est
65% · 100/154 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →[!TLDR]
Compute ratio = a/b, and if it is > 0 swap a and b via a temp variable; 19.0 and 36.0 become 36.0 and 19.0.
Two ideas meet here: the classic three-variable swap and a guarded (conditional) action. Exchanging two values needs a temporary store - temp = a; a = b; b = temp - because assigning a = b first would overwrite a before it is saved. The swap is wrapped in an if (ratio > 0) so it happens only when the ratio is positive; the braces group the three statements into one compound statement that the if controls. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.