I have asked this question before, but the code I was given does not continue re
ID: 3730426 • 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 the numbers they've entered prior to the negative number. to the output file.
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
Note: The condition used down there counts the no. of entries before negative no. is entered. And that count(i.e. fcount) is used in the for loop to print numbers in display_all_numbers() function.
#include<iostream.h>
#include<stdlib.h>
void read_data_function();
void display_numbers();
void display_all_numbers();
int stack[50],top=-1,i, count=0, fcount=0;
void read_data_function()
{
for(i=0;i<50;i++)
{
top++;
cin>>stack[i];
count++;
if(stack[i]<0 && fcount==0) /* this is the condition you needed to count the the number of entries before negative number is entered */
{
fcount=count;
}
}
}
void display_numbers()
{
cout<<" ";
cout<<"displaying all numbers you entered prior to negative number"<<" ";
for(i=0;i<fcount-1;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--;
}
}
void main()
{
system("cls");
read_data_function();
display_numbers();
top++;
display_all_numbers();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.