C 练习实例27
题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。
程序分析:无。
实例
// Created by www.facesoho.com on 15/11/9.
// Copyright © 2015年 小鸟启蒙. All rights reserved.
//
#include <stdio.h>
int main()
{
int i=5;
void palin(int n);
printf("请输入5个字符\40:\40");
palin(i);
printf("\n");
}
void palin(n)
int n;
{
char next;
if(n<=1) {
next=getchar();
printf("相反顺序输出结果\40:\40");
putchar(next);
} else {
next=getchar();
palin(n-1);
putchar(next);
}
}
以上实例输出结果为:
请输入5个字符 : abcde 相反顺序输出结果 : edcba

文人墨客
/* * * 题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。 * * */ #include<stdio.h> #include<string.h> int reverse(int num, char* chr) { int head = 0,tail = num - 1; int counter = num / 2; counter--; if(counter < 0) return 0; else { *(chr + head) ^= *(chr + tail); *(chr + tail) ^= *(chr + head); *(chr + head) ^= *(chr + tail); } return reverse(num - 2,chr + 1 ); } int main() { char buf[6] = {0}; printf("请输入5个字符:"); fgets(buf, 6, stdin); reverse(strlen(buf),buf); printf("倒叙输出结果为:%s\n\n",buf); return 0; }文人墨客
参考方法:
#include<stdio.h> void Print(char a[], int n) { if(n >= 0) { printf("%c",a[n]); Print(a,n - 1); } } int main(void) { char a[5]; printf("请输入5个字符 :"); for(int i = 0; i < 5; i++) scanf("%c",&a[i]); printf("相反顺序输出结果 : "); Print(a,4); return 0; }文人墨客
参考方法:
#include <stdio.h> void f() { char ch; if((ch=getchar())!='\n') { f(); } if(ch!='\n') { printf("%c",ch); } } void main() { printf("请输入字符: "); f(); }文人墨客
参考方法:
#include<stdio.h> void fun(char* s,int length) { if (length >= 1) { printf("%c\n", s[length - 1]); fun(s, length - 1); } } int main() { char* s = "hello"; int length = 5; fun(s, length); return 0; }