Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Why does this for loop gets executed 100 times?

I'm creating a for loop here.

for (int i = 100; i > 0; i--) {
   Console.WriteLine(i);
}

Why does this gets printed 100 times? 1 is the last comparison number in this for loop, thus 1 > 0 which is true. From here 0 > 0 is false right? So it should print 99 times am I right?

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Kevin Narain! Yes, it gets printed 100 times. I think you're subtracting 1 from 100 and getting 99. Once it gets down to 0 it stops printing. But between 100 and 1 there are 99 numbers. But that doesn't include the 1.

For example, if counting on your fingers from 1 to 10 there is a difference of 9. But because both 1 and 10 are included in the count, there are ten fingers held up :smiley:

In this case, we're counting down from 100 to 1 and all of those get printed. That includes both the 100 and the 1.

Hope this helps! :sparkles:

Hi Jennifer Nordell, thanks for your swift response I finally get it now!