当前位置:网站首页>C language array processing batch data

C language array processing batch data

2022-04-23 17:55:00 Chshyz

One dimensional array 、 Two dimensional array 、 Array of strings

Environmental Science :CentOS7
PS: An array is a collection of ordered data ( Each element belongs to the same data type , Use a unified array name and subscript to uniquely determine the elements in the array .)

  • One dimensional array ( Type character Array name [ Constant expression ])
    Example : First give the array elements with a circular structure a[0]~a[9] assignment 0 To 9, And then follow 9-0 Output
#include <stdio.h>
int main() {
    
    int i, a[10]; # Defining integer variables i And integer arrays a
    for (i = 0; i <= 9; i ++) # One by one 10 Element assignment 
        a[i] = i;
    for (i = 9; i >= 0; i --) # Output in reverse order 
        printf ("%d\n", a[i]);
    printf("\n");
    return 0;
}
[[email protected] c]# gcc -o for2 for2.c
[[email protected] c]# ./for2
9
8
7
6
5
4
3
2
1
0
  • Two dimensional array ( Type name Array name [ Constant expression ] [ Constant expression ])
    Example : Row and column transpose
#include <stdio.h>
int main() {
    
    int a[2] [3] = {
    
        {
    1, 2, 3}, {
    4,5,6}
     };
    int b[3] [2], i, j;
    printf ("array a:\n");
    for (i = 0; i < 2; i ++) {
    
        for (j = 0; j < 3; j ++) {
    
            printf ("%5d", a[i] [j]);
            b[j] [i] = a [i] [j];
            }
         printf ("\n");
         }
     printf ("array b:\n");
     for (i = 0; i < 3; i ++) {
    
         for (j = 0; j < 2; j ++)
             printf ("%5d", b[i] [j]);
         printf ("\n");
     }
     return 0;
}
[[email protected] c]# gcc -o for3 for3.c
[[email protected] c]# ./for3
array a:
    1    2    3
    4    5    6
array b:
    1    4
    2    5
    3    6

  • A character array
    Example : The diamond
#include <stdio.h>
int main() {
    
    char a[][5] = {
    
         {
    ' ',' ','*'},
         {
    ' ','*',' ','*'},
         {
    '*',' ',' ',' ','*'},
         {
    ' ','*',' ','*'},
         {
    ' ',' ','*'}
         };
    int i, j;
    for (i = 0; i < 5; i ++) {
    
        for (j = 0; j < 5; j ++)
            printf ("%c", a[i][j]);
        printf ("\n");
        }
    return 0;
}
[[email protected] c]# gcc -o for4 for4.c
[[email protected] c]# ./for4
  *
 * *
*   *
 * *
  *

  • Count the number of words
#include <stdio.h>
int main() {
    
    char b[100];
    int i, num = 0, word = 0;
    char c;
    gets (b);
    for (i = 0; (c = b[i]) != '\0'; i ++)
        if (c == ' ') word = 0;
        else if (word == 0) {
    
             word = 1;
             num ++;
             }
    printf ("you have %d words in this line.\n", num);
    return 0;
}
[[email protected] c]# ./for5
huang hong zhang
you have 3 words in this line.

版权声明
本文为[Chshyz]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230547413965.html