Friday 30 May 2014

for Loop in C

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A For loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a For loop statement :

Synatax:

for(initial expression; test expression; update expression) 
{ 
body of loop; 
}

Lets take an Simple Example:
#include<stdio.h>
int main()
{
        int i;
        for(i=0;i<=5;i++)
              printf("Hello World");
         return 0;
}

Output:
it will print five times Hello World
Explanation of For Loop :

1.Firstly the for loop executes the initialize statement in which the subscript variable will be initialized
with the initial value.

2.After the initialize statement the condition part of the loop will be executed if the condition becomes true then body of the loop will be executed otherwise the loop will be terminated

3.If the loop condition becomes true then body of the loop will be executed. After the execution of the for loop body the control goes to the third part of the loop statement i.e Expression Updation

4.After updating subscript variable control again goes to execute condition statement.



for more understanding the flow of loop plz go here....


Different ways of using For loop :

In order to do certain actions multiple times , we use loop control statements. For loop can be implemented in different verities of using for loop -

1. Single Statement inside For Loop
2. Multiple Statements inside For Loop
3.  No Statement inside For Loop
4.  Semicolon at the end of For Loop
5.  Multiple Initialization Statement  inside For Loop
6.  Missing Initialization in For Loop
7.  Missing Increment /Decrement  Statement
8.  Infinite For Loop
9.  Condition with no Conditional Operator.

Way 1 : Single Statement inside For Loop

for(i=0;i<5;i++)
     printf("Hello");
1. Above code snippet will print Hello word 5 times.
2. We have single statement inside for loop body.
3. No need to wrap printf inside opening and closing curly block.
4. Curly Block is Optional.

Way 2 : Multiple Statements inside For Loop
for(i=0;i<5;i++) 
{ 
        printf("Statement 1"); 
        printf("Statement 2"); 
        printf("Statement 3"); 
        if(condition)     
        {     
              --------     
              --------     
          } 
  }
If we have block of code that is to be executed multiple times then we can use curly braces to wrap multiple statement in for loop.

Way 3 : No Statement inside For Loop
for(i=0;i<5;i++) 
{   }
1.This is bodyless for loop. It is used to increment value of “i”.
2.This verity of for loop is not used generally.
3.At the end of above for loop value of i will be 5


Way 4 : Semicolon at the end of For Loop

for(i=0;i<5;i++);
1. Generally beginners thought that , we will get compile error if we write semicolon at the end of for loop.
2. This is perfectly legal statement in C Programming.
 3. This statement is similar to bodyless for loop. (Way 3)

Way 5 : Multiple Initialization Statement inside For
for(i=0,j=0;i<5;i++) 
{ 
       statement1; 
       statement2;  
       statement3; 

}
Multiple initialization statements must be seperated by Comma in for loop.


Way 6 : Missing Increment/Decrement Statement
for(i=0;i<5;) 
{ 
        statement1; 
        statement2; 
        statement3; 
         i++; 
}
however we have to explicitly alter the value i in the loop body.

Way 7 : Missing Initialization in For Loop
i = 0;
for(;i<5;i++) 
{ 
       statement1; 
       statement2;
       statement3;
 }
we have to set value of ‘i’ before entering in the loop otherwise it will take garbage value of ‘i’.

Way 8 : Infinite For Loop
i = 0;
for(;;) 
{ 
       statement1; 
       statement2; 
       statement3; 
       if(breaking condition)    
              break; 
        i++; 
}
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause overflow of stack.


Understanding of For loop

#include<stdio.h>
int main()
{
        int i;
        for(i=0;i<=5;i++)
              printf("Hello World");
         return 0;
}
Lets start with step by step and what will happen when condition is true:
Seq.No        Statement Flow                Explanation
01    Flow No 1 will be executed            i = 0
02    Flow No 2 will be executed            Condition Checking
03    Flow No 3 will be executed        True Condition and print Hello World
04    Flow No 4 will be executed              -
05    Flow No 5 will be executed            i = 1
06    Flow No 3 will be executed        True Condition and print Hello World
07    Flow No 4 will be executed              -
08    Flow No 5 will be executed            i = 2
09    Flow No 3 will be executed        True Condition and print Hello World
10    Flow No 4 will be executed              -
11    Flow No 5 will be executed            i = 3
12    Flow No 3 will be executed        True Condition and print Hello World
13    Flow No 4 will be executed              -
14    Flow No 5 will be executed            i = 4
15    Flow No 3 will be executed        True Condition and print Hello World
16    Flow No 4 will be executed              -
17    Flow No 5 will be executed            i = 5
18    Flow No 3 will be executed            False Condition

