Suppose you want to define a function that outputs a multiplication table for the values from 1 to 6. A good way to start this is to write a simple loop that prints the multiples of a specific number (say 2) all on one line.
|
|
The first line initializes a variable named j, which is going to act as
our loop variable.
As long as j is less than or equal to 6, the loop repeats, and the value
of j increases at each iteration, so it stops when j = 7.
Each iteration through the loop, the value j is output to the console,
followed by a tab mark.
By omitting the endl from the first output statement, all the
output is on a single line.
So far, so good. The next step is to put ALL THIS CODE into another loop in order to get multiple rows to print. To do this, instead of using "2" in the output statement, we will use another variable called i:
int i = 1;
while (i <= 6) {
int j = 1;
while (j <= 6) {
cout << i*j << "\t";
j = j + 1;
}
i = i + 1;
cout << endl;
}
|
****** * * * * * * * * ****** |
int i = 1;
while (i <= 6) {
if (i==1 || i==6) {
cout << "******" << endl;
}
else {
cout << "* *" << endl;
}
i = i + 1;
}
|
cout << "******" << endl; // output top line
int i = 1;
while (i <= 4) {
cout << "* *" << endl;
i = i + 1;
}
cout << "******" << endl; // output bottom line
|
You are to design a program that will output diamonds onto the console.
* * * * * * * * * * * *If the input size is 2, your output should appear like:
* * * *If the input size is 1, your output should appear like:
*
| HINT: | Try to use variables to keep track of how many spaces you will need. |
|---|
Be sure to:
// Course: CSC 306 Introduction to Programming with C++
// Name: Your Name
// Lab #5: Using loops to output diamonds
/* Put what your program does here */