I have asked this question before, but the code I was given does not continue re
ID: 3730453 • Letter: I
Question
I have asked this question before, but the code I was given does not continue reading the rest of the numbers after the negative number is entered. If the user enters the negative number as the 3rd number, I don't want the loop to stop there before they get to enter all 50 numbers. After they have entered all 50 numbers including the negative number, I want to then display all 50 numbers and the numbers they've entered prior to the negative number. I am required to use an Array to store the numbers and an output file to show every interaction between the user and the program.
Here is the code in C++
#include<iostream>
using namespace std;
void read_data_function();
void display_numbers();
void display_all_numbers();
int stack[50],top=-1,i;
void read_data_function()
{
for(i=0;i<50;i++)
{
top++;
cin>>stack[i];
if(stack[i]<0)
{
break;
}
}
}
void display_numbers()
{
cout<<" ";
cout<<"displaying all numbers you entered prior to negative number"<<" ";
for(i=0;i<top;i++)
{
cout<<stack[i]<<" ";
}
cout<<" ";
}
void display_all_numbers()
{
cout<<"printing all numbers including negative number in a vertical line (LIFO ORDER)"<<" ";
top--;
while(top>=0)
{
cout<<stack[top]<<" ";
top--;
}
}
int main()
{
read_data_function();
display_numbers();
display_all_numbers();
return 0;
}
Explanation / Answer
#include<iostream>
using namespace std;
void read_data_function();
void display_numbers();
void display_all_numbers();
int stack[50],top=-1,i;
void read_data_function()
{
for(i=0;i<50;i++)
{
top++;
cin>>stack[i];
}
}
void display_numbers()
{
cout<<" ";
cout<<"displaying all numbers you entered prior to negative number"<<" ";
for(i=0;i<top;i++)
{
cout<<stack[i]<<" ";
}
cout<<" ";
}
void display_all_numbers()
{
cout<<"printing all numbers including negative number in a vertical line (LIFO ORDER)"<<" ";
top--;
while(top>=0)
{
cout<<stack[top]<<" ";
top--;
}
}
int main()
{
read_data_function();
display_numbers();
display_all_numbers();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.