Therefore it gives five times Hello World . Ok Guys i think u will understand of whole scenario.

Return Statement In Java

Return statement

The return statement is used to explicitly return from a method.That is it transfer the control to the caller of method.
And most important , return statement is always be the last statement of the current block.

Simple Program for Return statement:

package org.modi;
public class Test
{
    public static void main(String[] args)
    {
       System.out.println("Main method begin");
       if(true)
       {
          return; //it is last statement of current (if) block
       }
       System.out.println("Main method end");
    }
}
OUTPUT
Main method begin
From this program we can see that , when return statement encountered the execution of method terminated.







Continue Statement In Java

Continue Statement

The continue statement is used to continue the execution of loop.
In while and do-while loops , a continue statement transfer control to the conditional expression that controls the loop.
In for loop , first control goes to the increment/decrements portion and the goes to the expression.

Simple Program for Continue Statement

package org.modi;
public class Test
{
   public static void main(String[] args) 
   {
      for(int i=0;i<10;i++)
      {
         System.out.print( i+" " );
         if(i%2==0)
            continue;
         System.out.println("");
      }
  }
}
OUTPUT
0 1 
2 3 
4 5 
6 7 
8 9 
From program we can see that when continue statement encountered then first the control goes to the increment/decrements and then goes to expression.

Break Statement in Java

Break Statement

In java , the break statement has three uses.
1. It terminates a statements sequence in switch statement.
2. It can be used to exit a loop.
3. It can be used as a "civilized" form of goto.

And last two uses are explained here.

2. Using the break to exit loop:

By break  , you can force to terminates the loop.When a break statement is encountered inside a loop , 
the loop is terminated and program control reeches to the next statement to the loop.The break statement can be used with any of the loop.

Simple program of Break statement:

package org.modi;
public class Test
{
  public static void main(String[] args)
  {
 int i=1;
 while(i<100)
 {
  if(i==5)
  {
   break; //terminates the loop while i become 5
  }
  System.out.println("i : "+i);
  i++;
 }
 System.out.println("After while loop");
 }
}
OUTPUT
i : 1
i : 2
i : 3
i : 4
After while loop
You can see in above program the while loop designed  to iterate from 1 to 99 ,
But the break statement terminate the loop while i reach to 5
When break statement  used inside a set of nested loops , it will only break out the innermost loop.

3. Using break as a goto form:

Java does not have a goto statement,so where goto is required java defines the expanded form of the break statement.
By using this form of the break statement you can break out one or more blocks of code.
This form of the break works with a label.

The general form of the labeled break statement is :

break label;
Here,label is the name of a label that identifies the block of the code.When this form of the break executes , control transferred 
to the named block.
To name a block , put label at the start of it.A label is valid java identifier followed by a colon (:) .

Simple program of break statement in from of goto:

package org.modi;
public class Test
{
   public static void main(String[] args)
   {
       one:
       {
          two:
         {
             three:
            {
              System.out.println("Block Three begin");
              if(true)
                  break two;  //control goes out of block two
              System.out.println("Block Three End");
           }
           System.out.println("Block Two");
        }
        System.out.println("Block one");
      }
   }
 
}
OUTPUT
Block Three begin
Block one

Do-While In Java

Do-While Loop

The do-while loop always executes its body at least once,because its conditional expression is at the bottom of the loop.It repeats the statement or block of code while its controlling expression is true.It can execute the statements at least one  or more times.

Syntax of the while loop:

do
{
   //statements
}while(condition);
Each iteration of the do-while loop first execute the body of the loop and then evaluates the conditional expression.If this expression is true, then loop will repeat otherwise the loop terminates.

Flow Chart Of do-while loop:

Simple program of the while loop:

package org.modi;
public class Test
{
    public static void main(String[] args)
    {
 int i=5;
 do
 {
  System.out.println("Count " + i );
  i--;
 }while(i>0)
   }
}
OUTPUT
Count 5
Count 4
Count 3
Count 2 
Count 1


