0% found this document useful (0 votes)
15 views27 pages

Understanding Loop Structures in C++

The document discusses different types of loops in programming - entry controlled loops, exit controlled loops, while loops, do-while loops, and for loops. It provides examples of each loop type and describes features like nesting loops, breaking/continuing out of loops early, and calculating values using loops.

Uploaded by

Parth R. Shah
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views27 pages

Understanding Loop Structures in C++

The document discusses different types of loops in programming - entry controlled loops, exit controlled loops, while loops, do-while loops, and for loops. It provides examples of each loop type and describes features like nesting loops, breaking/continuing out of loops early, and calculating values using loops.

Uploaded by

Parth R. Shah
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Decision making & Looping

A sequence of statements are executed until some termination conditions satisfied. Program loop: body of loop. control statement -> tests certain conditions & then directs repeated execution of statements within the body of loop. Two types: Based on position of control statement. 1) Entry controlled loop: control are tested before the start of the loop. If false body will not be executed. 2) Exit controlled loop: test is performed at the end of the body. i.e body of loop executed at least once.
3/22/2013 CS&E Dept

Entry Controlled & Exit controlled loop


Entry Exit

Test Condition True Body of The loop

False

Body of The loop

Test Condition False

True

3/22/2013

CS&E Dept

While statement
Basic format: while (test condition) { body of the loop } * Entry controlled loop statement. Test condition evaluated & if it is true, then body of the loop is executed. After execution, the test condition is again evaluated & if it is true, the body is executed again. This Procedure is repeated until test condition becomes false, & control transferred out of the loop. i.e body of loop may not executed if the condition is false at the very first attempt.

3/22/2013

CS&E Dept

Example
#include <iostream.h> void main() { int counter; counter =0; while (counter < 5) {
cout << "I love computer science << endl; counter = counter + 1;

}
3/22/2013 CS&E Dept

Example
#include <iostream.h> void main() { int counter; int sum; sum=0; //initialize sum counter=0; while (counter<100) { sum=sum+counter; counter = counter +1; } cout<<sum; }
3/22/2013 CS&E Dept

The do statement
General form: do { body of the loop } while (test condition); Exit controlled loop. After do statement, program executes the body of the Loop. At the end of the loop, the test condition in the while is evaluated. If it is true, body of the loop is executed once again & this process continues as long as the condition is true. When condition becomes false, the loop will be terminated. Body of the loop executed at least once. do while loop can be nested. 3/22/2013 CS&E Dept

Example
#include <iostream.h> void main() { int counter; int sum; sum=0; //initialize sum counter=0; do { sum=sum+counter; counter = counter +1; } while (counter<100) cout<<sum; }
3/22/2013 CS&E Dept

The for statement


The general form: for (intilization; test condition; increment) { Body of the loop } Entry controlled loop. Next statement;
3/22/2013 CS&E Dept

Explanation
1. The expression initial_value1 is evaluated, usually an assignment statement that sets a variable to a particular value. [Link] expression condition is evaluated. It is typically a relational expression. 3. If condition evaluates as false (zero), the for statement terminates and execution passes to the first statement following the for statement that is the next_statement. 4. If condition evaluates as true (non zero), the subsequent C++ statements are executed. (i.e body of the loop) 5. The expression increment is executed, and execution returns to step no. 2.
3/22/2013 CS&E Dept

Example
#include <iostream.h> void main() { int counter; int sum; sum=0; //initialize sum for(counter=0;counter<100;counter++) { sum=sum+counter; counter = counter +1; } cout<<sum; }
3/22/2013 CS&E Dept

Additional features of for loop


1. More than one variable can be initialized. Example: for (p=1,n=0;n<15;++n) [Link] section may also have more than one part. Example: for (n=1,m=50;n<=1*m;n++,m--) [Link] condition may have any compound relation & testing need not be limited to the loop control variables. Example: sum=0; for (i=1;i<20 && sum<100;++i) { sum=sum+i; cout << sum; }
3/22/2013 CS&E Dept

Continued
4. It is also permissible to use expressions in the initialization & increment sections. Eg: for (x=(m+n)/2; x>0; x=x/2) 5. In for loop one or more sections can be omitted. Eg: i) m=5; for(;m!=50;) { cout<<m; m=m+5; } ii) for (;;) iii) for (i=1000;i<100;i=i-1) ; . iv) for (i=1000;i<100;i=i-1) ; no syntax error treated as null statement.
3/22/2013 CS&E Dept

