Loops More loops Off-by-one errors Infinite loops Nested Loops.
Presentation on nesting of loops
description
Transcript of Presentation on nesting of loops
PRESENTATION
By:- Balwinder Singh
nested loops
CONTENTS
What is a Loop? Nested While loops. Do…..While loops. Nested For loops. Question.
WHAT IS A LOOP?
A loop is a programming structure that contains an executable block of code that repeats so long as a given condition is true/not true.
Good programmers include a way to satisfy the condition somewhere inside the executable block. loops
TYPES OF NESTED LOOPS
Nested While Loops. Do…..While Loops. Nested For Loops.
nested loops
NESTED WHILE LOOPS
WHILE loops may be nested, that is you can put a WHILE loop inside another WHILE loop.
However, one must start the inner loop after starting the outer loop and end the inner loop before ending the outer loop for a logically correct nesting.
EXAMPLE:- NESTED WHILE LOOPS
To print the following series:-
11 21 2 31 2 3 41 2 3 4 5
EXAMPLE:- NESTED WHILE LOOPS#include<stdio.h>#include<conio.h>main(){
int r=1,c=1;while (r<=5){c=1;while(c<=r){ printf(“%d”,c); c++; }printf(“\n”);r++;}getch();
}
DO……WHILE LOOP Executes the loop statement once and then
repeats the loop statement until the condition is zero (false).
Starts with a do statement and then tests the repetition condition in the while statement at the end of the loop.
Syntax:- do{ statements;}
while(condition);
LOGIC OF A DO….WHILE LOOPS
statement
true false
condition evaluated
The while Loop
EXAMPLE:- DO….WHILE LOOP
#include<stdio.h>#include<conio.h>main(){
int a;do{printf(“Enter any number”);scanf(“%”,&a);if (a>=0)printf(“Number is positive”);elseprintf(“Number is Negative”);}while(a!=0);getch();
}
Accept any number from the user to print the number is positive or negative.
NESTED FOR LOOPS A for loop can contain any kind of
statement in its body, including another for loop.
The inner loop should have a different name for its loop counter variable so that it will not conflict with the outer loop.
EXAMPLE:- NESTED FOR LOOPS
Write a program to print the following series:-
12 34 5 67 8 9 10
EXAMPLE:- NESTED FOR LOOPS#include<stdio.h>#include<conio.h>main(){
int r,c,k=1;for (r=1;r<=4;r++){for (c=1;c<=r; c++) {printf(“%d”,k);k++;} printf(“\n”);}getch();
}
ANY QUESTIONS???
Do….WhileNested
While
Nested For