CSE Rockz Home Blog Links Forum VSF

Friday, December 12, 2008

DAILY:1:FOR LOOP

 
date:12/12/08

Todays topic: Introduction to for loop.

For loop

Syntax:   for(intialization;condition;increment or decrement)

key points:

1. for loop comes under looping commands like while and do while.

2. in for loop all three operations are written at one place(intialization;condition;increment or  
decrement).unlike the while loop.

3. first time when a for loop is to be executed....it initializes first,then cheks the condition and proocedes...after executing it increments or decrements.the next time...i directly checks the given condition without any initialization....and after that it decrements or increments...the process continues untill c
ondition is satisfied..

4. scope of a for loop is only up to the next statment.to include more statements,bunch them with a couple of flower braces....
 


                 
                                                            A for loop flow chart



examples:

example1:

/* write a program to print 1 to 10 numbers using a for loop */

#include
main()
{
int i;

for(i=1;i<=10;i++)
{

printf("%d",i);

}

}

output:
12345678910


example2:

/*write a program which accepts a number and prints all numbers upto it*/


#include
main()
{

int n,i;
printf("enter a number");
scanf("%d",&n);

for(i=1;n=i;i++)
{


printf("%d",i);

}


}

output:
enter a number 5
12345

example 3:

/*write a program that accepts two numbers and prints all numbers between them*/

#include
main()
{

int n1,n2,i,s,b;
printf("give two numbers");
scanf("%d %d",&n1,&n2);

s=(n1>n2)?n2:n1;
b=(n2>n1)?n2:n1;

for(i=s;b>=i;i++)
{

printf("%d",i);

}

}

output:
give two numbers 3 7

34567


Nested for loop:

a for loop with in a for loop is called nested for loop.  



                                                        A nested loop flowchart


example:4;

/*write a program which prints 1 t0 10 5 times*/

#include
main()
{

int i,j;

for(i=1;i<=5;i++)
{

for(j=1;j<=10;j++)
{
printf("%d",i);
}
}




}


output:
1234567891012345678910..........



example:5:

*/write a program which prints an output
1
12
123
1234
12345
123456
1234567
.
.
.
.
.
. . . . . . . . . . . . . . . . . . . . n 

where n is input integer*/


#include
main()
{

int n,i,j;
printf("give n");
scanf("%d",&n);

for(i=1;n>=i;i++)
{

for(j=1;n>=j;j++)
{

printf("%d",j);
}
prinf("\n");
}



}


output: 

give n 6

1
12
123
1234
12345
123456


No comments:

Post a Comment