Showing posts with label control statement. Show all posts
Showing posts with label control statement. Show all posts

Thursday, 29 May 2014

Break And Continue in C

Break:
The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. When the break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop. The break statement can be used with all three of C's loops for, while and do...while loops.
Syntax:
break;

The figure below explains the working of break statement in all three type of loops.


Here's an example of a use for the break statement:
#include
int main()
{
 int t ;
 for ( ; ; ) 
 {
  scanf("Enter any no.\n%d" , &t) ;
  if ( t==10 ) 
                break ;
 }
 printf("End of an infinite loop...\n");
 return 0;
 }
Output:
Enter any no.
2
3
10
End of an infinite loop...
In above example, it takes no. until user enter 10 because t=10 then it will break.

Continue:
The continue statement is somewhat the opposite of the break statement. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. In while and do-while loops, a continue statement will cause control to go directly to the test condition and then continue the looping process. In the case of the for loop, the increment part of the loop continues. One good use of continue is to restart a statement sequence when an error occurs.

Syntax:
continue; 

Here's an example of a use for the break statement:

#include
int main()
{
 int x ;
 for ( x=0 ; x<=100 ; x++) 
 {
  if (x%2) continue;
  printf("%d\n" , x);
 }
}

Goto Statement in C

10:53 Posted by Hindustan News , , No comments
In C programming, goto statement is used for altering the normal sequence of program execution by transferring control to some other part of the program.
Syntax:
goto label;
.............
.............
.............
label: 
statement;
}
 When, the control of program reaches to goto statement, the control of the program will jump to the label: and executes the code below it.


#include
#include
void main(){
    int a;
    goto label;
    a = 10;
    printf(“%d”, a);
    label:
    a = 20;
    printf(“%d”, a);
}
Output:
20

When goto label in C is encountered, control goes to the statement next to the label. Here, label is not the keyword. We can use any name for the label. It’s user defined.
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced as much as possible in a program.

Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto statement makes the logic of the program complex and tangled. In modern programming, goto statement is considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue statements. In fact, any program in C programming can be perfectly written without the use of goto statement. All programmer should try to avoid goto statement as possible as they can.

Switch-Case Statement in C

While if is good for choosing between two alternatives, it quickly becomes typical when several alternatives are needed. C's solution to this problem is the switch statement. The switch statement is C's multiple selection statement. It is used to select one of several alternative paths in program execution and works like this: A variable is successively tested against a list of integer or character constants. When a match is found, the statement sequence associated with the match is executed. The general form of the switch statement is:
Syntax:
switch(expression)
{
 case constant1: statement sequence; break;
 case constant2: statement sequence; break;
 case constant3: statement sequence; break;
 .
 .
 .
 default: statement sequence; break;
}

