Lab 9
Lab 9
Lab 9
TASK #1:
Describe the difference between pre-test loop and post-test loop.
SOLUTION:
A pre-test loop tests its condition before each iteration. A post-test loop tests its condition after each
iteration. A post-test loop will always execute at least once.
Task #2:
Why are the statements in the body of a loop called conditionally executed statements?
SOLUTION:
Because they are only executed when a condition is true.
TASK #3:
Write a Program that display numbers from 1-20 using for loop.
1,2,3,4,5,6,7,8,9………………..20.
SOLUTION:
#include <iostream>
using namespace std;
int main ()
{
for( int a = 1; a <= 20; a ++ )
{
cout << a << ", ";
}
}
TASK #4:
Write a program in C++ that calculates the factorial of user defined number, using for loop.
Hint: n*(n-1)*(n-2)*(n-3)*………….*3*2*1
SOLUTION:
#include <iostream>
using namespace std;
int main ()
{
int i,j, fact=1;
cout<<"Enter Number: ";
cin>>j;
TASK #5:
Write a Program to display “ * “ which get number of rows from user using for loop.
Hint:
*
**
***
****
*****
******
SOLUTION:
#include <iostream>
using namespace std;
int main ()
{
int i,j,r;
cout<<"Enter Number of Rows: ";
cin>>r;
for(i=1;i<=r;i++)
{
for(j=1;j<=i;j++)
cout<<"*";
{
cout<<"\n";
} } }
TASK #6:
Write a program in C++ to display the following output using for loop.
Number (Number)2
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
SOLUTION:
#include <iostream>
using namespace std;
int main ()
Page 3 of 4
{
int i;
cout<<"Number---------Number Square\n";
for(i=1;i<=10;i++)
cout<<i<<"------------------"
<<i*i<<endl;
}
TASK #7:
Write a program using for loop that displays following set of numbers.
0, 10, 20, 30, 40, ……….1000
SOLUTION:
#include <iostream>
using namespace std;
int main ()
{
for( int a = 1; a <= 100; a ++ )
{
cout << a*10 << ", ";
}
}
Page 4 of 4
TASK #8:
Write a program using nested for loop that display 10 rows of “#” characters. There should
be 15 “#” characters in each row.
SOLUTION:
#include <iostream>
using namespace std;
int main ()
{
for( int a = 1; a <= 10; a ++ )
{
for( int b = 1; b <= 15; b ++ )
cout<<"# ";
cout << endl << endl;
}
}