Rewrite this program using pointer arithmetic and eliminate the loop index varia
ID: 3729457 • Letter: R
Question
Rewrite this program using pointer arithmetic and eliminate the loop index variables and all use of the [] operator in the roll function.
As part of the solution, write and call the function roll() with the following prototype. The roll function should roll the first three elements of the array a1 by moving the third element of the array to the first in the output array a2. void roll(int *a1, int n, int *a2)
The roll() function should use pointer arithmetic – not subscripting – to visit array elements. In other words, eliminate the loop index variables and all use of the [] operator in the function.
3) In the main function, ask the user to enter the length of the array, declare the array with the length, read in the values for the array and call the roll function. The main function should display the result.
#include<stdio.h>
// Prototype
void roll(int *a1, int n, int *a2);
void main() {
// Store size of array;
int size;
printf("Enter the size of array ");
// Input size of array
scanf("%d",&size);
// Making two array.
int a1[size], a2[size];
// fill a1 with user input.
for(int i=0; i < size; i++) {
scanf("%d",&a1[i]);
}
printf(" ");
// print a1 for testing and checking correctness.
for(int i=0; i < size; i++) {
printf("%d ",a1[i]);
}
printf(" ");
// calling roll function
roll(a1,size,a2);
printf(" ");
}
void roll(int *a1, int n, int *a2) {
// roll function login
for(int i=0; i < n; i++) {
if(i == 0)
a2[i] = a1[2];
else if(i == 1)
a2[i] = a1[0];
else if(i == 2)
a2[i] = a1[1];
else
a2[i] = a1[i];
}
// printing array
for(int i=0; i < n; i++) {
printf("%d ",a2[i]);
}
}
Explanation / Answer
#include<stdio.h>
// Prototype
void roll(int *a1, int n, int *a2);
void main() {
// Store size of array;
int size;
printf("Enter the size of array ");
// Input size of array
scanf("%d",&size);
// Making two array.
int a1[size], a2[size];
// fill a1 with user input.
for(int i=0; i < size; i++) {
scanf("%d",&a1[i]);
}
printf(" ");
// print a1 for testing and checking correctness.
for(int i=0; i < size; i++) {
printf("%d ",a1[i]);
}
printf(" ");
// calling roll function
roll(a1,size,a2);
//printing the result
for(int i=0; i < size; i++) {
printf("%d ",*(a2+i));
}
printf(" ");
}
void roll(int *a1, int n, int *a2) {
// roll function login
for(int i=0; i < n; i++) {
if(i == 0)
*(a2+i) = *(a1+2);
else if(i == 1)
*(a2+i) = *(a1+0);
else if(i == 2)
*(a2+i) = *(a1+1);
else
*(a2+i) = *(a1+i);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.