write a program that will ask the user to input the size of an array of numbers. the user will then be asked to enter a number for each index of the array.the program must:
a) sort all the elements of the array
b) give the first position of a designated number within the array
your main program should implement the above.you must use pointers
This seems like a homework assignment to me :). That's really no problem. I'll help get you started; hopefully you'll have a clearer idea of what to do from there.
This problem really isn't too complicated. We'll need to create our array based on a number we grab from the user (I'm assuming standard cin and cout will do here). Grab that number, and store it in a variable (we'll call it iSize). Then we create our array like this:
int * intArray = new int [iSize];
Actually, there are a couple different ways to manage the creation of an array. If your professor uses a different one in class, I recommend following his/her instructions. Next we'll want to prompt the user for all the numbers. At this point, you probably know about for loops, and that we can use them to repeat a task any number of times. You'll want to set your loop up like this:
for (int i = 0; i < iSize; i++)
// This will be where your prompts live. Think intArray[i].
Next we'll sort all the elements (assuming your teacher wants each function separated). This shouldn't be too tricky, as long as you remember this four step method:
1. Compare two numbers, if Second is bigger than First:
2. Store the contents of First in a temporary variable
3. Store the contents of Second in First
4. Store the contents of the temporary variable in Second
That switches any two numbers in an array. Next we'll think about how to find the position of a number in the array. I'm not sure how your teacher wants you to use pointers, but it might be helpful use them here. Remember, every element of an array is technically a pointer. Therefore, if I say intArray; I'm getting a pointer to the third element in the array (remember, we start with zero).
We'll want to use a while loop for item B. That will let us iterate until we find our number. After prompting the user for the number, do something like the following:
int check = 0;
While ((intArray[check] != designatedNum)&&(check <= iSize)
That will test the condition for all the items, but if the item is not found, we won't get stuck in an infinite loop. I'm sure you can figure out the output to indicate whether we've found our number, and where.
Thanks for the question, and good luck!