Tuesday, 10 July 2012

Sixth Class ( Looping )

Sixth Class Material (Types of Looping concept)

There are four types of loops
1. for
2.while
3.do while
4.for each

1. for Loop


In for loop we declare three thing under for loop parameter
1. intialization
2.Termination or condition (always use comparison operator)
3.Increament or Decreament
Always have body for this loop

Like this

for(int a=0;  a<=10;  a++)
{
}

A simple program to use this loop.

Example 1.


using System;
class Loop
{
public static void Main()
{
for(int a=0; a<=100; a++)
{
Console.WriteLine(a);
}
}
}
Output : 0 to 100 no will be display

Example 2.


using System;
class Loop
{
public static void Main()
{
for(int a=2; a>=100; a++)
{
Console.WriteLine(a);
}
}
}
Output : Nothing will be display....body will be close bcaz 2 is less than 100 and cant excute under for loop body.

Example 3.


using System;
class Loop
{
public static void Main()
{
for(int a=2; a>=1; a++)
{
Console.WriteLine(a);
}
}
}
output : 0 to infinite to stop this excution on run time type ctrl+c

Example 4.

Make a simple table. Here we have to give a no for table and generate a table.


using System;
class Loop
{
public static void Main()
{
int b=1;
Console.Write("Enter any no to get Table : ");
b=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Table of  "+b+" is : ");
for(int a=1; a<=10; a++)
{
int c=a*b;
Console.WriteLine(c);
}
}
}


Mystery about for loop


Example 1.



using System;
class Loop
{
public static void Main()
{


for(int i=0;i<10;i++);
Console.WriteLine(i);
}
}
Here output is error


Example 2.



using System;
class Loop
{
public static void Main()
{
int i;
for(i=0;i<10;i++);
Console.WriteLine(i);
}
}
output is 10

2. While loop


In while loop our for loop confusion remove and know our looping process in a good way.
Because there we dont know when our increament occur. increament doessn`t occur in a first time iteration.
thats occur from second time.
We will learn here in a good way what`s happening.

Using System
class Loop
{
public static void Main()
{
int i=0;
while(i<=5)
{
Console.WriteLine(i);
i++;
}
}
}
Output : 0 to 5

In this program we can know when intializing variable when terminating and also about increasing.

3. do while

do while loop is same as a do loop but differ is that
in while loop if condition is true than while body will be excute and if false than while body will be terminate but in do while loop 1 statement will be must display wheather statement is true or false.
always


using System;
class Loop
{
public static void Main()
{
int i=0;
do
{
Console.WriteLine(i);
i++;
}
while(i<10);
}
}
Output : 0 to 9

No comments:

Post a Comment