C++ Primer For Java Programmers


Loop Constructs

Logical Constructs Table of Contents Text Files

While Loops

While loops in C++ like those in Java can be used to create event- and count-controlled loops. The following function which sums a range of integers, illustrates a count-controlled loop in C++

int sumInts( int from, int to )
{
  int sum = 0;
  int i = from;
  while( i <= to ) {
    sum += i;
    i++;
  }
  return sum;
}
 

Event-controlled loops are typically used when extracting data from files and for user interaction. The following function illustrates the use of an event-controlled loop to extract and sum positive integer values from the user.

int sumUserValues()
{
  int sum = 0;
  int value;

    /* We must extract the first value before the loop. */
  scanf( "%d", &value );
  while( value > 0 ) {

      /* We use the extracted value. */
    sum += value;

      /* Extract the next value from the user. */
    scanf( "%d", &value );
  }

  return sum;
}
 

For Loops

Do-While Loops


Logical Constructs Table of Contents Text Files

Print - Changes - Search
Last modified: April 28, 2007, at 11:37 PM.