C, Multi-Dimensional Arrays Exercise

2019-09-02 03:36发布

My understanding of a 2d array is wrong. So I'll approach this question another way. Say I have the following variables.

int student_id[10], course_id[5];

int student_course[10][2];

There can only be 10 students. There can only be 5 courses. A student can only take 2 courses.

/*prompt user for student id*/

/*
say that the value for: 
student_id[0]=123
*/

/*prompt user for course id*/

/*
say that the value for:
course_id[0]=101
course_id[1]=102
course_id[2]=103
course_id[3]=104
course_id[4]=105
*/

What I want to print out is the
student_course[value_of_student_id][value_of_course_id].

So I thought of doing it this way:

int student_id[10], course_id[5], student_course[10][2]

int i, j, k;

for(i=0; i<10;i++){
    for(j=0; j<5; j++){

        /*prompt user for student id*/
        printf("Enter User ID: ");
        scanf("%d", &student_id);

        /*prompt user for course id*/
        printf("Enter Course ID: ");
        scanf("%d", &course_id);

        for(k=0; k<2; k++){
            student_course[i][j]=student_course[i][k];
        }

    }
}

If this is the wrong way, what is the correct way to get the results I want? A 3 dimensional array perhaps? I might not be ready for that yet.

标签: c arrays 2d
1条回答
混吃等死
2楼-- · 2019-09-02 04:13

You could do it like this instead

typedef struct
{
  int student_id;
  int course_id[2];
} Student

Student Students[10];

then initialize the array with the student_id's and what courses he is attending

查看更多
登录 后发表回答