C语言学习——day3 递归、数组、str函数

一、递归

项目:i个台阶,每次走1个或2个台阶,有多少种走法?

#include <stdio.h>

int step(int i) {
	if (1 == i ) {
		return 1;
	}
	if (2 == i) {
		return 2;
	}
	return step(i - 1) + step(i - 2);
}

int main() {
	int i;
	scanf("%d", &i);
	step(i);
	printf("%d", step(i));
	return 0;
}

二、数组

1、数组遍历

#include <stdio.h>

void print(int a[], int number) {
	for (int i = 0; i < number; i++) {
		printf("a[%d] = %d\n",i, a[i]);
	}
	a[4] = 10;
}

int main() {
	int a[6] = { 2,5,3,4,7 };//自动在数组多于位置加0
	print(a, 6);
	printf("a[4] = %d", a[4]);
	return 0;
}
/*
a[0] = 2
a[1] = 5
a[2] = 3
a[3] = 4
a[4] = 7
a[5] = 0
a[4] = 10
*/

2、向数组内输入数据

#include <stdio.h>

int main() {
	int i;
	scanf("%d", &i);
	int arr[100];
	//怎么向数组内输入数据
	//注意a <= i;是错误的,如果 =i 则数组出界arr[0] 1 2 3 4 (i = 5)
	for (int a = 0; a < i; a++) {
		scanf("%d", &arr[a]);
	}
	int tmp = 0;
	for (int b = 0; b < i; b++) {
		if (arr[b] == 2) {
			tmp++;
		}
	}printf("%d", tmp);
}

3、字符数组

#include <stdio.h>

int main() {
	char a[6] = { 'h','e','l','l','o' };
	//注意字符串后面的结束标识符'\0',所以a[5]-->a[6]
	char b[4] = "how";
	//和上面相同的道理,结束标识符'\0'
	printf("%s----%s\n", a, b);
	char e[20],f[20];
	scanf("%s%s", e,f);//what fuck?
	printf("%s %s", e,f);//what fuck?
//scanf不能识别输入字符之间的空格,如果没有printf的%s %s之间的空格会变成whatfuck?
	return 0;
}

4、字符数组遍历

#include <stdio.h>

void print(char b[]) {
	int i = 0;
	while (b[i] != '\0') {//while(b[i]){  这个写法也可以,'\0'也是0,当等于0时循环结束
		printf("%c", b[i]);
		i++;
	}
}

int main() {
	char a[10] = "hello";
	print(a);
	return 0;
	
}

加:str函数的使用

#include <stdio.h>
#include <string.h>

int main() {
	char a[20] = "abcdef";
	//strlen()函数计算数组里面字符的个数
	printf("数组a里面的字符长度 = %d\n", strlen(a));
	//strcpy将a赋值到b
	char b[20] = "ee";
	strcpy(b, a);
	puts(b);
	
	// char *strcpy(char *to,const char *from)
	//带有const的,可以赋值一个字符串常量
	strcpy(b, "jacklove");
	puts(b);

	//strcmp比较两个字符串的大小,跟上面一样可以对两个字符串常量进行比较
	//a>b  = 1 ; a=b = 0 ;a<b = -1;
	//字符串大小比较从左到右比较,字符依次比较ASCII值
	//int strcmp(const char *str1,const char *str2)
	int s = strcmp(a, b);
	printf("数组a与b的大小 = %d\n", s);

	//strcat拼接字符串
	//char *strcat(char *str1,const char *str2)  常量拼接
	
	strcat(b, " ADC");
	puts(b);
	return 0;
}

---------------------------------------------------------->

5、反转字符并比较大小

#include <stdio.h>
#include <string.h>
int main() {
	char a[100],d[100];
	gets(a);
	//hello -->h e l l o \0
	
	//注意字符串数组后面有  '\0' 
	int i, j;
	for (i = strlen(a) - 1, j = 0; i >= 0; i--, j++) {
		d[j] = a[i];
	}
	d[j] = '\0';
	puts(d);
	int cmp = strcmp(a, d);
	if (cmp > 0) {
		printf("%d", 1);
	}
	else if (cmp < 0) {
		printf("%d", -1);
	}
	else {
		printf("%d", 0);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值