I was implementing Newton Raphson method in C. The code work well. There is no error in the code.
#include<stdio.h>
#include<math.h>
#define f(x)(x * sin(x)+cos(x))
#define df(x)(x*cos(x))
int main()
{
float x,h,e;
e=0.0001;
printf("Enter the initial value of x:\n");
scanf("%f",&x);
do
{
h=-f(x)/df(x);
x=x+h;
}
while(fabs(h)>e);
printf("The value of the root is=%f",x);
return(0);
}
/*
Output:
Enter the initial value of x: 3
The value of the root is = 2.798386
However, I was surprised I mean how did this code work? As per c rule while statement does not have any terminating semicolon. However, in my code while(fabs(h)>e); has a semicolon yet it run well.
Can anyone tells me how does it work?
What you mean is putting
while(...);
{
//some code
}
that will be interpreted as
while(...){
//looping without any instruction (probably an infinite loop)
}
{
//some code that will be executed once if the loop exits
}
do-while
loop has the code executed before the condition (so at least once differently from simple while loop). The correct syntax has a semicolumn:
do{
//your code to be executed at least once
}while(...);