In: Computer Science
In C, take the following programming that initializes 2 arrays and swaps them and displays the initial input and output and modify it so that it uses different functions for the swapping and printing, so that the main method only has variables and function calls.
#include<stdio.h> int main() { const int n = 5; int firstArray[n], secondArray[n]; int i, k=0, temp; for(i=0, k=0; k<n; i+=2, k++){ firstArray[k] = i; secondArray[k] = i+1; } printf("Before Swap\n"); for(i=0; i<n; i++) { printf("firstArray[%d] = %d, secondArray[%d] = %d\n", i, firstArray[i], i, secondArray[i]); } //swapping for(i=0; i<n; i++) { temp = firstArray[i]; firstArray[i] = secondArray[i]; secondArray[i] = temp; } printf("After Swap\n"); for(i=0; i<n; i++) { printf("firstArray[%d] = %d, secondArray[%d] = %d\n", i, firstArray[i], i, secondArray[i]); } return 0; }
CODE
#include<stdio.h>
void swap(int *firstArray, int *secondArray, int n) {
for(int i=0; i<n; i++)
{
int temp = firstArray[i];
firstArray[i] = secondArray[i];
secondArray[i] = temp;
}
}
void print(int firstArray[], int secondArray[], int n) {
for(int i=0; i<n; i++)
{
printf("firstArray[%d] = %d, secondArray[%d] = %d\n", i, firstArray[i], i, secondArray[i]);
}
}
int main()
{
const int n = 5;
int firstArray[n], secondArray[n];
int i, k=0, temp;
for(i=0, k=0; k<n; i+=2, k++){
firstArray[k] = i;
secondArray[k] = i+1;
}
printf("Before Swap\n");
print(firstArray, secondArray, n);
swap(firstArray, secondArray, n);
printf("After Swap\n");
print(firstArray, secondArray, n);
return 0;
}