Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Latest Posts

C Programming goto Statement

In C programming, goto statement is used for altering the normal sequence of program execution by transferring control to some other part of the program.

Syntax of goto statement

goto label;
.............
.............
.............
label: 
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the control of the program will jump to the label: and executes the code below it.

Example of goto statement


/*  C program to demonstrate the working of goto statement. */
/* This program calculates the average of numbers entered by user. */
/* If user enters negative number, it ignores that number and 
   calculates the average of number entered before it.*/

# include <stdio.h>
int main(){
   float num,average,sum;
   int i,n;
   printf("Maximum no. of inputs: ");
   scanf("%d",&n);
   for(i=1;i<=n;++i){
       printf("Enter n%d: ",i);
       scanf("%f",&num);
       if(num<0.0)
       goto jump;             /* control of the program moves to label jump */ 
       sum=sum+num;
}
jump:
  average=sum/(i-1);       
  printf("Average: %.2f",average);
  return 0;
}
Output
Maximum no. of inputs: 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average: 7.07
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced as much as possible in a program.

Reasons to avoid goto statement

Though, using goto statement give power to jump to any part of program, using goto statement makes the logic of the program complex and tangled. In modern programming, goto statement is considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue statements. In fact, any program in C programming can be perfectly written without the use of goto statement. All programmer should try to avoid goto statement as possible as they can.

Go Back on Home Chapter By Clicking below Button :)
If above button is not working then copy the below link and paste in your address bar.


http://www.mastercaptainit.com/p/c-programming-tutorial.html

No comments:

Post a Comment

Master Captain IT Designed by Master Captain It Team. Copyright © 2014

.
Theme images by Bim. Powered by Blogger.