打印2~100的素数:
int main(int argc,char *argv[]){
int num,i,j;
int arr[50];
int index = 1;
for(num = 2;num < 100;num++){
for(j = 2;j <= num;j++){
if(num % j == 0)
break;
}
if(j == num){
arr[index] = num;
index++;
}
}
for(i = 0;i < index;i++){
if(i % 5 == 0 && i / 5 != 0)
printf("\n");
printf("%4d",arr[i]);
}
return 0;
}
在已排好序的数组中插入一个数,人让其排好输出:
#include<stdio.h>
int main(){
int arr[6] = {4,6,33,35,65};
int i,insert,temp;
printf("input a num of insert:\n");
scanf("%d",&insert);
//insert = 5;
for(i = 0;i < 6;i++){
if(arr[i]>insert){
temp = arr[i];
arr[i] = insert;
insert = temp;
}
}
arr[5] = insert;
for(i = 0;i<6;i++){
printf("%d ",arr[i]);
}
printf("\n");
return 0;
}
课堂笔记:
指针:
- 野指针:
没有初始化,或者其指向的内存被释放,而指针没有被置空;
危害:造成段错误处,出现未知的错误。 - 指针的运算:
指针的自增和自减
自增:指针向高地址方向移动;
自减:指针向低地址方向移动;
指针不能相加,只能相减; - 概念区分
int buf[3];
int *pb;
int arr[3];指针数组
int (pa)[3];数组指针 - 二级指针:
DataType **pointername;
int a = 10;
int *p = &a;
int **pa = &p;
**pa = *p = a = 10;
总结:今天讲的东西重在理解数组,理解数组和指针之间的各项,要学会思路的理转换和理解
作业:
- 1.编程输入一行文字,找出其中的大写字母,小写字母,空格,数字,及
其他字符的个数(用指针实现)
#include<stdio.h>
int main(int argc,char *argv[]){
char arr[100];
char *p = arr;
int index = 0;
int capital_count = 0;
int lowercase_count = 0;
int space_count = 0;
int number_count = 0;
int other_count = 0;
printf("input string:");
for(p = arr;p < arr+100;p++){
scanf("%c",p);
if(*p == '\n')
break;
//index++;
else if(*p>='A' && *p<='Z')
capital_count ++;
else if(*p>='a' && *p<='z')
lowercase_count ++;
else if(*p == 32)
space_count ++;
else if(*p>=48 && *p<=57)
number_count ++;
else
other_count ++;
}
printf("大写字母:%4d\n小写字母:%4d\n空格:%4d\n数字:%4d\n其他:%4d\n",capital_count,lowercase_count,space_count,number_count,other_count);
printf("%d",index);
return 0;
}```
* 2.从键盘输入5个整数存入一个数组。然后输入另外一个数,用指针的方法从中查找该数是否存在,如果找到,输出该数所在的下标,否则输出消息:"没有找到"。
//在数组中查找一个数然后输出下标
include<stdio.h>
int main(int argc,char *argv[]){
int index = 0;
int arr[5];
int pointer = arr;
int i = 0;
printf("input five number:");
for(i = 0;i < 5;i++)
scanf("%d",pointer+i);
int seek_num = 0;
printf("input a num of seeking:");
scanf("%d",&seek_num);
for(pointer = arr;pointer < arr + 5;pointer++){
if(pointer == seek_num){
i = pointer -arr;
index++;
printf("this number is found!index is :%d\n",i);
}
}
if(index == 0)
printf("Dont found!!!\n");
return 0;
}```
- 3.char a[5]="hello"; char b[5]="world"; char c[14];用指针方法将数组a和数组b的内容存到数组c中
//合并字符串
#include<stdio.h>
int main(int argc,char *argv[]){
char a[5] = "hello";
char b[5] = "world";
char c[14] = {0};
char *pa = a;
char *pb = b;
char *pc = c;
for(pa = a;pa < a+5;pa++,pc++)
*pc = *pa;
for(pb = b;pb < b+5;pb++,pc++)
*pc = *pb;
pc = c;
printf("%s\n",pc);
}
网友评论