next up previous
Next: Activity Up: Overview of C++ Previous: break Statement

Nested Loops

Nested loops are used to solve a wide variety of programming problems. For example, the following program uses a nested for loop to find the prime numbers from 2 to 1000. One way to determine whether a number is a prime is to successively divide it by the numbers between 2 and the number one half its value. You can stop at the halfway point because a number that is larger than one-half of another number cannot be a factor. If any division is even the number is not prime, however if the loop completes the number is a prime.

Example

/* This program finds the prime numbers from 2 to 1000 */
#include <iostream.h>
main()
{
int i,j;
for(i=2;i<1000;i++){
for(j=2;j<=i/2;j++)
if(!(i%j)) break;// if factor found not prime
if(j>i/2) cout << i << " is prime $\backslash$n";
}
return 0;
}



Yousef Haik
2/23/1998