4 Replies - 1621 Views - Last Post: 02 January 2015 - 11:51 AM Rate Topic: -----

#1 vsg24   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 34
  • Joined: 02-January 15

Shifting elements in an array in C

Posted 02 January 2015 - 09:59 AM

Hi,

Let's say I have an array of 10 elements. I want user to enter 9 numbers so that they fill arrays 0 to 8 (9 numbers).
Now I shift the arrays +1. so array[0] is now array[1] and so on.
Now I ask user to enter 10th number (fills array 0).

how can I do that??

Here's my code(it doesn't shift arrays and doesn't ask for 10th num)

#include <stdio.h>
 
 
int main()
{
    int a[10];
    int i;
 
 
    printf("\nEnter 9 numbers:\n");
 
 
for(i=0;i<9;i++)
{
    printf("%10d numbers remaining\n\n", 9-i);
    scanf("%d", &a[i]);
}
 
 
printf( "%s%13s\n", "Element", "Value" );
for(i=0;i<10;i++)
{
    printf("%7d%13d\n",i, a[i]);
}
 
 
}


Is This A Good Question/Topic? 0
  • +

Replies To: Shifting elements in an array in C

#2 snoopy11   User is offline

  • Engineering ● Software
  • member icon

Reputation: 1556
  • View blog
  • Posts: 4,930
  • Joined: 20-March 10

Re: Shifting elements in an array in C

Posted 02 January 2015 - 10:21 AM

Well,

the simplest way would be to have a temporary value call it

'int temp'

read a[8] into temp

let a[9] equal temp

read a[7] into temp

let a[8] equal temp

read a[6] into temp

let a[7] equal temp

etc etc...

then for the final number input that tenth number into a[0]

Regards

Snoopy.
Was This Post Helpful? 0
  • +
  • -

#3 CTphpnwb   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3839
  • View blog
  • Posts: 14,003
  • Joined: 08-August 08

Re: Shifting elements in an array in C

Posted 02 January 2015 - 10:23 AM

You'll want to either swap individual elements, or you could get a bit fancier and use memcpy.

Read the links and see what you can come up with.
Was This Post Helpful? 0
  • +
  • -

#4 Salem_c   User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 2463
  • View blog
  • Posts: 4,614
  • Joined: 30-May 10

Re: Shifting elements in an array in C

Posted 02 January 2015 - 11:44 AM

Cross-posted here -> http://cboard.cprogr...ts-array-c.html
Was This Post Helpful? 0
  • +
  • -

#5 vsg24   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 34
  • Joined: 02-January 15

Re: Shifting elements in an array in C

Posted 02 January 2015 - 11:51 AM

Problem solved. thanks.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1