Introduction to C language
“This is the 27th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.
About the author
- The authors introduce
🍓 blog home page: author’s home page 🍓 Introduction: JAVA quality creator 🥇, a junior student 🎓, participated in various provincial and national competitions during school, and won a series of honors
Introduction to C language
As soon as C language appeared, it was rapidly popularized and promoted all over the world with its features of rich functions, strong expression ability, flexibility and convenience, and wide application. C language not only has high execution efficiency and good portability, can be used to develop application software, drivers, operating systems and so on. C is also the ancestor of many other high-level languages, so learning C is a required course to enter the programming world.
Array traversal
Arrays can loop through each element, rather than fetching the element at a specified location. For example, we can loop through an array using a for loop:
Note the following points:
- It is best to avoid out-of-bounds array access, and loop variables should not exceed the length of the array.
- Once declared, the length of an array in C is fixed and cannot be changed, and C does not provide a method to calculate the length of an array.
Since C does not have a mechanism to check for array length changes or arrays out of bounds, it is possible to compile and pass in the editor, but the result is not certain, so it is best not to cross bounds or change the array length
C gets the length of the array
int length = sizeof(arr)/sizeof(arr[0]);
Copy the code
Array as function arguments
An array can take the entire array as an argument to a function, or an element of the array as an argument to a function:
- The entire array is taken as a function argument, that is, the array name is passed to the function, for example:
- Array elements are passed to the function as arguments. For example:
When using arrays as function arguments, note the following:
- When the array name is passed as a function argument, the array type parameter that the function definition receives as an argument may or may not specify a length.
- When an array element is passed as a function argument, the array element type must be the same as the parameter type.
Application of array (1) [Bubble sort]
Take ascending sort as an example. The idea of bubble sort is to compare adjacent elements in pairs and place the larger number after them until all numbers are sorted. Just like the primary school queuing by size of the same, will pull out a classmate and the back of the comparison, if tall put behind, has been lined up.
#include <stdio.h>
int main(a)
{
double arr[]={1.78.1.77.1.82.1.79.1.85.1.75.1.86.1.77.1.81.1.80};
int i,j;
printf("\n************ before queue *************\n");
for(i=0; i<10; i++) {if(i ! =9)
printf("% 1.2 f.", arr[i]); //%1.2f indicates one place before the decimal point and is accurate to two places after the decimal point
else
printf("% 1.2 f", arr[i]); //%1.2f indicates one place before the decimal point and is accurate to two places after the decimal point
}
for(i=8; i>=0; i--)
{
for(j=0; j<=i; j++) {if( arr[j]>arr[j+1]) // When the number in the front is greater than the number in the back
{
double temp; // Define the temporary variable temp
temp=arr[j];// Assign the preceding number to temp
arr[j]=arr[j+1]; // The number is reversed
arr[j+1]=temp;// Place the larger number after}}}printf("\n************ after queue *************\n");
for(i=0; i<10; i++) {if(i ! =9)
printf("% 1.2 f.", arr[i]); //%1.2f indicates one place before the decimal point and is accurate to two places after the decimal point
else
printf("% 1.2 f", arr[i]); //%1.2f indicates one place before the decimal point and is accurate to two places after the decimal point
}
return 0;
}
Copy the code
Array application (2) [Array lookup function]
When we go shopping and come home with our shopping bags, we check each item to see if it’s missing or what we want to buy.
Then apply to the program, you can use the array lookup function to see if the data exists, and if so, return the element’s subscript.
#include <stdio.h>
int getIndex(int arr[5].int value)
{
int i;
int index;
for(i=0; i<5; i++) {/* Please improve the array query function */
if(arr[i]==value)
{
index=i;
break;
}
index=- 1;
}
return index;
}
int main(a)
{
int arr[5] = {3.12.9.8.6};
int value = 8;
int index = getIndex(arr,value); // What arguments should be passed here?
if(index! =- 1)
{
printf("%d exists in array with subscript: %d\n",value,index);
}
else
{
printf("%d does not exist in array. \n",value);
}
return 0;
}
Copy the code
Strings and Arrays
In C, there is no way to define string data types directly, but we can use arrays to define strings. Generally, there are two formats:
- Char String name [length] = “string value “;
- Char String name [length] = {‘ character 1′,’ character 2′,… N ‘, ‘character,’ 0 ‘};
Note:
- The length in [] can be omitted;
- In the second case, the last element must be ‘0’, indicating the end of the string;
- The second method cannot write Chinese in the array.
To print a string, use: printf(” %s “, character array name); Or puts(character array name); .
String function
Commonly used string function is as follows (strlen, STRCMP, strcpy, strcat, atoi) :
Note the following when using string functions:
- Strlen () gets the length of the string, which does not include ‘0’ and the length of characters and letters is different. Such as:
- STRCMP () converts strings into ASCII codes before comparing them. A return of 0 means that s1 and S2 have the same ASCII code, a return of 1 means s1 is larger than THE ASCII code of S2, and a return of -1 means s1 is smaller than the ASCII code of S2. For example:
- Strcpy () overwrites the original string and cannot copy string constants, for example:
- When strcat is used, s1 and S2 must not overlap, and S1 must have enough space to hold the string to be copied, for example:
Multidimensional array
A multidimensional array is defined in the following format: Data type Array name Constant expression 1… [constant expression n];
Defines a two-dimensional array named num and of type int. The first [3] represents the length of the first dimension subscript, just like shopping stored in categories. The second [3] represents the length of the subscript in the second dimension, like the element in each shopping bag.
Initialization of a multidimensional array is similar to initialization of a one-dimensional array in two ways:
- Data type Array name Constant expression 1… [constant expression n] = {{value 1,.. , value n},{value 1,.. , value n},… , {1,… , n}};
- Data type Array name Constant expression 1… [constant expression n]; Array name subscript 1… [subscript n] = value;
Note the following when initializing multidimensional arrays:
- With the first initializer, the array declaration must specify the dimension of the column. Because the system will allocate space according to the total number of elements in the array, when the total number of elements and the dimension of the column is known, it will directly calculate the dimension of the trip.
- With the second type of initialization, the array declaration must specify the dimensions of both rows and columns.
When you define a two-dimensional array, you don’t have to specify the number of rows, but you must specify the number of columns
When you define a two-dimensional array, you don’t have to specify the number of rows, but you must specify the number of columns.
Traversal of multidimensional arrays
Multidimensional arrays are traversal, and like one-dimensional arrays, loops are required. The difference is that multi-dimensional arrays require nested loops
Note: Each subscript of a multidimensional array cannot be out of bounds
Comprehensive exercises:
#include <stdio.h>
#define N 10
// Prints the score
void printScore(int score[])
{
int i;
printf("\n");
for(i=0; i<N; i++) {printf("%d ",score[i]);
}
printf("\n");
}
// Calculate the total score
int getTotalScore(int score[])
{
int sum = 0;
int i;
for(i=0; i<N; i++) { sum+=score[i]; }return sum;
}
// Calculate the average score
int getAvgScore(int score[])
{
return getTotalScore(score)/N;
}
// Calculate the highest score
int getMax(int score[])
{
int max = - 1;
int i;
for(i=0; i<N; i++) {if(score[i]>max) { max = score[i]; }}return max;
}
// Calculate the lowest score
int getMin(int score[])
{
int min =100;
int i;
for(i=0; i<N; i++) {if(score[i]< min) { min = score[i]; }}return min;
}
// Scores are sorted in descending order
void sort(int score[])
{
int i,j;
for(i=N2 -; i>=0; i--) {for(j=0; j<=i; j++) {if(score[j]<score[j+1])
{
int temp;
temp = score[j];
score[j] = score[j+1];
score[j+1]=temp;
}
}
}
printScore(score);
}
int main(a)
{
int score[N]={67.98.75.63.82.79.81.91.66.84};
int sum,avg,max,min;
sum = getTotalScore(score);
avg = getAvgScore(score);
max = getMax(score);
min = getMin(score);
printf("Total score: %d\n",sum);
printf("The average score is: %d\n",avg);
printf("The highest score is: %d\n",max);
printf("Lowest score: %d\n",min);
printf("---------- Ranking ---------\n");
sort(score);
return 0;
}
Copy the code
After the language
The original intention of the director to write blog is very simple, I hope everyone in the process of learning less detours, learn more things, to their own help to leave your praise 👍 or pay attention to ➕ are the biggest support for me, your attention and praise to the director every day more power.
If you don’t understand one part of the article, you can reply to me in the comment section. Let’s discuss, learn and progress together!
Wechat (Z613500) or QQ (1016942589) for detailed communication.