user2971015
user2971015

Reputation: 51

Ordering numbers in an array

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

Upvotes: 1

Views: 69

Answers (2)

haccks
haccks

Reputation: 106012

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
}

Upvotes: 1

P.P
P.P

Reputation: 121387

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.

Upvotes: 4

Related Questions