Explanation of array in the early stage of C language

Posted by Millar on Sat, 01 Jan 2022 11:18:17 +0100

catalogue

Insert sort explanation

Two dimensional array

Initialization of two-dimensional array

Access to two-dimensional arrays

n-dimensional array

Character array

Character arrays and strings

Input and output of character array

Character input / output

String input / output

Simple use of string functions

Comprehensive use of string functions

After the final exam, continue to publish the blog. Following the previous section, I wonder if my friends have ever tried to design the program left by the last blog to insert a number into an ordered array. Let's stop talking about it and start today's explanation

Insert sort explanation

#include<stdio.h>
int main() {
	int arr[8] = { 1,2,3,4,6,7,10 };
	int i = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);
	int n = 0;
	scanf("%d", &n);
	for (i = 0; i < sz - 1; i++)
		if (n < arr[i])       //Find insertion location
			break;
	for (int j = sz - 1; j > i; j--)
		arr[j ] = arr[j-1];   //Move each position back one bit
	arr[i] = n;       //Insert n into array
	for (int j = 0; j < sz; j++)
		printf("%d ", arr[j]);  //Print results
	return 0;
 }

The above program can realize the function of inserting numbers into an ordered array, and the insertion sorting is equivalent to continuously inserting new numbers into an ordered array. Based on the above program, the insertion sorting function can be realized

#include<stdio.h>
int main() {
	int arr[8] = { 4,55,66,8,4,1,3,2};
	int i = 0;
	int j;
	int sz = sizeof(arr) / sizeof(arr[0]);
	for (i = 1; i < sz; i++) {      //Loop insert data
			int num = arr[i];     
		for (j = 0; j < i; j++)   //The sequence of the first i items is incorrect, breaking the cycle
			if (arr[i]< arr[j])
				break;
		for (int x=i; x > j; x--) //Move all right
			arr[x] = arr[x- 1];
		arr[j] =num;     //insert data
	}
	for (i = 0; i< sz; i++)
		printf("%d ", arr[i]); 
	return 0;
 }

Each cycle is an insertion, which also has the characteristics of these two-layer cycles.

Two dimensional array

Two dimensional array is the extension and development of one-dimensional array. Two dimensional array is the nesting of one-dimensional array, which is similar to two-layer for loop. Generally speaking, two-dimensional array is an array of one-dimensional array, and each element of two-dimensional array is a one-dimensional array

int arr[5][5];
//Two dimensional array

The row and column idea mentioned in the 99 multiplication table can be used here. The first 5 represents that the two-dimensional array has five rows, and the second 5 represents that the two-dimensional array has five columns in each row. Next, explain it with a simple picture

When we study two-dimensional arrays, we can understand it in the first form, but if we want to go deeper, we have to understand the second form

Initialization of two-dimensional array

When learning one-dimensional array, we can omit the array length and supplement it by the compiler
 So is a two-dimensional array OK?
The answer is yes. The rows of a two-dimensional array can be omitted, but the columns cannot, because the number of columns and rows can be determined
 as
int arr[][4]={1,2,3,4,5,6,7,8};
int arr[][4]={{1,2,3},{},{4,5}};
The first method should be understandable
 The second method is to use the properties of two-dimensional arrays. Each row can be regarded as a one-dimensional array
{}The element in is the element in this line

Access to two-dimensional arrays

Two dimensional array is the same as one-dimensional array. The array subscripts start from zero. Here's a simple way to print a two-dimensional array

#include<stdio.h>
int main(){
int arr[4][4] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 };
	for (int i = 0; i < 4; i++) {
		int j = 0;
		for (j = 0; j < 4; j++)
			printf("%2d ", arr[i][j]);
		printf("\n");
	}
return 0;
}

Is it very similar to the program for printing the 99 multiplication table? Similarly, two-dimensional arrays are inseparable from two-layer loops. Therefore, we can see the importance of two-layer loops. As for the deep use of two-dimensional arrays, we will understand when we explain minesweeping and Sanzi chess

n-dimensional array

n-dimensional array is actually the expansion and extension of n-1-dimensional array. According to the thinking of studying two-dimensional array, we can study it step by step

