C language advanced tutorial - C language array (1)

C language advanced tutorial - C language array (1)

insert image description here

We often need to store a large number of data values ​​of some type in a program.

  • For example, if you were writing a program to track the performance of a basketball team, you would store the game points and players' points for a season, and then output a player's points for the entire season, or calculate the season's score as the game progresses. average score.
  • We can write a program that uses a different variable for each score. However, if there are a lot of games in a season, this can be very cumbersome, because each player with a game needs many variables.
  • all basketball scoresThe type is the same, the difference is the score, but they are all basketball scores.
  • Ideally, these points should be organized under a name, such as the player's name, so that there is no need to define variables for each data item.
  • This article will introduce how to use arrays in C language programs, and then how to refer to a set of values ​​by a name when writing programs that use arrays.

First, the introduction of the problem

  • The best way to illustrate the concept of arrays and their usefulness is through an example of how simple programs can become when working with arrays. This example will calculate the average grade of students in a class.

To calculate the average grade of students in a class, assume that there are only 10 students in the class. To calculate the average of a set of numbers, add them all up and divide by the number of numbers to get the average:

  • The procedure is as follows
#define _CRT_SECURE_NO_WARNINGS

#include "Main.h"

int main()
{
    
    
	system("color 3E");

    // 存储学生成绩值
    int grade = 0;              
   
    // 学生人数
    unsigned int count = 10;
                   
    // /成绩的总和
    long sum = 0L;
             
    // 成绩的平均值
    float average = 0.0f;

    for (unsigned int i = 0; i < count; ++i)
    {
    
    
        printf("输入第%d个学生成绩: ", i + 1);
        scanf("%d", &grade);
        sum += grade;                      // 把它加到sum
    }

    average = (float)sum / count;          // 计算平均值

    printf("\n十个学生的平均成绩是: %f\n", average);


	system("pause");
	return 0;
}

Press F5 to debug the result as follows
insert image description here

  • If you're only interested in the average, you don't need to store the scores above. This program adds up all the scores and divides it by count (which is 10).
  • This simple program just uses a variable grade to store each grade entered in the loop. The loop executes when the value of i is 0, 1, 2, 3...9 for a total of 10 iterations.
  • Suppose you want to write this program into a more complex program, you need to input some values, then output the score of each person, and finally output the average score.
  • In the above program, there is only one variable. Each time a point is added, the old point value is overwritten and cannot be used again.
  • How to store all the scores? You can declare 10 integer variables to store fractions, but you cannot enter these values ​​in a for loop. Instead, you have to add code to read in these values ​​one by one. But this is too complicated.
  • At this time, arrays should be used to solve the problem of numerical storage

2. What is an array

  • An array is a fixed number of data items of the same type, and the data items in the array are called elements.
  • The elements in the array are all int, long, or other types.
  • The following array declaration is very similar to declaring a normal variable with a single value, but with a number in square brackets after the name.

