Below is my question and the code.
Write a program that will swap two values in an array. If the swap is successfull, the
program will display the updated list. If it contains any error, for example the values
are not in the list, the program will display appropriate error messages. Use related
functions to develop this program.
Example of outputs that the program must fulfill is as shown below (user input is in
bold font):
Example Output 1:
Key in value, 0 to stop: 6 8 11 35 64 0
list now : 6 8 11 35 64
value to change: 35
want to cahnge with: 8
list now: 6 35 11 8 64
Example Output 2:
Key in value, 0 to stop: 6 8 11 35 64 0
list now: 6 8 11 35 64
value to change: 35
want to cahnge with: 27
ERROR!! : no this number 27!
list now: 6 8 11 35 64
Example Output 3:
Key in value, 0 to stop: 0
list now: EMPTY LIST!
This is my code:
Expand|Select|Wrap|Line Numbers
- #include <stdio.h>
- #define max 5
- int main()
- {
- int num[max], i=0;
- int swapFromNum = 0;
- int swapToNum = 0;
- int swapFromArrIndex = 0;
- int swapToArrIndex = 0;
- bool swapFromNumFound = false, swapToNumFound = false;
- printf("Enter value, 0 to stop: \n");
- while(1)
- {
- scanf("%d", &num ); // read value
- if(num[i]==0)
- break; // if 0 finished
- i++;
- }
- printf("List now: ");
- for(i=0;i<max;i++)
- {
- printf("%d ",num[i]);
- }
- printf("\n");
- printf("Value to change:");
- scanf("%d",&swapFromNum);
- for(i=0;i<max;i++)
- {
- if(num[i] == swapFromNum)
- {
- swapFromNumFound = true;
- swapFromArrIndex = i;
- }
- }
- if (swapFromNumFound == false)
- {
- printf("ERROR!! : No this Value\n");
- }
- return main();
- printf("Want change with value:");
- scanf("%d",&swapToNum);
- for(i=0;i<max;i++)
- {
- if(num[i] == swapToNum)
- {
- swapToNumFound = true;
- swapToArrIndex = i;
- }
- }
- if(swapToNumFound == false)
- {
- printf("ERROR!! : No this value\n");
- }
- if(swapFromNumFound && swapToNumFound)
- {
- num[swapFromArrIndex] = swapToNum;
- num[swapToArrIndex] = swapFromNum;
- printf("List now: ");
- for(i=0;i<max;i++)
- {
- printf("%d ",num[i]);
- }
- printf("\n");
- }
- }
Enter value, 0 to stop:
1
2
0
List now: 1 2 0 4202500 37814140
value to change:
1. Why my output cannot stop after 0, it still auto generate the number which I didn't key in?