1
# 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!

asked Mar 22, 2014 at 17:34
1
  • 1
    Sounds 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. Commented Mar 22, 2014 at 17:36

2 Answers 2

4

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.

answered Mar 22, 2014 at 17:40
Sign up to request clarification or add additional context in comments.

1 Comment

That's very clever, it didn't occur to me.
1

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
}
answered Mar 22, 2014 at 17:40

2 Comments

You don't really need the conditional if you're using a modulo.
@ciphermagi; Yes. You are right. I don't know why I did this :P

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.