C语言实现数组的循环左移,右移,翻转的示例

时间:2022-03-31 03:55:45

数组结合指针可以实现很多有趣的功能,比如下面这个程序:

假设数组为 : 12345

如果左移一次即为:23451 ,依次类推

如果右移一次即为:51234 ,依次类推

翻转则为:54321

我们来实现下这个程序:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NR(x) (sizeof(x)/sizeof(x[0]))
//数组左移
int buffer_left_move(int *buffer , int buf_len)
{
    int i ;
    char tmp = buffer[0];
    for(i = 1 ; i < buf_len ; i++)
    {
        buffer[i-1] = buffer[i] ;
    }
    buffer[buf_len-1] = tmp ;
}
//数组右移
int buffer_right_move(int *buffer , int buf_len)
{
    int i ;
    char tmp = buffer[buf_len - 1];
    for(i = buf_len ; i > 0 ; i--)
    {
        buffer[i] = buffer[i-1] ;
    }
    buffer[0] = tmp ;
}
//数组翻转
int buffer_turn_over(int *buffer , int buf_len)
{
    int size = buf_len ;
    int i , tmp;
    for(i = 0 ; i < size/2 ; i++)
    {
        tmp = buffer[i] ;
        buffer[i] = buffer[size-1-i] ;
        buffer[size-1-i] = tmp;
    }
}
//打印数组
void print_buffer(int *buffer, int buf_len)
{
    int i ;
    system("cls");
    printf("please input \'a' or \'b' or \'w' \n");
    for(i = 0 ; i < buf_len ; i++)
    {
        printf("%d",buffer[i]);
    }
    putchar('\n');
}
 
int main(void)
{
    int buffer[5] = {1,2,3,4,5} ;
    
    print_buffer(buffer,NR(buffer));
    while(1)
    {
        switch(getch())
        {  
            //左边
            case 'a':
                    buffer_left_move(buffer,NR(buffer)) ;
                    print_buffer(buffer,5);
                    break ;
            //右边
            case 'd':
                    buffer_right_move(buffer,NR(buffer));
                    print_buffer(buffer,5);
                    break ;
            //翻转
            case 'w':
                    buffer_turn_over(buffer,NR(buffer)) ;
                    print_buffer(buffer,5);
                    break ;
        }
    }
    return 0 ;
}

运行结果:

?
1
2
3
please input 'a' or 'b' or 'w'
 
12345

按下a为不断左移,按下d为不断右移,按下w则为翻转

以上这篇C语言实现数组的循环左移,右移,翻转的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/morixinguan/article/details/77481270