数组一

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

数组初始化
 
运行结果:
对于没有初始化的数组,里面的元素值是不确定的:
 
 
如果想给全部元素都赋值为0,则可以用下面这种方式简写:
 
 
 
使用数组的注意事项
 
 
 
 
 
 
 
 
 
 下面以两个小程序来操练一下数组:
统计字符出现次数示例
#include <stdio.h>
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 = %d\n", nwhite, nother);
    return 0;
}

看下效果:

整型数组逆序示例
#include <stdio.h>

//将一个数组进行逆序
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<cnt; i++)
        printf("%d ", ary[i]);
    printf("\n");

    return 0;
}

实现思路:

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

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

 

#include <stdio.h>

//将交换逻辑定义为宏
#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--)
    {
        /*
        a[first] = a[first] + a[last];
        a[last] = a[first] - a[last];
        a[first] = a[first] - a[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<cnt; i++)
        printf("%d ", ary[i]);
    printf("\n");

    return 0;
}

 

运行结果:

 

posted on 2013-12-01 10:05  cexo  阅读(205)  评论(0编辑  收藏  举报

导航