Tuesday 2 October 2018

Printing counting numbers till n using if and goto statement in C++

Counting numbers


The infinite set of natural numbers or positive integers are known as counting numbers. They are used for quantification process(i.e. finding the quantity). All the integers from 1 to infinity are considered as counting numbers i.e. 1, 2, 3, 4, 5,.......to infinity.


Write a program in C++ to print counting numbers till n using if and goto statement.


In this program, we input how many numbers the user wants to print. Then using if and goto statement, we print the counting numbers. Generally for, while, or do...while statement is used for executing the same statement repeatedly. But the if statement can also be used to execute the same statement repeatedly using a goto statement. This method of using if and goto statement to produce iteration is not recommended as it increases the execution time of a program.

The goto statement is used to transfer the control of execution of the program to a specified label. It alters the normal sequence of program execution.
Syntax:
             goto label name;

The label is an identifier of the target where the control of execution is to be shifted. It can be placed anywhere within the main function, below or above the goto statement.


Program


#include<iostream.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
cout<<"How many numbers do you print= ";
cin>>n;
x:if(i<=n)
{
cout<<i<<endl;
i++;
goto x;
}
getch();
}


Output


Program to print counting numbers
PRINTING COUNTING NUMBERS USING IF AND GOTO STATEMENT














Explanation


In this program, the user wants to print 10 numbers(i.e. n=10). We use if statement to check whether the condition i<=n(i.e. 1<=10) is true or false. If the condition is true then the number is printed. Every time a number has printed the control of execution is brought back to the condition of if statement by the goto statement. This process is continued till i<=n is true. In this way, an iteration is produced and we obtain our required output on the screen. 





No comments:

Post a Comment