Nothing Special   »   [go: up one dir, main page]

For Loop ES081 PART B

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Control Flow

for statement
- a kind of loop command wherein the execution of the
statement does not depend on another instruction.
Syntax:
for (initialization expression; loop repetition condition; update expression)
{
statement/s;
}
Basic For Loop Syntax
For loops are usually used when we know exactly how many
times we need to execute repeating block of code. It is also
good for creating definite loops.
int counter;
1. Priming: Set 2. Test Condition: 3. Update: Update the
the start value. Set the stop value. value.

for (counter =1;counter <= 10;counter++)


System.out.println (counter); Note that each section is
separated by a semicolon.
Control Flow

Example

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


printf(“Hello World\n”);
}
Flowchart of for loop
For Loop Flowchart
1. Priming
Set counter=1

2. Test TRUE 3a. print counter


counter
3b. Update counter++;
<= 10

FALSE
Sample Problems: Implement using for loop
#include<stdio.h>
#include<conio.h>
//Make a C program to input 10 integers and will output their sum
Problem 1
int main()
{
Make a C program int num, ctr, sum=0; //declaration part
that will input 10 for(ctr=1; ctr<=10; ctr++)
{
numbers. Output the printf("Enter number%d:", ctr);
sum. scanf("%d", &num);
sum=sum+num; //can be written also as sum+-=sum;
}
printf("The sum is %d", sum);
return 0;
}
Sample Problems: Implement using for loop
int main()
{
int num, ctr, ctr_pos_odd=0, sum_pos_odd=0; //declaration part
Problem 2 float ave_pos_odd=0.0;
for(ctr=1; ctr<=10; ctr++)
{ printf("Enter number%d:", ctr);
Make a C program scanf("%d", &num);
if(num>0 && num%2!=0)
to output the { sum_pos_odd+=num;
ctr_pos_odd++;
average of all }
positive odd }
ave_pos_odd=(float) sum_pos_odd/ctr_pos_odd;
integers. );
printf("The average of all positive add ineteger is %0.2f", ave_pos_odd

return 0;
}
Types of Loop

Additional information on the different


types of Loops
Loop types (reminder)
Indefinite Loop:

 You do not know ahead of time how many times your loop will execute.
 For example, you do not know how many books a person might order.
Definite Loop:

 You know exactly how many times you want the loop to execute.
 not at compile time necessarily
Infinite Loop
You can still end up with an infinite loop when using for loops

for (counter = 0; counter <= 10; counter--)


For Loop Variations
 The limit can be a variable:
for ( i = 1; i <= limit; i++)
 This counts from 1 to limit
 Update may be negative:
for (i = 100; i >= 1; i--)
 This counts from 100 to 1.
 Update may be greater than 1:
for (i = 100; i >= 5; i -= 5)
 This counts from 100 to 5 in steps of 5
While Loop
While loop is usually used when we do not know exactly how many times we need
to execute repeating block of code

while (*)
{
/* repeating block of code */
}

* Is a condition which is true or false. Ex. Value> 5


Condition is checked at every iteration start. If condition is true, execution will
continue, if it is false execution will break.
Do While
Do-while loop is usually used when we do not know exactly how many times we need to
execute repeating block of code, but we know that we need to execute it at least once

do {
/* repeating block of code */
} while (*);

do-while is same as while loop with difference that the condition is checked at every
iteration end. Consequence is that repeating block of code in do-while loop is
always executed at least once.
When to Use Which Loop ?

If you know (or can calculate) how many iterations you need
, then use for loop.
Otherwise, if it is important that the loop complete at least
once before checking for the stopping condition, or if it is
not possible or meaningful to check the stopping
condition before the loop has executed at least once, then
use a do-while loop.
Otherwise use a while loop.
Loop within a loop (Nested loops)
C programming language allows to use one loop inside another loop.
Following section shows few examples to illustrate the concept.

The syntax for a nested for loop statement in C is as follows:


for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
Additional Problems
Make a C program to output the following
figures shown below:

a] *
**
* * *
* * * *
Solution to Figure a:

#include<stdio.h>
#include<conio.h>
//This program will print a box of asterisks
int main(){
int row, col, max_col, max_row;
printf("Enter maximum rows:");
scanf("%d", &max_row);
max_col=max_row; //since figure is square
for(row=1; row<=max_row; row++) //this is for outer loop: row
{
for(col=1; col<=row; col++) //this is for inner loop: column
{
printf("*");
}
printf("\n"); //this will position the cursor to the next row
}
return 0;
}
Loop within a loop (Nested loops)
The syntax for a nested while loop statement in C
programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
Loop within a loop (Nested loops)
The syntax for a nested do...while loop statement in C programming
language is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
Loop within a loop (Nested loops)

A final note on loop nesting is that you can


put any type of loop inside of any other type
of loop. For example, a for loop can be
inside a while loop or vice versa.
Loop within a loop (Nested loops)
Some programmers like to use successive integers i, j, k, l, etc. for use in
nested for loops. This can be appropriate if the mathematics being
implemented uses multiple i j k subscripts.
Other times it can be less confusing to use alternative variables that are more
meaningful to the problem at hand, such as the r and c variables used above to keep
track of rows and columns.
The limits as to how deeply loops may be nested is implementation
dependent, but is usually too high to be of any concern, except in cases of
extremely complex or extremely poorly written programs.

You might also like