C# - Lesson 4 - Iterations

View previous topic View next topic Go down

C# - Lesson 4 - Iterations

Post  Guest on Wed Nov 18, 2009 2:10 pm

Iterations or Loops are used to let some code execute over and over again.
We can use it for example, if we want to let code execute untill a certain value is reached.

For example, we are going to make a small program that gives us the value of an integer after executing the code 10 times in a row.

> example: loop to 10

Code:
private void button1_Click(object sender, EventArgs e)
        {
            int answ = 1;
         
          for (int i=1; i<11;i++)
          {
              answ = answ * 2;
          }

          MessageBox.Show(answ.ToString());
        }

So, the void is a button click, you know that if you push the button the code will execute.

First we declared the variable "answ", that is an integer. Then we put up the loop.
This is a bit more complicated.

for (int i = 1; i < 11; i++)
{
}

The "int i" declares the "i" variable immediately in the iteration. The i is used to set an end value, and a limit.
"i = 1" means that if the code gets executed, the value on the first round will be set to 1.
"i < 11" means that the code will executed up to 10 times and stops before 11 is reached.
"i++" is the update expression. You don't need to worry about that one.

Note: You can use any other variable instead of "i", but i is just the most common used one.

So, if we look at our code again, we see "answ = answ * 2".
That means that the first time we run the code, the answ variable goes from 1 to 1*2 (=2).
As we set the loop to 10 loops we will get: 1*2*2*2*2*2*2*2*2*2*2 = 2^10 = 1024
The answer (1024) will be shown in the messagebox that pops up. (see end of the code)



That was it for this time.

___________

Next lesson : We actually gonna do some real stuff, no abstract things anymore...

Guest
Guest


Back to top Go down

View previous topic View next topic Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum