栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C学习---数组一

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C学习---数组一

继续C语言的学习,今天还是学习很基础的东东,也是很重要的,正式开始:

数组初始化

运行结果:

对于没有初始化的数组,里面的元素值是不确定的:

如果想给全部元素都赋值为0,则可以用下面这种方式简写:

使用数组的注意事项

 下面以两个小程序来操练一下数组:

统计字符出现次数示例

#include 
int main(void)
{
    int c, i;
    int nwhite = 0;//空白字符记数
    int nother = 0;//其它字符记数
    int ndigit[10] = {0};//统计十个数字出现的次数
    while ((c = getchar()) != EOF)
    {
        switch (c)
        {
        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
            ndigit[c-'0']++;
            break;
        case ' ':
        case 'n':
        case 't':
            nwhite++;
            break;
        default:
            nother++;
            break;
        
        }
    }
    printf("digits =");
    for (i = 0; i < 10; i++)
        printf(" %d", ndigit[i]);
    printf(", white space = %d, other = %dn", nwhite, nother);
    return 0;
}

看下效果:

整型数组逆序示例

#include 

//将一个数组进行逆序
void reverse(int a[], int cnt)
{
    int first, last;
    
    for (first = 0, last = cnt - 1; first < last; first++, last--)
    {
        a[first] = a[first] + a[last];
        a[last] = a[first] - a[last];
        a[first] = a[first] - a[last];
    }
}

int main(void)
{
    int ary[] = { 1, 2, 3, 4, 5 };
    int cnt = sizeof(ary) / sizeof(ary[0]);
    reverse(ary, cnt);

    int i;
    for (i=0; i 

实现思路:

对于两数的交换,我们都知道可以利用中间tmp变量,但是对于整型的两个数,实际也可以不借助中间变量,也能达到交换的目的:

另外换一种写法,将交换逻辑定义为宏(这个之后会详细学习,先知道有这么回事)

#include 

//将交换逻辑定义为宏
#define SWAP(a,b) { a=a+b; b=a-b; a=a-b; }

void reverse(int a[], int cnt)
{
    int first, last;
    
    for (first = 0, last = cnt - 1; first < last; first++, last--)
    {
        
        SWAP(a[first], a[last]);//直接调用宏既可实现两数交换
    }
}

int main(void)
{
    int ary[] = { 1, 2, 3, 4, 5 };
    int cnt = sizeof(ary) / sizeof(ary[0]);
    reverse(ary, cnt);

    int i;
    for (i=0; i 

运行结果:

关注个人公众号,获得实时推送

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/312380.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号