Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   For Loops [basic] (http://www.go4expert.com/forums/for-loops-basic-t27989/)

k3y 10Mar2012 01:24

For Loops [basic]
 
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:

Code:

i = 1; // initializer
while (i <= 10) // condition
{
    cout << i << " ";
    i++; // increment
}

Now in a FOR loop

Syntax of a FOR loop:
Code:

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):
Code:

#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;
    }
    else
    {
        cout << "Number is not prime." << endl;
    }
    return 0;
}

Here are a few good exercises to get yourself familiar with WHILE and FOR.
Exercises:
- 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


All times are GMT +5.5. The time now is 13:33.