Looping control structures in C Language:
Though goto can be used as a looping structure, it is
discouraged of using in C language.
The goto makes the program unreliable, unreadable and hard
to debug.
C provides three dedicated iterative control structures to
build the iterations.
1. do-while ( Exit controlled ).
2. while ( Entry controlled )
3. for (Entry controlled).
do-while iterative control structure:
It is an exit controlled iterative control structure.
The condition is checked while coming out of the loop.
The body of loop executes repeatedly until the condition is
false.
It is only the iterative control structure terminated with a
semicolon.
Specification1:
Print the
natural numbers from 10 to 15.
Program:
#include<stdio.h>
void main()
{
int x;
In case
of goto x=10; nice: printf("\n%d",x); x=x+1; if(x<=15) goto nice;
x=10;
do{
printf("\n%d",x);
x=x+1;
}while(x<=15);
}
Output:
10
11
12
13
14
15
Specification2:
Print the
natural numbers 1 to n
Program:
#include<stdio.h>
void main()
{
int i,n;
In case
of goto i=1; xyz: printf("%10d",i); i=i+1; if(i<=n) goto xyz;
printf("Enter
the limit:");
scanf("%d",&n);
i=1;
do{
printf("%10d",i);
i=i+1;
}while(i<=n);
}
Execution1:
Enter the
limit: 5
1 2 3 4 5
Execution2:
Enter the limit: 3
1 2 3
Specification3:
Print the natural number from n to 1 that is reverse order.
Program:
#include<stdio.h>
void main()
{
int n,i;
printf("Enter the limit:");
scanf("%d",&n);
In case
of goto i=n; xyz: printf("%10d",i); i=i-1; if(i>=1) goto xyz;
i=n;
do{
printf("%10d",i);
i=i-1;
}while(i>=1);
}
Execution:
Enter the limit: 5
5 4 3 2 1
0 comments:
Post a Comment