long numbers[10];

  • The number in square brackets defines the number of elements to be stored in the array, called the array dimension. Arrays have a type that combines the type of elements and the number of elements in the array. So if two arrays have the same number of elements and the same type, the two arrays are of the same type.
  • Each data item stored in the array is accessed with the same name, which in this case is
    numbers.
  • To select an element, use the index value within square brackets after the array name.
  • The index values ​​are consecutive integers starting from 0. 0 is the index value of the first element, and the element index value of the previous numbers array is 0~9. Index
    value 0 represents the first element, and index value 9 represents the last element. Thus array elements can be represented as numbers[0],
    numbers[1], numers[…numbers[9].

As shown below
insert image description here

3. Use arrays

  • The following will use array knowledge to solve the average score problem.
  • Use an array to store all the scores to be averaged. i.e. store all scores so they can be reused.

Now rewrite the program to calculate the average of 10 scores: the
code looks like this:

#define _CRT_SECURE_NO_WARNINGS

#include "Main.h"

int main()
{
    
    
	system("color 3E");
	
    // 存储学生成绩的数组
    int grades[10];

    // 学生人数
    unsigned int count = 10;
                   
    // /成绩的总和
    long sum = 0L;
             
    // 成绩的平均值
    float average = 0.0f;

    printf("输入十个学生的成绩分数值:\n");   
    
    for (unsigned int i = 0; i < count; ++i)
    {
    
    
        printf("输入第%d个学生成绩--> ", i + 1);
        scanf("%d", &grades[i]);               
        sum += grades[i];                      
    }

    average = (float)sum / count;              // 计算平均值

    printf("\n十个学生的平均成绩是: %.2f\n", average);

	system("pause");
	return 0;
}

Press F5 to debug the result as follows
insert image description here

  • The program starts with the usual #include <stdio.h>, since the printf() and scanf() functions are used here.
  • At the beginning of the main() function, declare an array of 10 integers, followed by some variables needed for the calculation:
    // 存储学生成绩的数组
    int grades[10];

    // 学生人数
    unsigned int count = 10;
                   
    // /成绩的总和
    long sum = 0L;
             
    // 成绩的平均值
    float average = 0.0f;
  • The count variable is of type unsigned int because it must be non-negative.

  • Then, prompt for a score with the following statement:

printf("输入十个学生的成绩分数值:\n");   
  • Next, use a loop to read in the values ​​and accumulate them:
 	for (unsigned int i = 0; i < count; ++i)
    {
    
    
        printf("输入第%d个学生成绩--> ", i + 1);
        scanf("%d", &grades[i]);               
        sum += grades[i];                      
    }
  • The for loop uses the standard format, and the loop continues as long as i is less than count. The loop counts from 0 to 9,
    not 1 to 10, so each member of the array can be accessed directly using the loop variable i.

  • Use the function scanf() to read each value of the input into element i of the array: the 1st value is stored in number[0], the 2nd input value is stored in number[1]...the 10th input value is stored into number[9].

  • On each iteration of the loop, the value read is added to sum. When the loop ends, calculate and display the average with the following statement:

    average = (float)sum / count;              // 计算平均值

    printf("\n十个学生的平均成绩是: %.2f\n", average);
  • The method of calculating the average is to divide sum by the number of fractions count, and the value of count is 10.

This program can also add the function of inputting the grades of each student. The
added code is as follows

    for (unsigned int i = 0; i < count; i++)
    {
    
    
        printf("第%d个学生的成绩是: %d\n", i, grades[i]);
    }

Press F5 to debug the result as follows
insert image description here

  • This for loop iterates over the elements in the array and outputs each value. Use the loop control variable as
    the sequence number corresponding to each element, and access the corresponding array element. The numerical values ​​of these elements obviously correspond to the numbers entered.
  • To get a score starting at 1, you can use the expression i+1 in the output statement to get a score from 1 to 10, since i is from 0.
    to 9.

4. Complete program

The complete program code is as follows

  • main.h file
#pragma once


#include <stdio.h>
#include <stdlib.h>


  • main.c file
#define _CRT_SECURE_NO_WARNINGS

#include "Main.h"

int main()
{
    
    
	system("color 3E");

     存储学生成绩值
    //int grade = 0;              
   
     学生人数
    //unsigned int count = 10;
    //               
     /成绩的总和
    //long sum = 0L;
    //         
     成绩的平均值
    //float average = 0.0f;

    //for (unsigned int i = 0; i < count; ++i)
    //{
    
    
    //    printf("输入第%d个学生成绩: ", i + 1);
    //    scanf("%d", &grade);
    //    sum += grade;                      // 把它加到sum
    //}

    //average = (float)sum / count;          // 计算平均值

    //printf("\n十个学生的平均成绩是: %f\n", average);




    // 存储学生成绩的数组
    int grades[10];

    // 学生人数
    unsigned int count = 10;
                   
    // /成绩的总和
    long sum = 0L;
             
    // 成绩的平均值
    float average = 0.0f;

    printf("输入十个学生的成绩分数值:\n");   
    for (unsigned int i = 0; i < count; ++i)
    {
    
    
        printf("输入第%d个学生成绩--> ", i + 1);
        scanf("%d", &grades[i]);               
        sum += grades[i];                      
    }

    average = (float)sum / count;              // 计算平均值

    for (unsigned int i = 0; i < count; i++)
    {
    
    
        printf("第%d个学生的成绩是: %d\n", i, grades[i]);
    }

    printf("\n十个学生的平均成绩是: %.2f\n", average);

	system("pause");
	return 0;
}


insert image description here

Guess you like

Origin blog.csdn.net/m0_47419053/article/details/126567250