Showing posts with label for. Show all posts
Showing posts with label for. Show all posts

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.

Thursday, 29 May 2014

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

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