C语言一维数组学习编程案例
1.数组初始化及逆序
#include<stdio.h>
int main()
{
int arry[11];
int data;
for(data = 0;data <= 10;data++)
{
arry[data] = data;
printf("顺序数组的值:%d\n",arry[data]);
}
printf("\n");
for(data = 10;data >=0;data--)
{
arry[data] = data;
printf("逆序数组的值:%d\n",arry[data]);
}
return 0;
}
2.查看数组的存储个数
#include<stdio.h>
int main()
{
int arry[] = {12,10,11,13,14,45};
int data,size;
size = sizeof(arry) / sizeof(arry[0]);
printf("数组的个数为:%d\n",size);
for(data = 0;data < size;data++)
{
printf("数组地址:%p,data:%d\n",&arry[data],arry[data]);
}
return 0;
}
3.斐波那契数列
#include<stdio.h>
int main()
{
int arry[30];
int arrysize;
int i;
arry[0] = 0;
arry[1] = 1;
//数组个数写死,这句可有可无。主要计算数组的个数sizeof
arrysize = sizeof(arry) / sizeof(arry[0]);
puts("斐波那契数列为: ");
for(i = 2;i < arrysize;i++)
{
arry[i] = arry[i-1] + arry[i-2];
}
for(i = 0;i < arrysize;i++)
{
printf("%d ",arry[i]);
}
return 0;
}
4.冒泡排序
从大到小排序,从小到大同理
#include<stdio.h>
int main()
{
int arry[] = {12,13,8,22,5,9};
int len;
int temp;
int i;
int j;
len = sizeof(arry) / sizeof(arry[0]);
for(i = 0;i < len - 1;i++)
{
for(j = 0;j < len - i -1;j++)
{
if(arry[j] < arry[j+1])
{
temp = arry[j];
arry[j] = arry[j+1];
arry[j+1] = temp;
}
}
}
for(i = 0;i < len;i++)
{
printf("%d ",arry[i]);
}
return 0;
}
5.简单选择排序法
从大到小排序,从小到大同理
#include<stdio.h>
int main()
{
int arry[] = {18,12,8,5,22,13,25};
int len;
int temp;
int i;
int j;
puts("从大到小排序为:");
len = sizeof(arry) / sizeof(arry[0]);
for(i = 0;i < len - 1;i++)
{
for(j = i+1;j < len;j++)
{
if(arry[i] < arry[j])
{
temp = arry[i];
arry[i] = arry[j];
arry[j] = temp;
}
}
}
for(i = 0;i < len;i++)
{
printf("%d ",arry[i]);
}
return 0;
}