Sunday, June 26, 2011

How Use Loops in C-'While' Loops

0 comments


WHILE loops are very simple and the syntax is:
while(condition)
{
Code to execute while the condition is true
}
 The true represent a boolean expression which could be while(x==1) or while(x!=7),x does not equal to 7.It can be any combination of boolean statements that are legal.Even, while(x==5||y==7) which says execute the code while x equal to 5 or y equal to 7.


Example:


To print numbers up to 10:
#include<stdio.h>
int main()
{
int x=0;  /*Don't forget to declare variables*/
while(x<10) /*while x less than 10*/
{
printf("%d",x);
x++; /*Update x so the condition can be met eventually */
}
getchar();
}
This was another example ,but it is longer than FOR loop.The easiest way to think of the loop is that when it reach the brace at the end it jumps back up to the beginning of the loop,which check the condition again and decides whether to repeat the block another time,or stop and move to the next statement after the block.


More example using 'while' loop


<<Prev Home Next>>

Continue reading →

How Use Loops in C-'FOR' Loops

0 comments

Loops are used to repeat a block of code.Loops are one of the most basic but useful task in programming.We can simply produce extremely complex out put using loops.A loops let you write a very simple statement to produce a significantly greater result  simply by repetition.


FOR LOOPS:


FOR loops are the most useful one.The syntax of FOR loops:
for(variable initialization; condition; variable update)
{
code to execute while the condition is true
}
Example:


To print numbers upto 10:
#include<stdio.h>

int main()
{
    int x;
    /* The loop goes while x < 10, and x increases by one every loop*/
    for ( x = 0; x < 10; x++ ) {
        /* Keep in mind that the loop condition checks 
           the conditional statement before it loops again.
           consequently, when x equals 10 the loop breaks.
           x is updated before the condition is checked. */  
        printf( "%d\n", x );
    }
    getchar();
}


The variable initialization allows you to either declare a variable and give it a value or give it a value to already existing variable.The condition tells the program that while the conditional expression is true the loop should continue to repeat it self.The variable update section is the easiest way for a FOR loop to handle changing of the variable.It is possible to do things like X++,X=X+10 or even X=random(3).Notice that a semicolon separates each of these sections. Also note that every single one of the sections may be empty,though the semicolon still have to be there


This program is a very simple example of a for loop.x is set to zero,while x is less than 10 it calls printf to display the value of variable x,and it adds 1 to x until the condition is met.Keep in mind also that the variable is  incremented after the code in the loop is run for the first time


<<Prev Home Next>>

Continue reading →