Yorkville High School Computer Science Department
Yorkville High School Computer Science Department on Facebook  Yorkville High School Computer Science Department Twitter Feed  Yorkville High School Computer Science Department on Instagram

Yorkville High School Computer Science

ASSIGNMENTS: No Current Assignments

Computer Programming I :: Lessons :: While Loops

While Loops

Try clapping your hands 5 times. Did you stop after you reached 5? How did you know when to stop? What you did is count each time you clapped and you stopped once the count reached 5. This is how loops work in a programming language. Loops do the same thing over and over again until a certain condition is met.

  1. Create a new project called "Loops"
  2. Create a button on the form and call it "btnLoop"
  3. Change the Text Property to "While Loop"
  4. Double-click the button and add the following code:
int clap = 1;
while (clap <= 5)
{
    MessageBox.Show(clap.ToString());
    clap = clap + 1;
}

The code above will run 5 times, and you can see the value of clap below at the beginning of each loop.

Loop 1: clap = 1, MessageBox: 1
Loop 2: clap = 2, MessageBox: 2
Loop 3: clap = 3, MessageBox: 3
Loop 4: clap = 4, MessageBox: 4
Loop 5: clap = 5, MessageBox: 5
Loop 6: clap = 6, Loop does not run because 6 is not less or equal to 5

Yorkville High School Computer Science Department on Facebook Yorkville High School Computer Science Department Twitter Feed Yorkville High School Computer Science Department on Instagram