Don't feel alone. I feel in awe myself, when I see some replies from the pro's.
]This is my current code. The original numbers are displaying fine. The ascending numbers are not. Only four of the numbers are being displayed and the number 12 is appearing twice. Any advice?
Oh! this is C++!! That might change things.
Looks like it might be OK, but that's a dodgy practice.
Code:
#include "stdafx.h"
int main (void)
{
/*You may want to set the A array to all zero's to start with */
int A[[] = { 0 };
/* instead of these assignments to the array */
int A[5] = {27, 12, 2, 44, 35};
/*idx array must be initialized in order, either this way, or (more
commonly), through a loop.
*/
int idx[5] = {0,1,2,3,4,}; //A=main Array, idx= index int
int j;
int i;
int temp;
/* Original Order*/
printf("\nAscending\tOriginal\tDescending\n");
for(i = 0; i < 5; i++)
printf("\t\t %d\n", A[i]);
/*
This is the problem - you have combined the sorting, with the display.
The code looks fine, but you have to do the sorting of the index
*first*, and *then* do the display.
*/
/* Ascending order */
for(i = 0; i < 5 - 1; i++) {
for(j = i + 1; j < 5; j++) {
if(A[i] > A[j]) {
temp = A[idx[i]];
A[idx[i]] = A[idx[j]];
A[idx[j]] = temp;
/* ==========> none of this yet: printf("%d\n", A[idx[i]]); */
}
}
}
/*NOW print the ascending order */
for(i = 0; i < 5; i++)
printf("\n %d", A[idx[i]]);
/*
You have to print the ascending order, before you do the resort
for descending order, because we're re-using the same indexes.
*/
/* Descending order */
for(i = 0; i < 5 - 1; i++) {
for(j = i + 1; j < 5; j++) {
if(A[i] < A[j]) {
temp = A[idx[i]];
A[idx[i]] = A[idx[j]];
A[idx[j]] = temp;
/* Delete this line=====>printf("\t\t\t\t%d\n", A[idx[i]]); */
}
}
}
//For descending order, change this:
if(A[i] < A[j]) {
to
if(A[i] > A[j] {
//and print it just like the ascending order.
return 0;
}
Yes, you can enter the integers any way you want - scanf() is fine for careful use, but scanf() won't handle wrong input well in the real world.
Usual loop might be something like:
Code:
for(i = 0; i < 5; i++) {
printf("Enter number %d: ", i);
scanf("%d", &A[i]);
printf("Enter another number (y/n)? ");
scanf(" %c", &yesno);
if(yesno == 'n' || yesno == 'N')
break;
yesno = getchar(); //pull the newline char off the keyboard buffer
}
I haven't run any of this code, so it might have a bug in it - but it will be very close.