C Programming.


goto statement in C tutorials
-
Goto statement is used for branching to another part of program.
-
With the help of goto statement we can pass control to another statement within program.
Syntax:
goto label_name;
-
Where label_name has the same form as a variable name, and is followed by a colon :. The above statement tells to pass control to the line containing label name.
Program to test goto statement |
|
|
//Program Name :- test057.c//Program to test goto statement#include<stdio.h>void main(){printf("Hello friends\n");goto abc ;printf("How are you? \n");abc:printf("Welcome To \n");printf("cbtSam \n");} |
Output |
Hello friendsWelcome TocbtSam |
-
The first printf statement is executed first.
-
The second statement goto abc; (here abc is a label name) tells to pass control directly to the line where label name is written i.e. it will pass control directly to abc: and it will not execute statements written between goto <label > (here goto abc) and statement containing label name followed by colon i.e. abc :.
-
The statements written after abc: will be executed. And it will print cbtSam.
-
If you observe properly, of four printf statement printf("How are you? \n"); is not executed.
C Program to print whether no is even or odd using goto |
|
|
//Program Name :- test058.c//Program to print whether no is even or odd using goto#include<stdio.h>void main(){int no;printf("Enter No. : ") ;scanf("%d",&no);if(no%2 == 0)goto even;printf("%d No Entered is Odd Number \n",no);goto last;even:printf("%d No Entered is Even Number \n",no);last:printf("The Program Ends Here.\n");} |
Output |
Enter No. : 1212 No Entered is Even NumberThe Program Ends Here.Enter No. : 1717 No Entered is Odd NumberThe Program Ends Here. |
-
The above program begins with defining a integer variable no. The first printf statement prompts the user to enter any no and accepts number from the user. The number entered as input is stored in the variable no.
-
The if statement if(no% 2 ==0 ) checks that the remainder of the number entered and if result is equal to zero,then the goto even statement will be executed which will directly pass control to the line on which even followed by colon (i.e. even: ) is written and the next printf statements for even no is executed. After executing printf for even, it will goto last: and print The Program Ends Here statement.
If result of remainder is not zero, it will execute No is Odd Number statement and it will goto Last: statement which prints "The Program Ends Here" gets executed.