Hunali
Hunali

Reputation: 277

How to shift an array elements by n places in C

If we have an array, for example, Arr[] = {1,2,3,4,5} and I want to shift the elements by 2, how can I do that? the the array should be: {3,4,5,1,2}. I tried to slove this way:

#include <stdio.h>

int main(void) {
  int broj,pom,i,niza1[10],niza2[10],raz,tem=0,rest=0;

  scanf("%d%d",&broj,&pom);//broj= number of elements and pom=shifting
  for (int i=0;i<broj;i++){
    scanf ("%d",&niza1[i]);
  }
  raz=broj-pom;//difrence between thenumber of elements and shifting
    for (int i=raz;i<=broj;i++){
      niza2[tem]=niza1[i-1];
      tem++;

    }
       for (int i=0;i<broj;i++){
      printf("%d",niza2[i]);
      }

    return 0;
}

input: 5 2 1 2 3 4 5 resault: 3 4 5 0 0

How can I add the last two numbers inside the array?

Upvotes: 2

Views: 285

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

You are only copying broz - raz elements into new array.

  raz=broj-pom;//difrence between thenumber of elements and shifting
    for (int i=raz;i<=broj;i++){
      niza2[tem]=niza1[i-1];
      tem++;

    }

should be

  1. I removed unnecessary tem variable.
  2. (i+raz)%broj you need % to wrap the copying.

    raz=broj-pom;//difrence between thenumber of elements and shifting
    for (int i=0;i<broj;i++){
      niza2[i]=niza1[(i+raz)%broj];
    }
    

Upvotes: 2

Related Questions