1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

For Loops [basic]

Discussion in 'C' started by k3y, Mar 9, 2012.

  1. k3y

    k3y New Member

    Mar 9, 2012
    Likes Received:
    Trophy Points:
    Hey guys,
    I just learned the basics of FOR loops and felt maybe I should share for fellow n00bs out there. A FOR loop can in many cases replace a WHILE loop. This tutorial will show you the relationship between the WHILE loop and the FOR loop, as well as an exercise that I found to be very helpful in learning how to utilize them.
    Syntax of a WHILE loop:

    i = 1; // initializer
    while (i <= 10) // condition
        cout << i << " "; 
        i++; // increment
    Now in a FOR loop

    Syntax of a FOR loop:
    for (i=1; i <= 10; i++) //initializer; condition; increment
       cout << i << " ";   
    Now as you can see the FOR loop is much more condensed then the WHILE loop, and saves some headache. Now it's time for an example code (test a number for primeness):
    #include <iostream>
    #include <math.h>
    using namespace std;
    int main()
        int n;
        bool is_prime = true; // boolean (assumes true)
        cout << "Enter a number and press ENTER: ";
        cin >> n;
        for (int i = 2; i <= sqrt(n); i++) 
            if (n % i == 0) // if the remainder of n divided by i is zero
            is_prime = false; // then n is not prime
    // Print result
        if (is_prime)
            cout << "Number is prime." << endl;
            cout << "Number is not prime." << endl;
        return 0;
    Here are a few good exercises to get yourself familiar with WHILE and FOR.
    - optimize this program
    - find the correct place to put a break statement
    - make the same program using a WHILE loop

    Hope this can help someone
    shabbir likes this.

Share This Page