C goto statement
The goto statement is a control flow statement in C programming that allows you to transfer the control of a program to another part of the code. The goto statement is generally considered to be a less desirable method of controlling program flow, as it can make code more difficult to understand and maintain. However, in certain circumstances, it can be useful in controlling the flow of execution in loops. In this article, we will take a look at how to use the goto statement in loops with three examples.
Example 1: Printing numbers from 1 to 10 using goto statement
The first example demonstrates how to use the goto statement to transfer control within a loop. In this example, the loop variable "i" is initialized to 1, and the loop body is executed as long as the condition "i <= 10" is true. The goto statement is used to transfer control to the label "begin" when the value of "i" is equal to 5.
1#include <stdio.h> 2 3int main() { 4 int i = 1; 5begin: 6 if (i <= 10) { 7 if (i == 5) { 8 i++; 9 goto begin; 10 } 11 printf("%d\n", i); 12 i++; 13 goto begin; 14 } 15 return 0; 16}
Output:
11 22 33 44 56 67 78 89 910
Example 2: Printing even numbers from 1 to 10 using goto statement
The second example demonstrates how to use the goto statement to transfer control within a loop. In this example, the loop variable "i" is initialized to 1, and the loop body is executed as long as the condition "i <= 10" is true. The goto statement is used to transfer control to the label "begin" when the value of "i" is odd.
1#include <stdio.h> 2 3int main() { 4 int i = 1; 5begin: 6 if (i <= 10) { 7 if (i % 2 != 0) { 8 i++; 9 goto begin; 10 } 11 printf("%d\n", i); 12 i++; 13 goto begin; 14 } 15 return 0; 16}
Output:
12 24 36 48 510
Example 3: Finding the first perfect square using goto statement
The third example demonstrates how to use the goto statement to transfer control within a loop. In this example, the loop variable "i" is initialized to 1, and the loop body is executed as long as the condition "i <= 100" is true. The goto statement is used to transfer control to the label "end" when the first perfect square is found.
1#include <stdio.h> 2#include <math.h> 3 4int main() { 5 int i = 1; 6begin: 7 if (i <= 100) { 8 int root = sqrt(i); 9 if (root * root == i) { 10 printf("The first perfect square is: %d\n", i); 11 goto end; 12 } 13 i++; 14 goto begin; 15 } 16end: 17 return 0; 18}
Output:
1The first perfect square is: 1
goto statement can be useful in controlling the flow of execution in loops in C programming, but it is generally considered to be a less desirable method than other control flow statements like "if-else" statements, "for" loops, "while" loops, and "do-while" loops. It is important to use the goto statement with caution, as it can make code more difficult to understand and maintain. It is generally recommended to use the goto statement only in situations where it is the simplest and most straightforward solution.