While in Java

While Loop

The while loop is Java's most fundamental loop statement.It repeats the statement or block of code while its controlling expression is true.In while loop, condition is given before the statement.  It can execute the statements 0 or more times.

Syntax of the while loop:

while(condition)
{
   //statements
}

The condition can be any boolean expression.The body of the loop will be executed as long as the conditional expression is true.
When condition becomes false , control passes to the next line of code immediately following the loop.
If loop have only one statement then , curly braces are not necessary.

Flow Chart of the while loop:

Simple program of the while loop:

public class Test { public static void main(String[] args) { int i=5; while(i>0) { System.out.println("Count " + i ); i--; } } }
OUTPUT
Count 5 Count 4 Count 3 Count 2 Count 1

Some important points about while loop:


1.Since the while loop evaluates its conditional expression at the beginning the loop , the body of the loop        will not execute if condition is false at the beginning.
public class Test
{
 public static void main(String[] args)
 {
  int i=5 , j=10;
  while(i>j)
  {
   System.out.println("While loop body");
  }
  System.out.println("Out of While loop");
 }
}
OUTPUT
Out of While loop
2. The body of the while loop can be empty.This is because a null statement is syntactically valid in java.

public class Test
{
 public static void main(String[] args)
 {
  int i=5 , j=10;
  while(++i<--j)
  System.out.println(i);
 }
}
OUTPUT
8
3.If condition will always true then it will become infinite loop.
while(true) //infinite loop


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

if...else Statement in C

The if, if...else and nested if...else statement are used to make one-time decisions in C Programming, that is, to execute some code/s and ignore some code/s depending upon the test expression.

Simple  if statement

We often need to be able to choose which set of instructions are obeyed according to a condition. For example, if you're keeping a total(sum) and you need to display the message 'OK' if the value is greater than zero you would need to write something like:

if (total>O) printf("OK");

This is perfectly reasonable English, if somewhat terse, but it is also perfectly good C. The if statement allows you to evaluate a condition or expression and only carry out the statement, or compound statement, that follows if the condition or expression is true. In other words the printf will only be obeyed if the condition total> O is true.

Syntax:
The general form of a simple if statement is,
if( expression )
{
 statement-inside;
}
statement-outside ;

The if statement checks whether the 'expression' inside parenthesis ( ) is true or not. If the 'expression' is true, statement-inside the body of if statement is executed but if test is false, statement/s inside body of if is ignored and only 'statement-outside'  is executed. .
#include<stdio.h>
int main()
{
        int x=12;
        int y=5;
        if(x<y)
        {
                printf("x is less than y"); 
        }
       return 0; 
 }
Output: 
nothing will be printed becoz if statement gives false and it directly runs return 0.
if...else statement

The if...else statement is used if the programmer wants to execute some statement/s when the test condition or expression is true and execute some other statement/s if the test condition or expression is false.

This is another possibility is that you might want to select one of two possible statements - one to be obeyed when the condition is true and one to be obeyed when the condition is false. You can do this using the

if (condition) statement1;
else statement2;

 In this case statement1 is carried out if the condition is true and statement2 if the condition is false.

Syntax:
if( expression )
{
 statement-block1;
}
else
{
 statement-block2 ;
}

If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1' is skipped and
'statementblock2' is executed.

#include<stdio.h>
int main()
{
        int x=12;
        int y=5;
        if(x<y)
        {
                 printf("x is less than y"); 
        }
        else
        {
                 printf("x is greater than y"); 
        }
        return 0; 
 } 
Output: 
'x is greater than y' 


Nested if...else statement

The nested if...else statement is used when program requires more than one test expression.
if( expression )
{
        if( expression1 )
        {
            statement-block1;
        }
        else
        {
            statement-block 2;
        }
}
else
{
     statement-block 3;
}

