Files

53 lines
1.8 KiB
C
Executable File

/*
In this task, you should implement a function that swaps two elements in an existing array. The main function is already predefined. Your task is:
Add the user input to the main function by reading the first and second index from user input and write it into the array indices-array. indices[0] should contain the first user input. indices[1] should contain the second user input. You can use scanf for this operation. The two user inputs define the indices of the two elements that should be switched in the array.
Write a function called swapTwoNumbers(). The function takes 3 arguments: i) the array of numbers, ii) the size of the array as int, and iii) the array where the two indices to swap are stored. The function should check if the indices are valid in the current array. If one or both indices are invalid the function should return 1. Otherwise the elements in the array should be swapped and the function should return 0.
The provided main function prints the array or an error message, if the user enters invalid indices.
This is an example:
0
4
5 2 3 4 1
*/
#include <stdio.h>
#define SIZE 5
// TODO: add your function swapTwoNumbers()
int swapTwoNumbers(int array[], int size, int indices[]);
int main(void)
{
int my_array[SIZE] = {1,2,3,4,5};
int size = sizeof(my_array) / sizeof(my_array[0]);
int indices[2] = {-1, -1};
scanf("%d",&indices[0]);
scanf("%d",&indices[1]);
int failed = swapTwoNumbers(my_array, size, indices);
if (failed)
{
printf("Indices out of range\n");
return 0;
}
for (int i = 0; i < SIZE; i++)
{
printf("%d ", my_array[i]);
}
return 0;
}
int swapTwoNumbers(int array[], int size, int indices[])
{
if (indices[1] >= size){return 1;}
int placeholder = array[indices[0]];
array[indices[0]] = array[indices[1]];
array[indices[1]] = placeholder;
return 0;
}