Hi, I'm new to programming and I came accross this code online. But when I complied it, and enter, eg. 100, the program will keep continuing until i manually close it
#include <iostream>
usingnamespace std;
int display (char, int);
int main()
{
char ch;
int n, amount, total = 0, space = 0, character = 0;
bool flag = true;
cout << "Please enter the amount of non-whitespace characters \nyou would like to have appear:" << endl;
cin >> amount;
while (total < amount && flag == true)
{
space = 0;
while (character < 10 && flag == true)
{
character ++;
if ((amount - total)< character)
{
character = (amount - total);
flag == false;
}
if (amount == total)
{
break;
}
ch = ' ';
display (ch, space);
space ++;
ch = '*';
display (ch, character);
total += character;
if (flag == false || character >= 10)
{
break;
}
}
if (amount == total || flag == false)
{
break;
}
if (space != 9)
space = 9;
while (character != 0 && flag == true)
{
if ((amount - total) < character)
{
character = (total - amount);
flag == false;
}
if (amount == total)
{
break;
}
ch = ' ';
display (ch, space);
space --;
ch = '+';
display (ch, character);
character --;
total += character;
if (flag == false || character >= 10)
{
break;
}
}
}
system ("pause");
}
int display (char ch, int n)
{
int index = 0;
while (index < n){
cout << ch;
index ++;
}
if (ch == '*' || ch == '+')
cout << endl;
}
For 56 I assume it is supposed to print one '+' character but it doesn't, so study why it doesn't display a '+' even though character is 10 when the following while loop starts.
Also, it doesn't make sense to decrement character before adding it to total since then total will be out of sync with the characters displayed.
1 2 3 4 5 6 7 8 9
while (character != 0 && flag == true)
{
//...
ch = '+';
display (ch, character);
character --; // move this after the following line.
total += character;
//...
}