C Program to Find Total of Even Integers

C Program Exit with goto Statement

The below post gives simple steps how to use C program Exit with goto statement. Ready to execute code with clean output, in easy way with simple steps.

This C program to evaluate the series

1

—— = 1 + x + x2 + x3 + ….. + xn

1-x

for -1 < x < 1 with 0.01 per cent accuracy is given in below example,  The goto statement is used to exit the loop on achieving the desired accuracy.

C Program Exit with goto statement

We have used the for statement to perform the repeated addition of each of the terms in the series. Since it is an infinite series, the evaluation of the function is terminated when the term reaches the desired accuracy.

#define LOOP 100
#define ACCURACY 0.0001
main()
{
     int n;
     float x, term, sum;
     printf("Input value of x : ");
     scanf("%f", &x);
     sum = 0 ;
     for (term = 1, n = 1 ; n < = LOOP ; ++n)
     {
        sum += term ;
        if (term < = ACCURACY)
        goto output; /* EXIT FROM THE LOOP */
        term *= x ;
    }
printf("\nFINAL VALUE OF N IS NOT SUFFICIENT\n");
printf("TO ACHIEVE DESIRED ACCURACY\n");
goto end;
output:
printf("\nEXIT FROM LOOP\n");
printf("Sum = %f; No.of terms = %d\n", sum, n);
end:
      ; /* Null Statement */
}

The value of n that decides the number of loop operations is not known and therefore we have decided arbitrarily a value of 100, which may or may not result in the desired level of accuracy.

Output Screen

Input value of x : .21
EXIT FROM LOOP
Sum = 1.265800; No.of terms = 7
Input value of x : .75
EXIT FROM LOOP
Sum = 3.999774; No.of terms = 34
Input value of x : .99
FINAL VALUE OF N IS NOT SUFFICIENT
TO ACHIEVE DESIRED ACCURACY

Let me know if you find any difficulty in understanding this C Program example and I would be glad to explain it further.

Online Training Tutorials