Looping statements in C #: While Loops and for loops (i)

Source: Internet
Author: User

if we want to do a lot of things, say we want to output hundreds of numbers, one output of the words not only cumbersome and time-consuming, inefficient. In this case, C # provides us with a much simpler way to output the loop. There are many types of loops, here I compare two loops: while loop &for Loop.

first of all , the while loop:

the format of the while loop is simple:

While(loop condition)

Loop Body

This means that when the logical value is "true", the loop body loops continuously until the logical value becomes "false" before it stops. If the logical value is always true, the loop does not stop, which is what we often call a "dead loop". For example:

While(true)

Console.Write (1);

is to continuously output the number 1. There is no value in such a cycle. If you want to rewrite this code, we do this:

Output of 1 by using the while loop method .

First we can set an integer type variable int i=10,

Int i=10;

while (i>0)

{

Console.Write (i);

I= i-1;

}

Console.ReadLine ();

Then this code is ready to write.

analysis, when executing this program,

first loop: Because the variable i=10 i>0 Yes i=i-1 i 9

second loop: Since the first loop was executed i=9 i>0, Yes i=i-1 i 8

when the loop executes to the 11th time, the variable i=0, does not satisfy the i>0 condition, so is false, then the loop terminates, so the program output Ten a 1 after the stop. This is much easier when you need to output a large number of numbers.

Looping statements in C #: While Loops and for loops (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.