Tuesday, July 28, 2009

Need Help with a simple C# loop (For loop)?

I can't understand how do you get : 5050 with tis loop.


Can somebody explain that to me into details? Thanks





using System;





class Use_byte {


public static void Main() {


byte x;


int sum;





sum = 0;


for(x = 1; x %26lt;= 100; x++)


sum = sum + x;





Console.WriteLine("Summation of 100 is " + sum);


}


}





The output from the program is shown here:





Summation of 100 is 5050

Need Help with a simple C# loop (For loop)?
well lets walk through the first few iterations and you should get the idea .......





when we start x = 1 and sum is 0





so the first time through the loop we get





sum (0) = sum (0) + x(1) which make sum 1





the next time through the loop we get





sum (1) = sum (1) + x (2) which makes sum 3





the next time we get





sum(3) = sum(3) + x(3) which makes sum 6





now lets jump to (oh lets say 98 (x is now 98))





so what we get is





sum(4851) = sum(4851) + x(99) which make sum 4950





so te next time through the loop we get





4950 + 100 (x is now 100) which equals 5050





in a nutshell what the program does





is take x and add 1,2,3,4,5,6 .......100 to the previous sum of x





x = 1


sum = 0





0 + 1 = 1


1 + 2 = 3


3 + 3 = 6


6 + 4 = 10


10 + 5 = 15


15 + 6 = 21


21 + 7 = 28





etc


etc


etc





4950 + 100 = 5050





see the pattern? the first column is the sum the second column is x and the third column is the new sum after adding x to it





doug
Reply:First, sum is initialized to 0. This is used as a buffer.





The loop runs from 1 to 100. And notice that the for loop does not have a nested brackets. It means only "sum = sum + x" will be repeated. So it goes like...





x=1;


sum = sum + x;


x=2;


sum = sum + x;


x=3;


sum = sum + x;


......


x = 100;


sum = sum + x;





After the loop runs from 1 to 100, the for llop quits and write the sum on the console.


No comments:

Post a Comment