Give a For-Loop example?
Answer:
Here is a complete example of a for-loop:
for (int i = 0; i <= 10; i++)
{
Console.Write(i + " ");
}
The result of its execution is the following:
0 1 2 3 4 5 6 7 8 9 10
Here is another, more complicated example of a for-loop, in which we have two variables i and sum, that initially have the value of 1, but we update them consecutively at each iteration of the loop:
for (int i = 1, sum = 1; i <= 128; i = i * 2, sum += i)
{
Console.WriteLine("i={0}, sum={1}", i, sum);
}
The result of this loop’s execution is the following:
i=1, sum=1
i=2, sum=3
i=4, sum=7
i=8, sum=15
i=16, sum=31
i=32, sum=63
i=64, sum=127
i=128, sum=255
for (int i = 0; i <= 10; i++)
{
Console.Write(i + " ");
}
The result of its execution is the following:
0 1 2 3 4 5 6 7 8 9 10
Here is another, more complicated example of a for-loop, in which we have two variables i and sum, that initially have the value of 1, but we update them consecutively at each iteration of the loop:
for (int i = 1, sum = 1; i <= 128; i = i * 2, sum += i)
{
Console.WriteLine("i={0}, sum={1}", i, sum);
}
The result of this loop’s execution is the following:
i=1, sum=1
i=2, sum=3
i=4, sum=7
i=8, sum=15
i=16, sum=31
i=32, sum=63
i=64, sum=127
i=128, sum=255
No comments:
Post a Comment