I would like to know if anyone of you has an idea of how I could choose the values in order to not to have the for loop repeated for every input. Thank you in advance.
#include <iostream>
using namespace std;
int main()
{
int a, b, c, d, e, f, g, h, i;
std::cout << "Please enter a number from 1 to 8: ";
std::cin >> i;
std::cout << "The value you entered is " << i;
std::cout << "\n";
if (0 <= i <= 8) {
if (i == 8) {
for (a = 1; a <= 8; a )
{
std::cout << "\n";
for (c = 7; c >= a; c--) {
std::cout << " ";
}
for (b = 1; b <= a; b ) {
std::cout << "#";
}
}
}
else if (i == 7) {
for (a = 2; a <= 8; a )
{
std::cout << "\n";
for (c = 7; c >= a; c--) {
std::cout << " ";
}
for (b = 1; b <= a; b ) {
std::cout << "#";
}
}
}
else if (i == 2) {
for (a = 7; a <= 8; a )
{
std::cout << "\n";
for (c = 7; c >= a; c--) {
std::cout << " ";
}
for (b = 1; b <= a; b ) {
std::cout << "#";
}
}
}
}
return 0;
}
Here I would like to put all the loops together, meaning I dont have to type in the same loop for every integer
CodePudding user response:
First, let me point out that this does not mean what you think it does:
if (0 <= i <= 8)
In C , you need to write it like this:
if (0 <= i && i <= 8)
Now on to your loops. You wrote out three loops, for the cases where i
is 8, 7, and 2, but I assume you also wants loops for the other acceptable values of i
.
The only differences between your loops are what i
must be and what a
starts at:
i |
initial a |
---|---|
8 | 1 |
7 | 2 |
2 | 7 |
What is the relationship between i
and the initial a
here? I notice that i a == 9
in all three cases. So we can compute a = 9 - i
.
if (0 <= i && i <= 8) {
for (a = 9 - i; a <= 8; a ) {
std::cout << "\n";
for (c = 7; c >= a; c--) {
std::cout << " ";
}
for (b = 1; b <= a; b ) {
std::cout << "#";
}
}
}