Lecture-13 (17-10-2023)
Lecture-13 (17-10-2023)
MA144:
Computer Programming
Lecture-13
Loops, break, continue
Three important pyramids
Write a program to print the following pattern.
#include<iostream>
using namespace std;
int main()
{ int rows,space,i,j;
cout<<"enter no. of rows: ";
cin>>rows;
for(i=1;i<=rows;i++)
{
for(space=1;space<=rows-i;space++)
cout<<" ";
for(j=1;j<=2*i-1;j++)
cout<<"*";
cout<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{ int rows,space,i,j;
cout<<"enter no. of rows: ";
cin>>rows;
for(i=1;i<=rows;i++) two spaces
{
for(space=1;space<=rows-i;space++)
cout<<" ";
for(j=1;j<=2*i-1;j++)
One space
cout<<"* ";
cout<<endl;
}
return 0;
}
Write a program to print the following pattern.
Exercise
Write a program to print the following pattern.
#include<iostream>
using namespace std;
int main()
{ int rows,space,i,j;
cout<<"enter no. of rows: ";
cin>>rows;
for(i=0;i<=rows-1;i++)
{
for(space=0;space<i;space++)
cout<<" ";
for(j=space;j<rows;j++)
cout<<"* ";
cout<<endl;
}
return 0;
}
Loops
Group of statements that are executed
repeatedly while some condition
remains true
Each execution of the group of
statements is called an iteration of the
loop
for for()
{ statement-1;
while statement-2;
do-while }
statement-3;
for loop
for(expr1; expr2; expr3)
{ statement-1;
statement-2;
statement-3;
}
expr1 (initialization) : initialize parameters
expr2 (loop-continuation test): loop continues
if expression is non-zero
expr3 (update): used to alter the value of the
parameters after each iteration
Initialization, loop-continuation test, and
update can contain arithmetic expressions
} empty block
Guess the output of the following program.
Guess the output of the following program.
Infinite Loops
for(; ;) while(1)
{ statement1; { statement1;
statement2; statement2;
statement3; statement3;
} }
do
Condition is necessary in
{ statement1;
while and do-while
statement2;
statement3;
}while(1)
Infinite for Loop
Another
Infinite for Loop
Find out the output of the following program.
Relation between for and while loops.
for(expr1; expr2; expr3)
{ statement-1;
statement-2;
statement-3;
}
expr1;
same as while(expr2)
{ statement-1;
statement-2;
statement-3;
expr3;
}
The break statement
• Break out of the loop body { }
∎ can use with while, do-while, for, switch
∎ does not work with if, if-else
break continue
• exits loop • exits the current
iteration of the loop
What would be the output ?
Usage of both continue and break