Thursday, July 9, 2009

C++ array update help?

How do you write a function that will update an array.


for example: if i have "int x[20]" as my array and when a question prompted asking "Enter new digit" then store the new digit in the array x[1] following the array x[0]. And if i want the questions to loop and keep asking me to enter new digit and store it x[2], x[3], etc respectively. How should i write a function that will keep updating the array. The digit in those particular arrays only can be use once and it can not be change.





again, how do i write a function that indicate an invalid digit or an used digit if i store a digit in a used array?





for example (not sure if its right)


while "new digit" is equal to the array digit that i first stored in, prompt a message saying the digit has been use and try again.





And another thing, how do you write a function to test if the digit in the particular array is true and if its not, prompt a message saying digit not use yet.





please help me. im stuck

C++ array update help?
This should do the trick.





void main()


{


int array[20];


bool bExists;





for( int i=0; i%26lt;sizeof(array)/sizeof(int); i ++)


{


do {


cin %26gt;%26gt; array[i];


bExists = false;


for( int j=0; j%26lt;i; j ++)


{


if( array[i] == array[j] )


{


bExists = true;


cerr %26lt;%26lt; "Digit already in use";


break;


}


}


} while( bExists );


}


}
Reply:Let's use your example where you have int x[20]; You can use another variable, int index = 0; to specify where it should start inserting numbers, each time you insert a number set the array value at index to the value and increment index:





const int ARRAY_SIZE = 20;


int x[ARRAY_SIZE];


int index = 0;





int newDigit;





// get the digit here





x[index++] = newDigit;


if (index == ARRAY_SIZE)


{


// tell user they can't add anything else here


}


No comments:

Post a Comment