Thursday, May 31, 2012

Jumping Statments / UnConditional Control Structures



In C Language we have Unconditional Control Structures:
  • break
  • continue
  • goto
  • exit()
break: it is used to break the flow of the program at a particular condition.
Example for break keyword:
#include<stdio.h>
main()
{
    int i;
   printf("\n A Good Example for Break: ");
   for(i=1;i<=10;i++)
   {
              if(i==5)
                    break;
              printf("\t%d",i);
   }
}
Output: A Good Example for Break:           1            2              3              4               5
continue: it used to skip the iteration in the loops for a particular condition.

Example for continue keyword:
#include<stdio.h>
main()
{
    int i;
   printf("\n A Good Example for Break: ");
   for(i=1;i<=10;i++)
   {
             printf("\t%d",i);
              if(i==5)
              {
              printf("\n Loop is continued ");
              continue;
              }
              
   }
}
Output: A Good Example for Continue:           1            2              3              4            Loop is continued              6                7            8               9                   10
exit(): it is used to terminate the program and it is a function.

Example for exit():
#include<stdio.h>
main()
{
    int i;
   printf("\n A Good Example for exit(): ");
   for(i=1;i<=10;i++)
   {
              if(i==5)
             {  
                    printf("\n Program is terminated");
                    getch(); 
                    exit();
              } 
              printf("\t%d",i);
   }
}
Output: A Good Example for exit() :           1            2              3              4  
                                                                        Program is terminated
goto: it is used to execute the particular statement continuously when condition is given.
Write a program accept a number and display the numbers from 1 to n with out using loops

#include<stdio.h>
main()
{
    int i,n;
    printf("Enter a Number: \n");
    scanf("%d",&n);
     i=1;
     hai:
         printf("\t %d",i++);
     if(i<=n)
          goto hai;            
   }
}
Output: Enter a Number: 5
             1             2               3             4                  5

No comments:

Post a Comment