I’m Learning C# – Part 4

Today we will be learning about loops. What does a loop do? Suppose we want to add the number 2 to 10, 4 times. So instead of writing 10+2+2+2+2 we go in for a loop where we show the action once and indicate that it has to be repeated.

While loop

Now here is a code which uses the while loop. It will keep on asking to “enter the number” until you enter the value 10 at which the while loop will exist. Only if the condition while(True) does the loop get executed.

static void Main (string [] args)
{
int x = 0;
while (x != 10)
{
Console.WriteLine(“enter the number”);
x = Convert.ToInt32(Console.ReadLine());
}
}

Another loop is the do – while. It’s working is similar to while loop with one difference. The loop will be entered atleast once before the while(True) check is carried out.

static void Main(string[] args)
{
int x = 0;
do
{
Console.WriteLine(“enter the number”);
x = Convert.ToInt32(Console.ReadLine());
} while (x != 10);
}

The same code above is implemented using a for loop below:

static void Main (string [] args)
{
int x = 0;
for (;x!=10;)
{
Console.WriteLine(“enter the number”);
x = Convert.ToInt32(Console.ReadLine());
}
}

Basically a for loop will constitute of 3 parts – initialization, condition and then the increment.

Let’s write a code which will print the fibonacci series

static void Main(string[] args)
{

Console.WriteLine(“enter the number of Fibonacci numbers required”);
int x = Convert.ToInt32(Console.ReadLine());
if (x == 0) Console.WriteLine(“no numbers are printed”);
else if (x == 1) Console.WriteLine(“The number is 0”);
else if (x == 2) Console.WriteLine(“The numbers are 0 1 “);
else if (x == 3) Console.Write(“The numbers are 0 1 1 “);
else
{
int y = 1;
int z = 1;
int sum = 0;
Console.Write(“The numbers are 0 1 1 “);
for (; x > 3; x -= 1)
{
sum = y + z;
Console.Write(” {0} “, sum);
z = y;
y = sum;

}
}
}

We have skipped the initialization part in this code because we already have the value of x from the console.

We can skip initialization and the increment part but the following is an infinite loop.

static void Main(string[] args)
{
for (;;);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s