This document discusses different types of looping statements in programming. It begins by defining a loop as a programming structure that repeats a block of code as long as a condition is true or false.
It then describes three common loop types: for loops, which check a condition before each iteration; while loops, which check at the end of each iteration; and do-while loops, which check at the end but run the code block at least once. Nested loops, where one loop is placed within another, are also discussed. Examples are provided to demonstrate how each loop type is written and functions.
1. DEPARTMENT OF PHYSICS
M.SC. 1ST SEMESTER (2015-2016)
SUB: COMPUTATIONAL PHYSICS
PRESENTED BY: CHITRA JAIN
SUBMITTED TO : DR. D. K. SHARMA
2.
3. “LOOP is a programming structure that contains an
executable block of code that repeats (iterates) so long as a
given condition is true or false.” therefore looping statements
also called “ITERATIVE STATEMENTS”.
5. FOR LOOP
Pre-test or Entry controlled loop
i.e. conditions are checked first if found true
then and only then code is executed
otherwise
loop gets terminated.
For loop has three parts:
1. Initialization
2. Condition
3. Increment/ Decrement
All these three expressions need not be included in for statement. But semicolons must
be present.
for ( ; ; )
6. SYNTAX:
For (expression 1; expression 2;
exprssion3)
{
Body of the loop
}
expression 1 : used to initialize loop parameter.
expression 2 : represent test condition that must
be true for continue execution of loop.
expression 3 : is update expression that update
the loop parameter (Inc./Dec.)
8. EXAMPLE
Q. To find sum of first n natural numbers.
# include <stdio.h>
int main ()
{
int n, count, sum=0;
printf (“enter the value of n n”);
scanf (“%d”,&n);
for (count=1; count<=n; count++)
{
sum=sum+count;
}
printf (“sum=%d”, sum);
getch();
}
output of this program will be as follows:
Enter the value of n
7
sum=28
9. NESTED LOOP
“ A NESTED LOOP is a loop within a loop i.e. an inner loop within the body of an outer
loop.”
The inner and outer loops need not be generated by the same type of control
structure.
It is essential that one loop be completely embedded within the other, there can be
no overlap. Each loop must be controlled by a different index.
Common use for nested loop is to display data in Rows & columns.
10.
11. NESTED FOR LOOP STATEMENT
SYNTAX:
For (initialization; condition; Inc./Dec.)
{
for( initialization; condition; Inc./Dec.)
{
statement(s);
}
statements(s);
}
12. EXAMPLE
# include <stdio.h>
int main()
{
int row,col;
for (row=1; row,=3; row++)
{
for (col=1; col=row; col++)
{
printf(“%d”,row);
}
printf(“n”);
}
getch();
}
output of this program will be as follows:
1
2 2
3 3 3