CIS-104 T Computer Fundamentals: BSME 2015-19
CIS-104 T Computer Fundamentals: BSME 2015-19
CIS-104 T Computer Fundamentals: BSME 2015-19
BSME 2015-19
DCIS-PIEAS
By
Nauman Shamim
Todays Session
For loop
Syntax
Examples
Nested For Loop
For loop
Syntax
for ( 1-Initialization; 2-Test-Condition; 3-Update ){
statement(s);
}
#include<stdio.h>
#include<conio.h> Output
Value of i = 1
int i;
Value of i = 2
for(i=0;i<5;i++)
Value of i = 3
printf(\nValue of i = %d,i); Value of i = 4
getche();
}
Loop walk trough
Lets execute this loop step by step
for(i=0;i<4;i++)
printf(\nValue of i = %d,i);
Initialize i , i = 0
Is i<4 , yes, execute body of loop and update Output:
printf(\nValue of i = %d,i); Vallue of i = 0
i=1;
Is i<4, yes, execute the body of loop and update Output:
printf(\nValue of i = %d,i); Vallue of i = 1
i=2
Is i<4, yes, execute the body of loop and update Output:
printf(\nValue of i = %d,i); Vallue of i = 2
i=3
Is < 4 , yes, execute body of the loop and update Output:
printf(\nValue of i = %d,i); Vallue of i = 3
i=4
Is i<4 No as i=4, body of loop will not be executed and loop ends
for loop optional parts
#include<stdio.h>
void main(){
int a,b,i;
b=15;
b=25;
}
Example-2
Program :Print all even numbers between two numbers A
and B
#include<stdio.h>
void main(){
int a,b,i;
b=15;
b=25;
}
Nested Loops
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
How many times X is printed
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<3;j++)
printf(X);
}
The outer loop has 5 iterations (The body of outer loop is
executed 5 times)
So inner loop is executed 5 times
The inner loop has 3 iterations ( The body of inner loop is
executed 3 times )
In one iteration of outer loop x is printed 3 times
So, 5x3=15 the printf(X); statement will be executed 15 times