C语言-数组小练习

1.题目:1.有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    int n;
    printf("please input n:");
    scanf("%d",&n);

    int *a = (int *)malloc(sizeof(int)*n);
    int i = 0;
    for(;i<n;i++)
        a[i] = i+1;
    for(i=0;i<n;i++)
        printf("%d\t",a[i]);
    printf("\n");

    int m = 0;
    int l = n;
    int k = 0;
    while(m<n-1)
    {
        for(i=0;i<l;i++)
        {
            if(a[i] != 0)
            {
                k++;
                if(k%3 == 0)
                {
                    a[i] = 0;
                    m++;
                }
            }
        }
        for(i=0;i<n;i++)
            printf("%d\t",a[i]);
        printf("\n");
    }

    for(i=0;i<n;i++)
        if(a[i] != 0)
            printf("%d",a[i]);
    free(a);
    return 0;
}

2.字符数组在指定位置插入字符

int main()
{
    char a[5] = {'a','b','c','d','e'};
    int location;
    char b;
    int len = sizeof(a) / sizeof(char);

retry1:
    printf("insert location:");
    scanf("%d", &location);
    if(location > len-1)
    {
        printf("location(%d) > len(%d) - 1\n",location,len);
        goto retry1;
    }
    printf("%d\n",location);

    printf("insert char:");
    scanf(" %c",&b);
    printf("%c\n",b);

    char tmp = a[location];
    a[location] = b;
    int i = 0;
    for(i=4;i-1>location;i--)
        a[i] = a[i-1];
    a[location+1] = tmp;

    for(i=0;i<5;i++)
    	printf("%c ",a[i]);
    printf("\n");
    return 0;
}

3.在字符数组中指定开始位置插入字符串

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    char a[20],b[20],c[20];
    int lena,lenb,lenc;
    lena = lenb = lenc = 0;
    int location;
    int i = 0, j = 0;

    printf("input string a:");
    scanf("%s",a);
    printf("%s\n",a);
    //printf("%c\n",a[21]);
    printf("input string b:");
    scanf("%s",b);
    printf("%s\n",b);
    scanf("%d",&location);
    printf("%d\n",location);


    while(a[lena++] != '\0');
    lena--;
    printf("lena:%d\n",lena);
    while(b[lenb++] != '\0');
    lenb--;
    printf("lenb:%d\n",lenb);

    for(i=location;i<=lena;i++,j++)
        c[j] = a[i];
    printf("c:%s\n",c);
    for(i=location,j=0;j<lenb;i++,j++)
        a[i] = b[j];
    printf("a+b:%s\n",a);
    for(i=location+lenb,j=0;c[j] != '\0';i++,j++)
        a[i] = c[j];
    printf("a+b+c:%s\n",a);
    a[i+1] = '\0';
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值