Hi.
i am working on a code in where the add_values selection will allow the user to enter numbers into an array.
My question is : how can i change my code so that this function must ensure that if the user only enters a few numbers, leaves to access a different
menu choice, then returns to enter more numbers, that previously stored values are not overwritten
#include <iostream>
usingnamespace std;
#define array_max_size = 10
void Display_menu();
void Add_values();
void Edit_values();
void Print_values();
void Display_Stats();
void Quit_program();
float stored_values[10];
int element_to_change;
int max();
int min();
int main()
{
cout << " Hello please choose a option! " << endl;
Display_menu();
cout << " thanks for using my program" << endl;
return 0;
}
void Display_menu()
{ int n;
//float (num_array)[array_max_size] = {10};
{
cout << " 1 - Add Values " << endl;
cout << " 2 - Edit Values " << endl;
cout << " 3 - Print Values " << endl;
cout << " 4 - Display Statistics " << endl;
cout << " 5 - Quit Program " << endl;
cin>>n;
{ if (n<0 || n>5)
cout << "not a menu item" << endl;
else
{
if (n==1){Add_values();}
if (n==2){Edit_values();}
if (n==3){Print_values();}
if (n==4){Display_Stats();}
if (n==5){Quit_program();}
}
}
}
return Display_menu();
}
void Add_values()
{
cout<<"You selected option 1 to Add values"<<endl;
cout<<"Please enter 10 numbers between -999 and 999 and number outside this range will cause the program to terminate" << endl;
cout<<"Enter -1000 to exit this function" << endl;
for(int i=0; i<10; ++i)
{
if(stored_values[i]<-999||stored_values[i]>999)
{
cout<< " Please try again " << endl;
cout<< " Enter a number between -999 and 999" << endl;
}
else
{
cout<< "What number would you like to enter?" << endl;
cin>> stored_values[i];
}
if(stored_values[i]==-1000){ break;}
cout<< "You have entered value of ["<< i << "]"<<" is: "<<stored_values[i]<<endl;
}
}
You could have a counter variable that updates as data is input. Make sure the counter has scope outside the menu. It doesn't need to be global though, more than likely.
main(){
int counter = 0;
go to some_function(&counter) //counter is zero
do other_stuff //counter is updated a couple of times say
...
go to some_function(&counter) // counter is now 3 say so element 4 goes in
...
}
In short the counter keeps track of the last position in the list/array
some_function(&counter)
{
add new element
element [counter] = xyz
increment counter
}