第十次上机实验

来源:互联网 发布:php后端框架 编辑:程序博客网 时间:2024/04/28 11:06

第十次上机实验

任务1:
输入一个字符串和一个正整数x,将该字符串中的后x个字符复制到另一个字符串y中,再对y串的内容前后倒置后存入数组z中并输出。
要求:用指针访问数组元素、用函数getx(char *c1)实现复制、用函数getr(char *c2)实现倒置。
运行示例
Enter a string: abcABCD
Enter an integer: 4
The new string is DCBA

代码如下:

#include<stdio.h>      #include<string.h>      #define N 10      void getx(char *c1);    void getr(char *c2);    void main()    {      char a[N];        puts("Enter a string:");        gets(a);        getx(a);    }    void getx(char *c1)    {      int n,k=0;int j=0;char temp[N];        puts("Enter an integer:");        scanf("%d",&n);        while(*(c1+j)!='\0')          {j++;}         for(int i=j-n;i<j;i++)          {          temp[k]=*(c1+i);            k++;      }         temp[k]='\0';        getr(temp);        puts("The new string is ");        puts(temp);    }    void getr(char *c2)     {      int i=0;          char temp[N];          while(*(c2+i)!='\0')          {i++;}          for(int j=0;j<i;j++)          {temp[i-j-1]=*(c2+j);}          for(int k=0;k<i;k++)          {*(c2+k)=temp[k];}      }    


运行结果:

任务2:
定义一维整形数组,对数组分别进行“由大到小”和"由小到大"排序并输出。
要求:用函数和指针实现排序

代码如下:

#include"stdio.h"   void main()  {        int i,j,t,a[10];        printf("please input string a[]:\n");          for(i=0;i<10;i++)                        scanf("%d",&a[i]);         printf("交换前为:\n");                for(i=0;i<10;i++)                printf("%3d",a[i]);        printf("\n");         for(i=0;i<10;i++)                               for(j=0;j<=i;j++)                 if(a[i]<a[j])              {          t=a[i];a[i]=a[j];a[j]=t;      }             printf("交换后为:\n");            for(i=0;i<10;i++)                              printf("%3d",a[i]);            printf("\n");  }  


运行结果:

任务3:
输入字符串s,将字符放入d数组中,最后输出d中的字符串。
要求:用函数和指针实现
运行示例
输入字符串:abc123edf456gh
输出
字符串:abcedfgh

#include<stdio.h>   #define num 100   void xx(char*p);  void main()  {char a[num];  puts("输入字符串:");  gets_s(a);  xx(a);  }  void xx(char*p)  {char b[num];  int i=0;  while(*p!='\0')  {if(*p>=65&&*p<=90||*p>=97&&*p<=122)  {b[i]=*p;  i++;}  p++;}  b[i]='\0';  puts(b);  }  

运行结果: