# include <stdio.h>
# include <stdlib.h>
# include <time.h>
int main(){
int i, n, A[10] = {0}, B[10] = {0};
srand((unsigned)time(NULL));
printf("Shift how many elements? ");
scanf("%d", &n);
for (i = 0; i < 10; i++){
A[i] = rand()%10;
printf("%d ", A[i]);
}
printf("\n\n\n");
for (i = 0; i < 10; i++){
B[i + n] = A[i]; *******
}
for (i = 0; i < 10; i++){
printf("%d ", B[i]);
}
return 0;
}
I'm trying to write a code that shifts the numbers in the array by a value entered by the user but I really don't know how to deal with the indexing, if the number is at the end and you add number to it it might go outside the array so how do i prevent that. Pay attention to the line with asterisks. If you can, please give me a brief explanation of array indexing while coding, or hints about what I can do to fix this. I know my mistake however, I just don't know how to fix it.
This language is C and I'm using code::blocks. Thank you!
-
1Sounds like you're looking for a wraparound in the array. Just check to see if incrementing would put you past the bound, and if so, instead of incrementing, set the index equal to zero.ciphermagi– ciphermagi2014年03月22日 17:36:58 +00:00Commented Mar 22, 2014 at 17:36
2 Answers 2
You can use modulo (%) operator to get the correct indexing:
for (i = 0; i < 10; i++){
B[ (i + n) % 10 ] = A[i];
}
I have used 10 directly. In general, you should use sizeof(B) or actual number of elements in the array if it's less than size of the array.
1 Comment
You can use a wraparound condition for this.
for (i = 0; i < 10; i++){
B[i] = A[(i+n) % 10]; // to shift elements to the left by n
//B[(i+n) % 10 ] = A[i]; // to shift right
}