The nested if...else statement has more than one 'expression'. If the first 'expression' is true, it executes the code inside the braces{ } just below it. But if the first 'expression' is false, it  else is executed and the control of program jumps below the nested if...else.
In above , if 'expression' is false the 'statement-block3' will be executed, otherwise it continues to perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-block1' is executed otherwise 'statement-block2' is executed.
The ANSI standard specifies that 15 levels of nesting may be continued.
#include< stdio.h> 
#include< conio.h> 
void main( ) { 
     int a,b,c; 
     clrscr(); 
     printf("enter 3 number"); 
     scanf("%d%d%d",&a,&b,&c); 
     if(a>b)
     { 
         if( a > c) 
         { 
             printf("a is greatest"); 
         } 
         else  
         { 
             printf("c is greatest"); 
         } 
     } 
     else 
     { 
         if( b> c) 
         { 
             printf("b is greatest"); 
         } 
         else 
         { 
            printf("c is greatest"); 
         } 
     } 
getch(); 
}

if-else ladder

The general form of else-if ladder is:

if(expression 1) 
{ 
     statement-block1; 
} 
else if(expression 2) 
{ 
     statement-block2; 
} 
else if(expression 3 ) 
{ 
     statement-block3; 
} 
else  
default-statement
The expression is tested from the top(of the ladder) downwards. As soon as the true condition is found, the statement associated with it is executed.

#include< stdio.h> 
#include< conio.h> 
void main( ) 
{ 
    int a; 
    printf("enter a number"); 
    scanf("%d",&a); 
    if( a%5==0 && a%8==0) 
    {  
         printf("divisible by both 5 and 8"); 
    }
    else if( a%8==0 ) 
    {  
        printf("divisible by 8"); 
    } 
    else if(a%5==0) 
    {  
        printf("divisible by 5"); 
    } 
    else  
    {  
        printf("divisible by none"); 
    } 
    getch(); 
}
Points to Remember

1. In if statement, a single statement can be included without enclosing it into curly braces { }
int a = 5; 
if(a > 4)  
printf("success");

No curly braces are required in the above case, but if we have more than one statement inside if condition, then we must enclose them inside curly braces.

2. == must be used for comparison in the expression of if condition, if you use = the expression will always return true, because it performs assignment not comparison.

3. Other than 0(zero), all other values are considered as true.
if(27) 
printf("hello");

In above example, hello will be printed.

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)

For Loop in Java

The for loop is used to iterate the statement or a part of the program several times.
There are two forms of the for loop in java.
1. Traditional for loop
2. For-each loop

1. Traditional For Loop
Syntax of the traditional for loop is:
for(initialization ; condition ; increment/decrements)
{
       //statements
}
When the loop first starts , the initialization portion of the loop is executed.It is important to know that the initialization statement is only executed once.Next , condition is evaluated.This must be a Boolean expression.It checks the  loop control variable against a target value.If this expression is true , then the body of loop is executed otherwise terminates the loop.Next, the increment/decrements portion executed which is increments or decrements the loop control variable.
After first pass the loop iterates , first evaluated the conditional statements ,then executing the body of loop and then executes the increments/decrements portion.This process repeats until the condition false.


Flow Chart Of  Traditional For Loop:


Simple program of traditional for loop:
package org.modi;
public class Test
{
	public static void main(String[] args)
	{
		for(int i=0;i<5;i++)
		{
			System.out.println("loop body " + i );
		}
	}
}
OUTPUT
loop body 0
loop body 1
loop body 2
loop body 3
loop body 4

2. For-each Loop
The for-each loop was introduce in JDK 5(1.5)  version of java.The for-each loop is also know as enhanced for loop.The for-each specially designed for iterate the collection of objects , such as an array.It iterate all the elements from starting element to last element.We can con control the number of iteration it iterate all the elements one by one.
Syntax of for-each loop:
for(type variable : collection)
{
   //statements
}
Here, type specifies the type (e.g. String , int ) and variable specifies the name of the iteration variable that will receive the elements form the collection , one at a time from begin to end.The collection is the collection of elements which will be iterated by the loop.
Simple program of the for-each loop:
package org.modi;
public class Test
{
   public static void main(String[] args)
   {
	int[] arr={0,1,3,4};
	for(int itr : arr)
	{
	   System.out.println("loop body " + itr);
	}
    }
}
OUTPUT
loop body 0
loop body 1
loop body 3
loop body 4

Some Important points:
1. If for loop body contains only one statement then , no need for curly braces.
E.g.
for(int i=0 ; i< 5 ; i++)
      System.out.println("Hello World!");
2. If we declare a variable inside for loop , then the scope of the variable ends with ends of for loop.
3. To create infinite loop leave all the parts of for loop empty.
E.g.
for(  ;   ;  )

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");