Nesting of for loop


One for statement within another for statement. for (i=1;i<10;++i) {.. . for (j=1;j<4;++j) { ..} }
3/22/2013 CS&E Dept

Jumping out of a loop


An early exit from a loop can be accomplished by using the break statement. When the break statement is encountered inside a loop, the loop is immediately exited & the program continues with the statement immediately following the loop. When the loops are nested , the break would only exit from the loop containing it. i.E , the break will exit only a single loop.
3/22/2013 CS&E Dept

Exiting a loop with break statement


while (.) {. If(condition) break; Exit From loop
3/22/2013

do (.) {. If(condition) break; Exit From loop


CS&E Dept

.
} ..

.
} while() ..

for (.) for {. If(condition) break; Exit From loop . Exit From inner loop
CS&E Dept

{. for(..) { If(condition)

break;

} ..
} ..

}
..

3/22/2013

Skipping a part of loop


Skip a part of the body of the loop under certain conditions. Using continue statement. As the name implies, causes the loop to be continued with next iteration, after skipping rest of the body of the loop. while (.) {. If(condition) continue; do (.) {. If(condition) continue;

.
} ..
3/22/2013 CS&E Dept

.
} while() ..

for (.) {. If(condition) continue;

. } ..

3/22/2013

CS&E Dept

#include<iostream.h> #include<conio.h> #include<math.h> //Sine of an angle upto given accuracy i.e |term|<accuracy void main() { int i=1; double sum,angle,term,accr; const double pi=22.0/7; clrscr(); cout<<"enter angle and accuracy"; cin>>angle>>accr; angle=angle*pi/180;term=angle;sum=angle; while(fabs(term)>accr) { term=-term*angle*angle/((2*i)*(2*i+1)); sum=sum+term; i++; }cout<<"\n the sine angle is "<<sum;cout<<"\n actual value is "<<sin(angle); getch(); CS&E Dept } 3/22/2013

#include<iostream.h> #include<conio.h> #include<math.h> //Cosine of a number upto given accuracy void main() { int i=0;const double pi=22.0/7; float sum,angle,term,accr;clrscr(); cout<<"\n enter angle and accuracy"; cin>>angle>>accr; angle=angle*pi/180; term=1;sum=1; while(fabs(term)>accr) { term=-term*angle*angle/((2*i+1)*(2*i+2)); sum=sum+term; i++; } cout<<"\n the cosine of angle is "<<sum; cout<<"\n actual value is "<<cos(angle); getch(); 3/22/2013 CS&E Dept }

#include<iostream.h> #include<conio.h> #define true 1 #define false 0 //To check whether the number is prime or not
void main() { int n,i,prime;clrscr(); cout<<"enter number";cin>>n; if(n==1) cout<<"\n the number is not prime"; else if ((n==2)||(n==3)) cout<<"\n the number is prime"; else { for(i=2;i<=n/2;i++) { prime = true; if(n%i==0) { prime = false; break; }}if(prime==true) cout<<"\n the number is prime";else cout<<"\n the number is not prime";}getch();}
3/22/2013 CS&E Dept

#include<iostream.h> #include<conio.h> //Generating prime numbers below the given limit void main() { int n,i,prime,j;clrscr(); cout<<"enter limit";cin>>n; for(i=1;i<=n;i++) { for(j=2;j<=i/2;j++) { prime =1; if(i%j==0) { prime = 0; break; } } if((prime==1)||(i==2)||(i==3)) cout<<"\n"<<i; }getch(); }
3/22/2013 CS&E Dept

#include<iostream.h> #include<conio.h> #define true 1 #define false 0 // Generate prime Fibonacci numbers void main() { int j,prime,num,i,f1,f2,fib; clrscr(); cout<<"number of fib nos"; cin>>num; cout<<"\n sequence is "; for(i=1,f1=1,f2=1,fib=0;i<=num;i++) { if ((f1==2)||(f1==3)) cout<<"\n"<<f1; else { for(j=2;j<=f1/2;j++)
3/22/2013 CS&E Dept

{ prime = true; if(f1%j==0) { prime = false; break; } } if(prime==true) cout<<"\n"<<f1; } fib=f1+f2; f1=f2; f2=fib; } getch(); }

3/22/2013

