Lab 5: Loops
In this lab, you will be using loop structures (for, do while, and while) to
complete the following programs. As in the last lab, much of the programs are
already written.
Print out and turn in the source code of each of your completed programs.
Program 1.
This program
will calculate the factorial function ( n ! ).
Add a while loop to finish the program.
If you feel you
need additional variables, feel free to define them.
/*
* This program will print the value of n!
*/
#include
<iostream>
using namespace
std;
int main()
{
// Get the number n from the user
int n;
cout << "Enter n: ";
cin >> n;
// Loop and calculate the value of n!
unsigned long factorial = 1;
while ( )
{
}
cout << factorial << endl;
return 0;
}
Program 2.
This
program will calculate an approximation of pi.
Convert the program so that it uses a do while loop instead of a for
loop.
/*
* This program will print an approximation of
pi
* using the formula:
*
* pi
= 4 - (4.0/3.0) + (4.0/5.0) - (4.0/7.0) + ...
*
* The user will specify how many of the terms
to
* use in the calculation.
*/
#include
<iostream>
using namespace
std;
int main()
{
// Get the number of terms from the user
int numberOfTerms;
cout << "Enter the number of
terms: ";
cin >> numberOfTerms;
double approximation = 0.0;
double termValue = 0.0;
int sign;
int termCount;
for (termCount = 1; termCount <=
numberOfTerms; ++termCount)
{
if ( (termCount % 2) == 1 )
{
sign = 1;
}
else
{
sign = -1;
}
termValue = sign * (4.0 / (2.0 *
(termCount - 1) + 1.0));
approximation = approximation +
termValue;
}
cout << approximation << endl;
return 0;
}
Program 3.
Write a program
which will print a rectangle consisting of asterisks. The user will input the height and width of the rectangle. For example, if the user enters a height of 5 and a width of 3
the program will output:
***
***
***
***
***
Lab Homework:
1. Write a program which will print an
isosceles triangle consisting of asterisks.
The user will input the height of the triangle. The triangle of height 3 is shown below:
*
***
*****
2. Extra Credit: Write a program which will print a diamond shape consisting of
asterisks. The user will input the
“size” of the diamond. The first three
diamonds (size 1, 2, and 3) are shown below:
size = 1: *
size = 2: *
***
*
size = 3: *
***
*****
***
*