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

Structured Programming Language: The Loop

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 53

CSI 124

Structured Programming Language

Lecture 05
The Loop
loop
• Loops are used in C for repeating some portion of the
program either a specified number of times or until a
particular condition is being satisfied.
• A loop statement allows us to execute a statement or
group of statements multiple times.
• A loop is used for executing a block of statements
repeatedly until a given condition returns false.
loop
• There are three methods in C for repeating a
part of program
1. Using a for statement
2. Using a while statement
3. Using a do..while statement
Sr.No. Loop Type & Description
1 while loop: Repeats a statement or group of statements while a
given condition is true. It tests the condition before executing the
loop body.
2 for loop: Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.

3 do...while loop: It is more like a while statement, except that it


tests the condition at the end of the loop body.

4 nested loops: You can use one or more loops inside any other
while, for, or do..while loop.
loop
• A looping process would include the following
four steps:
– Setting and initialization of a counter
– Test for a specified condition for execution of
the loop
– Execution of the statement in the loop
– Incrementing/decrementing the counter
The for loop

Expression1, expression2 and expression3 are normally used for


initialization, loop condition and loop counter increment
respectively. Expression2 returns a value which may true or false.
The for Loop

• The for loop allows us to specify three


things in a single line:

1. Setting a loop counter to an initial value.


2. Testing the loop counter to determine whether its value
has reached the number of repetitions desired.
3. Increasing/decreasing the value of loop counter each time
the program segment within the loop is executed.
General form of for loop
Example of for loop

• This program prints number 1 to 10


Structure of for loop
Variation of for loop
Variation of for loop
Variation of for loop
Variation of for loop: Infinite loop
Observing for loops

The initialization, loop-continuation condition and


increment/decrement can contain expressions.
Assume, that x = 2 and y = 10.
The statement-
for(j = x; j <= 4*x*y; j = j + y/x) is equivalent to-
for(j = 2; j <= 80; j = j+5)
Observing for loops
There can be decrement as well( or you can say a
negative increment).

For example -
Observing for loops

If the loop continuation condition is initially false,


the body portion of the loop is not performed.
Observing for loops
Qs
What will be the output?
#include<stdio.h>
void main()
{
int c;
for(;c=0;)
{
printf("Hello");
}
}

Output:
* 1+2+3+…+n
#include <stdio.h>
void main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; count++)
{
sum += count;
}
printf("Sum = %d", sum);
}
* 3+11+19+…+1691
#include<stdio.h>
void main()
{
            int i,n,sum = 0;
            printf("Sum Of Series");
            for(i=3;i<=1691;i=i+8)
                 {
                 sum = sum+i;
                 }
            printf("sum = %d",sum);
}
What will be the output?
#include<stdio.h>
void main ()
{
int n,num,min,i;
min=5;
num=2;
for (i=1; i<5; i++)
{
if (num<i)
{
min=num;
printf(“Okay %d Bye\n",min);
}
printf(“Good %d Hello\n",min);
}
}
Nested for loop
• A for loop inside another for loop is called
nested for loop.
• We can have any number of nested loops as
required.
• Just like decision control instructions, a loop
control instruction can also be nested easily.
Syntax of nested for loop
• 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);
}
Sample Program
#include<stdio.h>
void main()
{
int row,col;
for(row=1;row<4;row++)
{
for(col=1;col<4;col++)
{
printf("row = %d \tcol = %d\n",row,col);
}
}
}
o/p of the previous program

row = 1 col = 1
row = 1 col = 2
row = 1 col = 3
row = 2 col = 1
row = 2 col = 2
row = 2 col = 3
row = 3 col = 1
row = 3 col = 2
row = 3 col = 3
Sample Program

#include<stdio.h> ***
void main()
{ ***
            int i,j;
            for(j=1;j<=3;j++) ***
             {
               for(i=1;i<=3;i=i+1)
                {
                  printf("*");
                }
               printf("\n");
             }
}
Loop Control Statements
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
C supports the following control statements.

Sr.No. Control Statement & Description


