954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

WHILE Loop vs. FOR Loop

I know a FOR loop is for definite loops when you know the starting value and ending value. It use step value (number use to alter a loop control variable on each past of the loop) in which the control value changes after the body executes. A for statement is never required for any loop; it is more efficient and less room for errors.

I can see the difference in writing out a for loop in pseudocode, but what is the difference when writing a for loop in flowchart form?

Dani

daniel1977
Newbie Poster
18 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

How about...

for (int n=1; n<5; n++) {
    do something
  }

   .-----.
  | Start |
   '-----'
      |
      V
  +-------+
  | n = 1 |
  +-------+
      |<---------------------------------------------+
      V                                              |
     ' '                                             |
   /     \           +--------------+   +---------+  |
  '  n<5? ' --yes--> | do something |-->| n = n+1 |--+
   \     /           +--------------+   +---------+
     ' '
      | no
      V
   .------.
  |  Done  |
   '------'


  n=1
  while (n<5) {
    do something
    n += 1
  }

   .-----.
  | Start |
   '-----'
      |
      V
  +-------+
  | n = 1 |
  +-------+
      |<---------------------------------------------+
      V                                              |
     ' '                                             |
   /     \           +--------------+   +---------+  |
  '  n<5? ' --yes--> | do something |-->| n = n+1 |--+
   \     /           +--------------+   +---------+
     ' '
      | no
      V
   .------.
  |  Done  |
   '------'

In flow chart, they are very similar (or the same if you want to). In coding, they are different because you need to control your loop. But remember that while can also be do-while too.

Taywin
Posting Virtuoso
1,727 posts since Apr 2010
Reputation Points: 229
Solved Threads: 239
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You