C Exercise 68
100 Classic C Language Examples
**Problem:** Given n integers, shift the preceding numbers back by m positions in order, so that the last m numbers become the first m numbers.
**Program Analysis:** You can use an auxiliary array to store the elements that need to be moved, then move the elements to the correct positions as required.
Example 1
#include
// Implement the movement of array elements through the shiftArray function.
void
shiftArray
(
int
arr
[
]
,
int
n
,
int
m
)
{
int
temp
[
m
]
;
// Save the last m numbers to a temporary array
for
(
int
i
=
n
m
,
j
=
0
;
i
<
n
;
i
++,
j
++
)
{
temp
[
j
]
=
arr
[
i
]
;
}
// Move the preceding n-m numbers back by m positions
for
(
int
i
=
n
m
1
;
i
=
0
;
i
--
)
{
arr
[
i
m
]
=
arr
[
i
]
;
}
// Put the numbers from the temporary array at the very front
for
(
int
i
=
0
;
i
<
m
;
i
++
)
{
arr
[
i
]
=
temp
[
i
]
;
}
}
// In the main function, get the array and the shift position from the user, call the shiftArray function, and finally output the shifted array
int
main
(
)
{
int
n
,
m
;
printf
(
"Please enter the number of integers n:"
)
;
scanf
(
"%d"
,
&
n
)
;
printf
(
"Please enter the position m to shift back:"
)
;
scanf
(
"%d"
,
&
m
)
;
int
arr
[
n
]
;
printf
(
"Please enter %d integers:"
,
n
)
;
for
(
int
i
=
0
;
i
<
n
;
i
++
)
{
scanf
(
"%d"
,
&
arr
[
i
]
)
;
}
shiftArray
(
arr
,
n
,
m
)
;
printf
(
"The shifted array:"
)
;
for
(
int
i
=
0
;
i
<
n
;
i
++
)
{
printf
(
"%d "
,
arr
[
i
]
)
;
}
printf
(
"\n"
)
;
return
0
;
}
Example 2
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
#include
<
stdlib.h
int
main
(
)
{
int
arr
[
20
];
int
i
,
n
,
offset
;
// Input the array size and array contents
printf
(
"
Total numbers?
\
n
"
)
;
scanf
(
"
%d
"
,&
n
)
;
printf
(
"
Input %d numbers.
\
n
"
,
n
)
;
for
(
i
=
0
;
i
<
n
;
i
++
)
scanf
(
"
%d
"
,&
arr
[
i
]
)
;
// Input the rotation offset
printf
(
"
Set your offset.
\
n
"
)
;
scanf
(
"
%d
"
,&
offset
)
;
printf
(
"
Offset is %d.
\
n
"
,
offset
)
;
// Print the array before rotation
print_arr
(
arr
,
n
)
;
// Rotate the array and print it
move
(
arr
,
n
,
offset
)
;
print_arr
(
arr
,
n
)
;
}
// Print the array
void
print_arr
(
int
array
[
]
,
int
n
)
{
int
i
;
for
(
i
=
0
;
i
<
n
;++
i
)
printf
(
"
%4d
"
,
array
[
i
]
);
printf
(
"
\
n
"
)
;
}
// Rotate the array
void
move
(
int
array
[
]
,
int
n
,
int
offset
)
{
int
p
,*
arr_end
;
arr_end
=
array
n
;
// The position after the last element of the array
int
last
;
// Rotate until the offset becomes 0
while
(
offset
)
{
last
=*
(
arr_end
1
)
;
for
(
p
=
arr_end
1
;
p
!=
array
;--
p
)
// Rotate one position to the right
p
=*
(
p
1
)
; *
array
=
last
; --
offset
;
}
}