Printing Odd Numbers using Goto Statememt in C Programming
This is a C program that prompts the user to enter two integers, 'i' and 'n' , and then uses the goto statement to print all the odd numbers between i and n.
- The #include<stdio.h> is a preprocessor directive that includes the contents of the standard input-output library in the program. The int main() function is the starting point of the program execution.
- Inside the main function, two integers i and n are declared. printf() is used to display the prompt for the user to enter the starting and ending values, and scanf() is used to get the input and store it in the variables 'i' and 'n' respectively.
- A label start is defined and a goto statement is used to jump to this label. The code between the label and the goto statement will execute repeatedly until the condition i<=n is false.
- The first time the code is executed, the modulus operator % is used to check if the current number i is odd or not by using the condition i%2==1. If the value is true, the number is printed using printf("\n%d",i) .
- Then the value of i is incremented by 1. Then the condition i<=n is checked, if it's true the control jumps back to the label 'start' and the same process is repeated until the condition is false.
- It is worth noting that the use of the goto statement is generally discouraged in modern programming because it can lead to unstructured and hard-to-maintain code. Alternative control structures such as for loops, while loops or do-while loops can be used for the same purpose and are considered more readable, maintainable and less prone to errors.
Finally, the return 0 statement is used to indicate the successful execution of the program. The return value of 0 is a convention used to indicate that the program has executed correctly.
Source Code
#include<stdio.h>
int main()
{
int i,n;
printf("\n Enter the starting value:");
scanf("%d",&i);
printf("\n Enter the Ending value:");
scanf("%d",&n);
start:
if(i%2==1)
{
printf("\n%d",i);
}
i++;
if(i<=n)
{
goto start;
}
return 0;
}
To download raw file
Click Here
Output
Enter the starting value: 5
Enter the Ending value : 15
5
7
9
11
13
15