Character array

Next is today's main course, character array

Character arrays and strings

There is no string type in the C language standard, which makes string related operations always need string functions. Character arrays are mostly used to store strings, but sometimes character arrays can not be regarded as strings.

The string is\0 End flag
char a[5]={'a','b','c','d','e'};
The character array here a Not in the\0,Forcing printing as a string will cause an error

When we do not initialize the character array and input it in the form of characters, we ignore \ 0. Of course, in most cases, we can still use the character array as a string

Input and output of character array

The input methods of character array are roughly divided into two types: character input and string input

Character input / output

//Before implementing input and output, we need to use character arrays as containers
#include<stdio.h>
int main() {
	char arr[5] = { 0 };
	for (int i = 0; i < 5; i++)
		scanf("%c", &arr[i]);
	for (int i = 0; i < 5; i++)
		printf("%c", arr[i]);
	return 0;
}

The two library functions getchar and putchar were mentioned earlier. Next, these two functions are used for character input and output

#include<stdio.h>
int main() {
	char arr[5] = { 0 };
	for (int i = 0; i < 5; i++)
		arr[i] = getchar();
	for (int i = 0; i < 5; i++)
		putchar(arr[i]);
	return 0;
}

String input / output

#include<stdio.h>
int main() {
	char arr[40] = { 0 };
	scanf("%s", arr);
	printf("%s\n", arr);
	return 0;
}

Next, two library functions, puts and gets, are used

#include<stdio.h>
int main() {
	char arr[40] = { 0};
	gets(arr);
	puts(arr);
	return 0;
}
//Incidentally, put will automatically wrap the string after printing

Simple use of string functions

As mentioned earlier, string functions are often required for string operations. In addition to the above functions, I will briefly teach you how to use the string functions introduced in the previous function article

#include<stdio.h>
#include<string.h>
int main() {
	char arr[10] = { 0 };
	strcpy(arr, "abc");//String copy, copy abc to arr
	strcat(arr, "def");//String append, append def after \ 0 of arr
	int len = strlen(arr);//Find the string length, excluding \ 0
	int cmp = strcmp(arr, "abcdef");//String comparison: the first string returns a number greater than zero,
                                    //Equal to returns 0, less than returns a number less than zero
	printf("%d %d", len, cmp);
	printf("%s\n", _strupr(arr));//Capitalize all strings
	printf("%s\n", _strlwr(arr));//Lowercase all strings
	return 0;
}

You can calculate the result according to the comments. Of course, the print string here also uses the feature of using the return value of the function

Comprehensive use of string functions

Next, string up all our knowledge and complete the following string sorting

#include<stdio.h>
include<string.h>
int main() {
char arr[5][20] = { "tiger","pander","eleplant","rabbit","lion" };//Declares and initializes the number of two-dimensional characters 
                                                                  //Group arr
	int i, j,flag;                               //i. J loop variable, flag is to judge whether the two-dimensional array is orderly 
                                                 //Variable of
	char t[20] = { '\0' };
	for (i = 0; i < 5; i++)                   //Print a two-dimensional character array as a string
		puts(arr[i]);
	printf("The above is an unordered two-dimensional character array\n");   //   Explain the printed results of the program
	for (i = 0; i < 4; i++) {
			flag = 1;
		for (j = 0; j < 4; j++) { 
			if (strcmp(arr[j], arr[j + 1]) > 0) {            //If the ascll value of the previous string is greater than 
                                                       //For the last string, the string position is exchanged
 			    strcpy(t, arr[j]); 
				strcpy(arr[j], arr[j+1]);
				strcpy(arr[j + 1], t);
				flag = 0;
			}			
		}
		if (flag)                                        //If flag is still equal to 1 after a cycle, then 
                                    //Without position exchange, the cycle is broken to reduce unnecessary operations
			break;
	}
	for (i = 0; i < 5; i++)                   //Print the two-dimensional character array sorted by bubble method in the form of string
		puts(arr[i]);
	return 0;
}

Well, that's the end of today's sharing

Next time I will share with you the simple function implementation of string library function.

Topics: C Back-end