Iterating an Array

Hello. I am new to C++. I've completed about five exercises discussing loops, logic, and arrays. I came to the final exercise of the chapter and became stuck.

The Exercise: Ask the User to input Ten random integers and store them in an array. Sort the integers in ascending order using the selection sort and output the sorted array.

The Problem: The algorithm for the selection sort is simple. I just can't seem to figure out how to scan the array for the lowest value integer. I'm not asking for the entire solution. Just the idea behind scanning the array. I would like to figure most out on my own but this is a stone in my path some extra hands could help move.
Use a for loop to loop over the an index variable (which is the index that you are checking).
How would I check the element of the the array?

So far for the loop. I understand I would have to check each element one by one, but how do I compare each element to the others?

for(int i = 0; i <= 9; ++i)
{


}

i being the counter variable for the loop.
Last edited on
Well, one way you could do it is have a secondary index variable that holds the index of the highest number you have found so far, then just update it if you can find a bigger one.

Btw, your for loop isn't correct. You have I going from 9 to 9 currently.
Fixed the loop to go from x[0]-x[9]. Thank you for that. Typos can kill.

Are you saying:

for(int i = 0; i <= 9; ++i)
{
for(int j = 0; j > x[i]; ++j)
{
//TODO
}
}

Last edited on
I got it. Just looked through material for sorting. Other people on forum had same question. Should have searched before I posted. Not the way I wanted, but it works.


// Exercise 2.7

#include "stdafx.h"


/*This is the funtion entertoExit();. It ask the user to press enter to exit.
It should only be used right before the return at the end of main.*/
void entertoExit()
{
std::cout << "\nPress the enter key to exit";
std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);
}
int _tmain(int argc, _TCHAR* argv[])
{
int enteredArray[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};


cout << "Please enter a random integer: ";

for(int i = 0; i <= 9; ++i)
{
cout << endl;

cout << "[" << i << "] ";
cout << "= ";
cin >> enteredArray[i];
cout << endl;



}
for (int i=0; i <= 9; ++i)
{
cout << " " << enteredArray[i] << " " ;
}

cout << endl;
cout << "Sorting..." << endl;


sort (enteredArray, enteredArray+9, less<int>() );

for (int i=0; i <= 9; ++i)
{
cout << enteredArray[i] << ", ";
}


entertoExit();
return 0;
}

Topic archived. No new replies allowed.