Explore
ProGrad Programs
Placement Prep
TCS Codevita
Webinars
About Us

Edit
Reply




Edit

Goto statement in C

Published on 06 Mar 2020

Goto statements are used to make unconditional jumps. Without testing any condition, the control can be transferred from one point to another point in the program. The use of goto is highly discouraged in a powerful structured programming language like C.


Syntax:

Backward:                                                   

label:                                                               
Statements                                
goto label      

(or)                                            

Forward:
goto label
statements
label:


The label can be named according to the user's wish provided it follows the naming rules.


Example: Read n letters containing both uppercase and lowercase letters. Write out the letters with uppercase and lowercase letters reversed, but all other characters intact.

int main( )
{
char c;
int n=0,count=0;
printf("Enter the number of characters:");
scanf("%d",&n);
repeat:                                                         // here repeat is the label or name of the location where 
printf("Enter a character:");                the goto statement can transfer the control to.
c=getchar( );
if(isupper(c))
c=tolower(c);
else
c=toupper(c);
putchar(c);
fflush(stdin);
count++;
if(count<n)
goto repeat;
getch( );
return 0;
}

 

The number of characters to be converted is got from the user in the variable n. Then a character is read and converted to its reverse case. After this, the count variable which is initially zero is incremented and checked whether it is less than n. If so, the above-said operations have to be repeated (reading a char, converting it and displaying). Hence, the point where the reading starts is given a name or label(repeat) and the control is transferred to that point again and again as long as the count is less than n.

If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in