Sunday, 24 August 2014

Unconditional statement

    Unconditional statements in C
1)      break
2)      goto
3)      continue

break:-  The break statement is used to terminate the execution of the nearest enclosing loop in which it appears. We have also used switch statement in which the use of break statement is must.
Syntax is very simple:-
                break;

example:

#include<stdio.h>
int main()
{
int a=0;
for(a=0;a<10;a++)
{

if(a==6)
{
break;
}
printf(“  %d”,a);
}
return 0;
}



Now the above code will print from 0 to 5 only. Because when “a” will be equal to 6 then the “if” condition is true and the break statement is executed and program will stop.





GOTO statement:- This statement is used to transfer control to a specific label, and label should be in the same program.
Syntax: goto label;

Here label can have any name.

How to declare label in a programè label can be any variable name that is followed by a colon (:). The label is immediately placed before the statement where the control has to be transferred.

There are two possibilities: 1)goto is located after the label.
                                                      2) label is located after the goto statement.





 Example with a program:
#include<stdio.h>
#include<conio.h>>
int main()
{
                int i=0;
               
               
                for(i=0;i<10;i++)
                {
                                if(1==6)
                                {
                                                goto label1;  // jumping to the label1 when condition is true
                                }
                                printf(" %d",i);
                }
               
                                label1:                                   // declaration of label1
                                for(i=7;i<12;i++)
                                {
                                                printf(" %d",i);
                                }
                                return 0;
                               
}



Continue :-

Continue is also used like break statement but the main difference is that it just skips the steps where break stops the program.
Let’s focus on the first example,
#include<stdio.h>
int main()
{
int a=0;
for(a=0;a<10;a++)
{

if(a==6)
{
break;
}
printf(“  %d”,a);
}
return 0;
}
 Here the output will be from 0 to 5 only.(after 5 program stops)

But when we use continue at the place of break the then we can understand better how continue works.

#include<stdio.h>
int main()
{
int a=0;
for(a=0;a<10;a++)
{

if(a==6)
{
continue;
}
printf(“  %d”,a);
}
return 0;
}





like us on facebook Programming infinitum

No comments:

Post a Comment