Reputation:
I'm trying to make a program that will request a string from the user and transform it into a letter pyramid (example below).
Ex: If the user enters the string "12345" the program should display:
1
121
12321
1234321
123454321
My code is as follows: (I'm not done yet)
#include <iostream>
#include <string>
using namespace std;
int main()
{
//gets input
cout << "Enter the string you would like to be processed" << endl;
string input;
cin >> input;
//bottom layer = bottommost layer on the pyramid | element amount = elements in any given layer. | layerNum is to determine which layer computer is on
int bottomLayer = input.size();
int elementAmount;
int layerNum;
//layerNum keeps track of the pyramid layer the loop is currently on. 1 is the top, bottom = the string's length
for (layerNum = 1; layerNum <= bottomLayer; layerNum++)
{
//signifies the amount of elements in a given layer. eg: for layer 2, the amount of elements would be 2*2-1=3
elementAmount = layerNum * 2 - 1;
//this loop prints the numbers up to where the order reverses
for (int strElement = 0; strElement < layerNum; strElement++)
{
cout << input.at(strElement);
}
//starts on the first reverse letter to be printed and prints the rest
for (int strElement = layerNum - 2; strElement < elementAmount; strElement--)
{
cout << input.at(strElement);
}
}
}
The console window opens up as expected, and I can input my string. However, after I do so, it returns the first letter and an error pop-up appears:
Debug Error!
abort() has been called
Other than this, there are no error messages or even warnings. For one execution, there was a warning about comparing unsigned ints at line 28, which is this:
for (layerNum = 1; layerNum <= bottomLayer; layerNum++)
But it stopped appearing after I ran the program next. Any ideas on how I can get my program to run?
Upvotes: 1
Views: 325
Reputation: 2588
There are some logical errors in second loop.
strElement
might be less than 0, because in int strElement = layerNum - 2
, layerNum
starts from 1.strElement
Element decreases by 1 every loop, so it MUST be less than zero after several rounds.strElement
> -1, so loop would be break once strElement
is less than 0.Note: > -1
might not be the correct logic. But strElement < elementAmount
once passes, loop would let the strElement
always less than 0 and run in infinite loop.
//starts on the first reverse letter to be printed and prints the rest
for( int strElement = layerNum - 2; ; strElement > -1; strElement--)
{
cout << input.at(strElement);
}
Upvotes: 2
Reputation: 3461
This loop:
for (int strElement = layerNum - 2; strElement < elementAmount; strElement--)
sometimes passes to at
the index -1 (occurs when layerNum = 1
), which would cause an error.
Upvotes: 1