Lab 9

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Page 1 of 4

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;

for( i = 1; i <= j; i++ )


fact *= i;
cout << "Factorial is: " <<fact;
}
Page 2 of 4

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;
}
}

Prepared By: Khawar Khalil

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy