In: Computer Science
For C code: Do not use any function other than getchar, scanf, and printf
Q2.A) Write a program to do the following: Read in two values into variables X and y from the keyboard (they may be decimal values like 2.3). Read in a 3rd value (which is really small < 1.0 ) into variable E. Using a loop find out the value of N in the below expression. i.e. Each iteration of the loop reduced the value of Y by dividing it by 2. Print out N at the end when the condition is met. For most input X and Y values the condition may not become true and the loop would become an infinite loop. To break from such "traps", you can have a loop count and break away. i.e. Count how many iterations it has run through the loop body, and if it goes over some number, say 100, just use "break" after saying "there is no solution for the given numbers" which should end the program.
Note: This program conveys the convergence vs divergence in numerical methods.
(a) Let X = 1.02 Y = 8.1, E = 0.05. In each iteration Y/2N values become 8.1, 4.05, 2.025, 1.0125, and stops since X - 1.0125 is 0.0075 which is < E. This starting Y value converges toward a solution.
(b) If X = 1.02 and Y = 9.5, then it would not converge to a solution to meet the criterion, but diverges away. Y/2N value become 4.75, 2.375, 1.1875, 0.59375, 0.2968,goes to 0, but difference goes up.
code in c (code to copy)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
//declare variables
float x,y,e;
//read user input
scanf("%f %f %f", &x, &y, &e);
//declare a loop count to avoid trap
int loop_count=100;
//print the value of y
printf("%f ", y);
// calculate the difference between x and y
float diff = x-y;
//calculate the absolute difference
if(diff<0)
diff*=-1;
//loop until we exhaust loop_count or abs(x-y)<e
while(loop_count>0&&diff>=e){
//decrement loop_count
loop_count--;
//y=y/2 in each iteration
y=y/2;
//print the value of y
printf("%f ", y);
// calculate the difference between x and y
diff = x-y;
//calculate the absolute difference
if(diff<0)
diff*=-1;
}
if(x-y>=e){
//print divergence
printf("\ndivergence\nthere is no solution for the given numbers\n");;
}else{
printf("\nconvergence\n");;
}
}
code screenshot
Sample Input/Output screenshot 1