CS&E Dept

#include<iostream.h> #include<conio.h> #define true 1 #define false 0 //Generating prime numbers below the given limit void main() { int n,i,prime,j; clrscr(); cout<<"enter limit"; cin>>n;
3/22/2013 CS&E Dept

for(i=1;i<=n;i++) { for(j=2;j<=i/2;j++) { prime = true; if(i%j==0) { prime = false; break; } } if((prime==true)||(i==2)||(i==3)) cout<<"\n"<<i; } getch(); }

3/22/2013

CS&E Dept

#include<iostream.h> #include<conio.h> //Find average of m numbers until negative number is typed using type casting void main() { int m; float sum,x,avg; clrscr(); cout<<"enter value"; sum=0; for(m=1;m<=100;m++) { cin>>x; if(x<0) break; sum+=x; } avg=sum/(float)(m-1);cout<<"\n avg = "<<avg; getch(); 3/22/2013 CS&E Dept }

Common questions

Powered by AI

While both 'continue' and 'break' alter the normal flow of loops, a 'continue' statement skips the rest of the loop body’s current iteration, whereas a 'break' statement terminates the loop entirely. 'Continue' is used when we want to ignore specific iterations under some conditions without halting the loop, while 'break' is appropriate for exiting early from loops when further iterations are unnecessary or counterproductive .

A 'break' statement is used to exit a loop prematurely when a specific condition is met. Within nested loops, it exits from the innermost loop containing it. This allows for early termination of the loop to avoid unnecessary iterations or when a specific criterion has been satisfied, improving efficiency. In nested loops, only the loop where the 'break' is invoked is terminated, and the control moves to the next statement following that loop .

The sine calculation is implemented by initializing variables for the angle and accuracy, then iteratively updating the 'term' value using its previous value multiplied by factors involving the angle, using the formula 'term=-term*angle*angle/((2*i)*(2*i+1))'. This process continues while the absolute value of the 'term' is greater than the desired accuracy, thus refining the 'sum' to approximate the sine value as closely warranted by the accuracy parameter .

Successful use of nested for-loops relies on carefully managing loop control variables and ensuring each loop has its own distinct variables. Initialization should be clear and should avoid conflicts or unintended interactions between inner and outer loop variables. Proper management of the logical conditions and increments is crucial to avoid infinite loops or off-by-one errors, requiring precise tailoring of each loop’s conditions and termination criteria for synchronized behavior .

These loop structures utilize a nested loop where the outer loop iterates through numbers from 1 to the given limit, and the inner loop checks divisibility for factors up to the number’s half value. If a number isn't divisible by any number other than 1 and itself, it is marked as prime. The prime checks are optimized by stopping early with a 'break' on finding a divisor, reflecting the efficient integer factorization principle .

A 'continue' statement in loops causes the loop to skip the remaining code in its current iteration and proceed with the next iteration. This is useful when certain conditions require parts of the loop body to be skipped. The 'continue' statement doesn’t exit the loop but only skips the execution of subsequent statements for the current loop cycle, thus control goes to the next iteration, affecting flow at a granular level .

The 'do-while' loop checks its condition at the end of the loop rather than at the beginning. This ensures that the body of the loop executes at least once before any condition is tested, unlike 'while' or 'for' loops where the condition is tested at the start. This characteristic makes 'do-while' particularly suitable for situations where an operation must be performed at least once regardless of initial conditions .

A 'for loop' can handle multiple variables by initializing and incrementing more than one variable simultaneously. This is done by separating the different expressions with commas. For example, 'for (p=1,n=0;n<15;++n)' initializes and manages two variables, and 'for (n=1,m=50;n<=1*m;n++,m--)' both increments and decrements the variables simultaneously .

The algorithm initializes two starting Fibonacci numbers and iteratively calculates subsequent numbers. Each new Fibonacci number is checked for primality by attempting division by all preceding numbers up to its half value. Only numbers that aren't divisible by any preceding numbers (except 1 and itself) are identified as prime. Including checks for small Fibonacci numbers like 2 and 3 explicitly ensures they are correctly identified as prime .

Entry-controlled loops evaluate the test condition before the loop body executes, allowing the body to potentially never execute if the condition is false initially, as seen in while and for loops. Exit-controlled loops evaluate the test condition after the body is executed, ensuring the body runs at least once, as demonstrated in do-while loops .

You might also like