C Decision Making - Branching

The GOTO statement

The goto statement is simple statement used to transfer the program control unconditionally from one statement to another statement.
Although it might not be essential to use the goto statement in a highly structured language like C, there may be occasions when the use of goto is desirable.

Syntax 
a > b > 
goto label; 
label; 
………….. …………. 
…………. …………. 
…………. …………. 
Label; 
goto label; 
Statement; 
        

Syntax description

The goto requires a label in order to identify the place where the branch is to be made.
A label is a valid variable name followed by a colon.
The label is placed immediately before the statement where the control is to be transformed. A program may contain several goto statements that transferred to the same place when a program.
The label must be unique. Control can be transferred out of or within a compound statement, and control can be transferred to the beginning of a compound statement. However the control cannot be transferred into a compound statement.
The goto statement is discouraged in C, because it alters the sequential flow of logic that is the characteristic of C language.

Sample program

/*A program to find the sum of n natural numbers using goto statement */ 
#include < stdio.h > //include stdio.h header file to your program 
main ( ) //start of main 
{ 
int n, sum = 0, I = 0, // variable declaration 
printf (“Enter a number”); // message to the user 
scanf (“%d”, &n); //Read and store the number 
Loop: I ++; //Label of goto statement 
Sum + = I; //the sum value in stored and I is added to sum 
If (i < n) goto Loop; 
Printf (“\n sum of %d natural numbers = %d”, n, sum); 
} 
        

Make Comments..!!


Oops!! No posts from user.

Download Android App