Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
this c program to shift the array elements is not working. Plz help.(i have given the code as an answer, instead of in details)?

5 Answers
- 3 years ago
p[5]={1,2,3,4,5};
In temp you are storing the 4th value, that's fine.
Now you start the shifting process from the 3rd cell to the 4th, then from 2nd cell to the 3rd and so on upto 0th cell to the 1st.
Then you copy temp to the 0th cell.
#include<stdio.h>
void main()
{
int temp,i,p[5]={1,2,3,4,5};
temp=p[5-1];
for(i=3;i>=0;i--)
p[i+1]=p[i];
p[0]=temp;
for(i=0;i<5;i++)
printf("%d",p[i]);
}
- ?Lv 53 years ago
Break the for loop down an look at what it is actually doing:
for (i=0; i< 5; i++) p[i+1]=p[i];
First time through:
i = 0, so you have p[1]=p[0], which overwrites the value of p[1] (i.e. 2) with the value of p[0] (i.e. 1).
Second time through:
i is 1, so p[2]=p[1], remember first time through p[1] was set to 1. so not both p[1] and p[2] will be set to 1.
etc.
Since you save the value of p[4] in temp, it looks like the intent of the code was to do:
temp = p[4]
then in the loop
p[4] = p[3]
p[3]=p[2]
p[2]=p[1]
p[1]=p[0]
then after the loop
p[0] = temp
You just have to play around with the for loop index to make that happen.
- Anonymous3 years ago
You've started at the wrong end of the array.
Your program will fill the array with whatever is in p[0].
- husoskiLv 73 years ago
If you want to shift right, you need to loop from right to left. Your current code copies p[0] to p[1], overwriting p[1] before it gets copied to p[2], and so on. That loop sets the entire array to the original contents of p[0]. (The final assignment gets the old value of p[5-1] correctly copied to p[0] because that value was preserved in the temp variable.)
Try this loop instead:
for (i=5-1; i>0; --i) /* loop from 4 down to 1 */
{ p[i] = p[i-1]; }
Step through that by hand and the assignment statements will execute in this order:
p[4] = p[3];
p[3] = p[2];
p[2] = p[1];
p[1] = p[0];
- How do you think about the answers? You can sign in to vote the answer.
- 3 years ago
Code in question:
#include<stdio.h>
void main()
{
int temp,i,p[5]={1,2,3,4,5};
temp=p[5-1];
for(i=0;i<5;i++)
p[i+1]=p[i];
p[0]=temp;
for(i=0;i<5;i++)
printf("%d",p[i]);
}