Expression is always a constant(or integer-valued constants). If expression is character then it will take as ascii value of that character. Each case is labelled by one, or more, constant expressions (or integer-valued constants). The default statement sequence is performed if no matches are found. The default is optional. If all matches fail and default is absent, no action takes place. When a match is found, the statement sequence associated with that case are executed until break is encountered. An example program follows:
#include
int main()
{
 int i;
 printf("Enter a number between 1 and 4");
 scanf("%d",&i);
 switch (i)
 {
  case 1:
   printf("one");
   break;
  case 2:
   printf("two");
   break;
  case 3:
   printf("three");
   break;
  case 4:
   printf("four");
   break;
  default:
   printf("unrecognized number");
} /* end of switch */ 
Output:
Enter a number between 1 and 4:
2
two
This simple program recognizes the numbers 1 to 4 and prints the name of the one you enter. The switch statement differs from if, in that switch can only test for equality, whereas the if conditional expression can be of any type. Also switch will work with only int and char types. You cannot for example, use floating-point numbers. If the statement sequence includes more than one statement they will have to be enclosed with {} to form a compound statement.

The break statement at the end of each case cause switch statement to exit. If break statement is not used, all statements below that case statement are also executed. In above example ,in case 2 break statement is not there then output will be : two three  , because in case 3 ,break statement is there then it will be break after printing the three.
Output:
Enter a number between 1 and 4:
2
twothree

Do-While Loop in C

While loops causes program to execute the certain block of code repeatedly until some conditions are satisfied, i.e., loops are used in performing repetitive work in programming.
Suppose you want to execute some code/s 10 times. You can perform it by writing that code/s only one time and repeat the execution 10 times using loop.
There are 3 types of while loops in C programming:
  1. while loop
  2. do...while loop
  3. infinite while loop.

1.WHILE LOOP:
               The ‘while’ loop allows execution of statements inside block of loop only if condition in loop succeeds.
Syntax:
            initialization
            while(condition)
            {
                   ..........
                   ..........
                   .......... 
                   condition change statement;
            }
In the pseudo code above :
  • Variable initialization is the initialization of counter of loop before start of ‘while’ loop
  • Condition is any logical condition that controls the number of times execution of loop statements
  • Condition Change statement is the increment/decrement of counter or which change the condition.


Ex:

#include<stdio.h>
#include<conio.h>
int main()
{
          int i;
          i=10;
          while(i)
          {
                  printf("Value of i :%d", i);
                  i++;
          }          return 0;
}

2. do...while loop:
It is another loop like ‘for’ loop in C. But do-while loop allows execution of statements inside block of loop for one time for sure even if condition in loop fails.

Syntax:
           initialization
            do
            {
                   Statement Block
                   ..........
                   .......... 
                   condition change statement;
            }while(condition)


Example:
#include
int main() 
{
   int j = -5;
   do
   {          
       printf("%d\n",j);           
       j = j + 1;     
   }while(j <= 0);        
   return 0;  
} 

Infinite While Loop:

 We can use infinite while loop in C to iterate loop for infinite times. We can Even use Infinite while loop for operation in which we cannot decide how many iteration does it take at compile time. There are many ways we declare infinite while loop:

Way 1 : Semicolon at the end of While
#include<stdio.h>

 void main()

{

        int num=300;

        while(num>255);  //Note it Carefully

        printf("Hello");

} 
Output:
It won't Print anything

Semicolon at the end of while indicated while without body. In the program variable num doesn’t get incremented , condition remains true forever. As Above program does not have Loop body , It won’t print anything.

Way 2 : Non-Zero Number as a Parameter

#include
void main()
{
        while(1)
        printf("Hello");
}
Output:
 Infinite Time "Hello" word 
Non Zero is specified in the While Loop means Loop will have always TRUE condition specified inside. As condition inside loop doesn’t  get changed, condition inside while remains true forever.

Way 3 : Subscript Variable Remains the same:
#include
void main()
{
      int num=20; 
      while(num>10)      
      {     
           printf("Hello");      
           printf(" C ");
      }
}
Output:
Infinite Time "Hello C" word

Way 4 : Character as a Parameter in While  Loop:

#include<stdio.h>
void main()
{
        while('A')
        printf("Hello");
}
Output:
Infinite Time "Hello" word
Explanation:
       Character is Represented in integer in the form of ASCII internally.Any Character is Converted into Non-zero Integer ASCII value Any Non-zero ASCII value is TRUE condition , that is why Loop executes forever

Decision Making In C

Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met. C language handles decision-making by supporting the following statements,

This also we known as control statement.It is also divided into following category:
1. Selection statements.(if..else and switch-case statement)
2. Iteration or looping statements.(for loop and do-while loop)
3. Jump statements.(break, continue and goto statement)

Tuesday, 27 May 2014

Switch In Java

The switch statement in  Java is used to execute the code from multiple conditions. It provides an easy way to dispatch execution to different parts of code based on the value of expression.It is a better alternative than a large series of if-else-if statements.

The syntax of switch statement :

switch(expression)
{
      case value1:
              //statements
        break;
     case value2:
              //statements
        break;
       .
       .
       .
       .
    case valueN:
              //statements
        break;
    default:
        //default statement
}
Flow Chart of switch Statement:



Rules for switch statement in Java language

1.  The switch expression must be of  byte,short,int or char type.
2.  The case value must be of type compatible with the expression.
3. Each case value must be a unique literal (means it must be a constant , not a variable).
4. Duplicate case values are not allowed.

How switch statement works ?
The value of the expression is compared with each of the literal values in the case statement.If match is found ,the code sequence following that case statement is executed.If none of the constants matches the value of the expression then the default statement is executed.Default statement is optional.
The break statement inside the switch is used for terminate a statement sequence.When a break statement is encountered , the execution comes out of the switch block to first line after the switch block.
If we are not keeping the break statement then , if  any case matched then all the case after that case will execute.

Simple Switch statement program

package org.modi;
import java.util.Scanner;
public class Test
{
public static void main(String[] args) 
{
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter your choice");
i=sc.nextInt();
switch(i)
{
case 0:
System.out.println("This is 0");
break;
case 1:
System.out.println("This is 1");
break;
case 2:
System.out.println("This is 2");
break;
case 3:
System.out.println("This is 3");
break;
case 4:
System.out.println("This is 4");
break;
default:
System.out.println("Default statement");
}
}
}
OUTPUT

Enter your choice                  //1st time execution
1
This is 1
Enter your choice              //2nd time execution
8
Default statement

Switch statement without break statement:
package org.modi;
import java.util.Scanner;
public class Test
{
 public static void main(String[] args) 
 {
  int i;
  Scanner sc=new Scanner(System.in);
  System.out.println("Enter your choice");
  i=sc.nextInt();
  switch(i)
  {
   case 0:
    System.out.println("This is 0");
   
   case 1:
    System.out.println("This is 1");
    
   case 2:
    System.out.println("This is 2");
    
   case 3:
    System.out.println("This is 3");
    break;
   case 4:
    System.out.println("This is 4");
    break;
   default:
    System.out.println("Default statement");
  
  }
  
 }
}

OUTPUT
Enter your choice
0
This is 0
This is 1
This is 2
This is 3


Friday, 23 May 2014

Java Control Statements

In this post we are going to discuss the control statements.
The control statements are used to control the flow of execution of the program.
Different type of control statements are:
1. Selection statements.
2. Iteration or looping statements.
3. Jump statements.

1.Selection statements:
 Java supports two selection statements if and switch. These  statements allows you to control the flow of your program's execution based upon conditions known only during run time.
For details information on control statements click on below links.

1. If
2. Switch

2. Iteration or Looping statements:
Java supports three Iteration or Looping statements for , while and do while.It executes a block of code or statements till the given condition is true. 
For details information on Iteration or Looping statements click on below links.

1. For loop
2. While loop
3. Do-While loop

3. Jump statements:
Java supports three Jump statements break , continue and return .These statements transfer control to another part of your program.
For details information on Jump statements click on below links.

1. break 
2. continue
3. return

If-else control statement

If is a selection statement which allows you to control the flow of  program's execution based upon condition known only during run time.

If
The if statement is java's conditional statement.It is used to perform task depending on whether the given condition is true or false.
Syntax
if(condition)
{
      //if block code
       statements
}
Here , If condition is true then statements inside block executed otherwise these statements skipped.

Flow chart of If





Let's see simple program of if statement
package org.modi;
public class Ifstatement
{
public static void main(String[] args )
{
int i=10;
if(i ==10)
{
System.out.println("This is if statement");
}
}
}

OUTPUT

This is if statement

If...else statement
If the condition is true then if block execute.Otherwise else block is execute.

Syntax
if(condition)
{
           //if block
}
else
{
          //else block
}
Here, if condition is true then if block executed otherwise else block executed.
Flow chart of If..else


Let's see simple program of if..else statement

package org.modi;
public class Test
{
public static void main(String[] args )
       {
          int i=10;
          if(i >10)
          {
              System.out.println("This is if statement");
          }
          else
          {
              System.out.println("This is else statement");
          }
       }
}
OUTPUT
This ia else statement

If the value of i is 10 then if block executed and it will print This is if statement.If values of  i other than 10 then else block executed and it prints This is else statement

Nested if...else
a nested if is an if statement within if or else statement.when we require to check more than one condition then we can use nested if..else.

Syntax
Form-1
if(condition 1)
      statement 1;
      if(condition 2)
        statement 2;
Form-2
if(condition 1)
     statement 1 ;
else
    else-statement;
    if(condition 2)
       statement 2;
Let's see simple program of  nested if..else statement

Form-1
package org.modi;
public class Test
{
public static void main(String[] args) 
{
int i=62;
if(i>18)
{
System.out.println("You are eligible for voting");
if(i>60)
{
System.out.println("You are Senoir citizen");
}
}
else
{
System.out.println("You are not eligible for voting");
}
}
}

OUTPUT
You are eligible for voting
You are Senoir citizen

Form-2
package org.modi;
public class Test
{
public static void main(String[] args) 
{
int temp=-2;
if(temp>10)
{
System.out.println("Hot day");
}
else
{
System.out.println("cool day");
if(temp<0 p="">
{
System.out.println("Water become ice");
}
}
}
}

OUTPUT
cool day
Water become ice

The If-else-if Ladder
Syntax
if(condition1)
    statement1;
else if(condition2)
   statement2;
else if(condition3)
   statement3;
.
.
.
.
else
    else statement;

Here,If condition 1 is true then statement 1 is executed.If condition 1 is false then condition 2 is tested.If condition 2 is true then statement 2 is executed,otherwise condition 3 is tested.If any conditions false then else statement executed. 

package org.modi;
public class IfLadder
{
public static void main(String[] args)
{
int i=85;
if(i>=90)
{
System.out.println("A Grade");
}
else if(i>=80)
{
System.out.println("B Grade");
}
else if(i>=70)
{
System.out.println("C Grade");
}
else if(i>=60)
{
System.out.println("D Grade");
}
else 
{
System.out.println("F Grade");
}
}

OUTPUT
B Grade

Important point:
1.If if block contains only one statement then it can be included without enclosing in curly brackets. 
2. == must be used for comparison in expression of condition.If we use = then it always return true because it's used for assignment not for comparison. 
E.g

int a=10;
if(a==10)
   System.out.println("a is equal to 10");