1、输入一行字符,分别统计出其中的英文字母,空格,数字和其他字符的个数。
#include "stdio.h"
#include "stdlib.h"
int main(int argc, char *argv[])
{
char c;
int letters=0,space=0,digit=0,other=0;
printf("请输入一行字符:\n");
while((c=getchar())!='\n') //获得单个字符,并将该字符赋值给变量c
{
if(c>='a' && c<='z' || c>='A' && c<='Z')
letters++;
else
if(c==' ') //统计空格数,存放到变量space中。
space++;
else
if(c>='0' && c<='9')
digit++;
else
other++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符数%d\n",letters,space,digit,other);
return 0;
}
2、输入123456,从后往前判断其各位数是否为偶数,若是则输出。
#include <stdio.h>
int main () {
int num;
scanf("%d",&num);
do{
if(num%10%2==0){
printf("%d",num%10);
}
num=num/10;
}while(num);
return 0;
}
3、将从键盘输入的一对数,由小到大排序输出。当输入一对相等数时结束循环。
#include <stdio.h>
int main () {
int a,b,t;
scanf("%d,%d",&a,&b);
while(a!=b){
if(a>b){
t=a;
a=b;
b=t;
}
printf("%d,%d",a,b);
scanf("%d,%d",&a,&b);
}
return 0;
}
4、输入一个整数a,输出a!
#include <stdio.h>
int main()
{
int i,a,sum=1;
scanf("%d",&a);
for(i=1;i<=a;i++)
sum=sum*i;
printf("%d!=%d",a,sum);
return 0;
}
5、输入一串字符串,输出其各位的ASCII码值。
#include "stdio.h"
int main(){
char a[80],*p=a;
gets(a);
while(*p!=0){
printf("%d ",*p);
p++;
}
return 0;
}
6、输入一串字符串,输出其各位的ASCII码之和。
#include "stdio.h"
int main(){
char a[80],*p=a;
int sum=0;
gets(a);
while(*p!=0){
sum=sum+*p;
p++;
}
printf("%d ",sum);
return 0;
}
7、从键盘接收一串字符串s,并检查字符串s中是否存在字符c,若存在,则删除字符串s中所有字符c。
思路:定义整型变量 i 和 j,其中 i 代表原数组下标,j 代表删除字符c后的新数组下标。利gets()函数从键盘接收一串字符串s,i 从 0 开始,判断每个 s[i] 是否等于 c,不等于 c,就将其赋值给 s[j],然后j自增 1。若 s[i]=='c',就不执行 s[j++]=s[i],j 的值也不增加。遇到 s[i]=='\0'循环结束,在新数组后面加上'\0',用puts()函数输出该删除字符c后的字符串。
#include < stdio.h>
int main( ){
char s[80];
int i,j;
gets(s);
for(i=j=0;s[i]!='\0';i++)
if (s[i]!='c')
s[j++]=s[i];
s[j]='\0';
puts(s);
}
8、用子函数计算字符串中字符的个数。
fun (char *s) {
char *p=s;
while (*p) p++;
return (p-s);
}
int main(){
char *a="abcdef";
printf("%d\n", fun(a));
}
9、将输入的字符中大写字母转换成小写字母,将小写字母转换成大写字母。
#include
void main( ){
char ch;
while ((ch=getchar( ))!='\n')
{ if (ch>='A' && ch<='Z') ch=ch+32;
else if (ch>='a' && ch<'z') ch=ch-32;
printf("%c", ch);
}
printf("\n");
}