1 break statement Terminates the loop or switch statement and
transfers execution to the statement immediately following the
loop or switch.
2 continue statement Causes the loop to skip the remainder of
its body and immediately retest its condition prior to reiterating.
3 goto statement Transfers control to the labeled statement.
The break Statement
• We often come across situations where we
want to jump out of a loop instantly, without
waiting to get back to the conditional test.
• The keyword break allows us to do this.
The break Statement
• The break statement in C has the following
two usages −
• When a break statement is encountered
inside a loop, the loop is immediately
terminated and the program control
resumes at the next statement following the
loop.
• It can be used to terminate a case in
the switch statement.
The break Statement
#include <stdio.h>
void main () {
int a = 10;
for(a = 10 ; a < 20 ; a++) { Output:
if(a > 15) { value of a: 10
break; value of a: 11
} value of a: 12
printf("value of a: %d\n", a); value of a: 13
} value of a: 14
} value of a: 15
The continue Statement
• In some programming situations we want to
take the control to the beginning of the loop,
by passing the statements inside the loop,
which have not yet been executed.
The continue Statement
• The keyword continue allows us to do this.
When continue is encountered inside any
loop, control automatically passes to the
beginning of the loop.
The continue Statement
#include <stdio.h>
void main () {
int a = 10;
for(a = 10 ; a < 15 ; a++) { Output:
if(a == 12) { value of a: 10
continue; value of a: 11
} value of a: 13
printf("value of a: %d\n", a); value of a: 14
}
}
The goto Statement
• A goto statement in C programming provides an
unconditional jump from the 'goto' to a labeled statement in
the same function.
• The goto statement allows to transfer control of the program
to the specified label.
• The label is an identifier. When the goto statement is
encountered, the control of the program jumps to label: and
starts executing the code.
The goto Statement
• // Program to calculate the sum and average of positive numbers
• // If the user enters a negative number, the sum and average are displayed.
#include <stdio.h>
int main() {
const int maxInput = 100;
int i;
double number, average, sum = 0.0;
for (i = 1; i <= maxInput; ++i) {
printf("%d. Enter a number: ", i);
scanf("%lf", &number);
// go to jump if the user enters a negative number
if (number < 0.0) {
goto jump;
}
sum += number;
}
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
The while loop
The while Loop
• Here, statement(s) may be a single
statement or a block of statements.
The condition may be any expression, and
true is any nonzero value. The loop iterates
while the condition is true.
• When the condition becomes false, the
program control passes to the line
immediately following the loop.
Flowchart of while loop
Example of while loop
• This program prints number 1 to 10

#include <stdio.h>
void main () {
int a = 1;
while( a <= 10 ) {
printf("value of a: %d\n", a);
a++;
}
}
Find the output of the program
#include <stdio.h>
main()
{ Output:
int i = 10; Hello 10
while ( i > 0 ) Hello 9
Hello 8
{ Hello 7
printf("Hello %d\n", i );
i = i - 1;
if( i == 6 )
{
break;
}
}
}
The do…while loop
The do…while Loop

• Unlike for and while loops, which test the loop


condition at the top of the loop,
the do...while loop in C programming checks
its condition at the bottom of the loop.
• A do...while loop is similar to a while loop,
except the fact that it is guaranteed to execute
at least one time.
Flowchart of do…while loop
Example of do…while loop

• This program prints number 1 to 10


#include <stdio.h>
void main () {
int a = 1;
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a <= 10 );
}
Find the output of the program
#include<stdio.h>
main()
{
int i=0;
do
{
printf("while vs do-while\n");
}while(i==1);
printf("Out of loop");
}
Solve using for, while, do…while
* 1+2+3+…+10 (while)
#include <stdio.h>
void main()
{
int count, sum = 0;
count=1;
while(count<=10)
{
sum += count;
count++;
}
printf("Sum = %d", sum);
}
* 1+2+3+…+10 (do…while)
#include <stdio.h>
void main()
{
int count, sum = 0;
count=1;
do
{
sum += count;
count++;
}while(count<=10);
printf("Sum = %d", sum);
}
Difference between for, while and
do-while loop?
Sr. For loop While loop Do while loop
No
1. Syntax: Syntax: Syntax:
for(initialization; condition; updating) while(condition) do {…Statements; }
{ …Statements; } { …Statements; } while(condition);

2. It is known as entry controlled loop. It is known as entry It is known as exit


controlled loop. controlled loop.

3. If the condition is not true first time If the condition is not Even if the condition is
than control will never enter in a loop true first time than not true for the first
control will never time the control will
enter in a loop. enter in a loop.

4. There is no semicolon; after the There is no There is semicolon;


condition in the syntax of the for loop. semicolon; after the after the condition in
condition in the the syntax of the do
syntax of the while while loop.
loop.
5. Initialization and updating is the part Initialization and Initialization and
of the syntax. updating is not the updating is not the part
part of the syntax. of the syntax

You might also like