vendredi 5 février 2016

C programming, if statements (large to small integer swap)

I have been working on getting code to put 3 numbers in ascending and then descending order. However, the code skips the if statements and assumes that the numbers are in order. This is my first time using if statements in C and my second day of learning pointers so any help would be appreciated. Thank you

#include<stdio.h>
void swap(int *, int *, int *);
int main(void){

printf("Please enter the first number to sort: ");
scanf("%d",&numberOne);

printf("Please enter the second number to sort: ");
scanf("%d",&numberTwo);

printf("Please enter the third number to sort: ");
scanf("%d",&numberThree);

//swap

swap(&numberOne, &numberTwo, &numberThree);

//return results

printf("The three numbers in descending order is: %d, %d, %d", 
numberOne, numberTwo, numberThree);

printf("THe three numbers in ascending order is: %d, %d, %d", 
numberThree, numberTwo, numberOne);
}

void swap(int *numberOne, int *numberTwo, int *numberThree){
if (numberOne>numberTwo){
if (numberTwo<numberThree){
int temp =*numberTwo;
*numberTwo=*numberThree;
*numberThree = temp; }
// "312"

else if (numberTwo>numberOne){
    if (numberOne>numberThree){
    int temp =*numberOne;
    *numberOne =*numberTwo;
    *numberTwo= temp;
    // "231"
}
    else if(numberOne<numberThree){
    if(numberTwo>numberThree){
    int temp =*numberOne;
    *numberOne =*numberTwo;
    *numberTwo =*numberThree;
    *numberThree = temp;
    // "132"
    }
    }
}
else if (numberThree > numberOne){
    if (numberTwo< numberOne){
    int temp =*numberThree;
    *numberThree =*numberTwo;
    *numberTwo =*numberOne;
    *numberOne = temp;
    // "213"
}
else {
    int temp = *numberThree;
    *numberThree = *numberOne;
    *numberOne = temp;
    // "123"
    }
}

}
else{
printf("Look at that these numbers were in order...");
}
}

Aucun commentaire:

Enregistrer un commentaire