在c中逐列迭代二维数组

时间:2016-01-19 08:41:57

标签: c arrays multidimensional-array

请有人向我解释如何逐列迭代二维数组,即保持行不变直到我们到达列的末尾? 感谢。

我正在编写一个程序来计算一类学生的某些科目的分数。它计算每个学生获得的总分,以及每个科目的最高分。

我遇到困难的棘手部分是计算每个科目的最低分。这将需要向下迭代每列并仅在获得该列中的最高分后更改行(主题)

代码(也 - http://pastebin.com/FmP4yX59):

#include <stdio.h>
#include <stdlib.h>
#define MAX_ST 3
#define MAX_SU 3

int main() {
  int student[MAX_ST][MAX_SU];

  int total_mark[MAX_ST];
  printf("\n_________________PRESS TAB KEY TO SHIFT A COLUMN_________________\n");
  printf("\nRoll_NO   subject1    subject2    subject3\n");
  printf("________________________________________________________________\n");
  for(int i = 0; i < MAX_ST; i++) {
    printf("%d\t|\t",i+1);
    for(int j = 0; j < MAX_SU; j++){
      scanf("%d",&student[i][j]);
    }
  }
  //total marks obtained by each student
  printf("\nTOTAL MARKS\n");
  for(int i = 0; i < MAX_ST; i++) {
    total_mark[i] = 0;
    for(int j = 0; j < MAX_SU; j++) {
      total_mark[i] += student[i][j];
    }
    printf("Student %d = %d\n",i+1, total_mark[i]);
  }

  //highest total mark
  int overRoll = 0;
  int high_S = 0;
  for(int i = 0; i < MAX_ST; i++) {
    if(high_S <= total_mark[i]) {
      high_S = total_mark[i];
      overRoll = i;
    }
  }

  printf("Highest total marks is %d for Student %d\n", high_S,overRoll + 1);

  //highest mark in each subject
  //where the problem lies
  int highest_mark[MAX_SU];
  int highest_sudent[MAX_SU];

  for(int i  = 0; i < MAX_SU;i++){
    for(;j = t;) {
      Highest_mark[i] = 0;
      if(student[i][j] > highest_mark[i]) {
        highest_mark[j] = student[][j];
        highest_student[i] = i;
      }
    }
    printf("the highest");
  }
}

3 个答案:

答案 0 :(得分:0)

#define rows 5
#define columns 4    

int matrix[rows][columns];

int r, c;

for (c = 0; c < columns; c++)
{
    for (r = 0; r < rows; r++)
    {
        matrix[r][c]; \\ the data
    }
}

答案 1 :(得分:0)

通常你会这样做:

typedef void action_t (int*);

void traverse_matrix ( size_t col, 
                       size_t row, 
                       int matrix[col][row],
                       action_t* action )
{
  for(size_t x=0; x<col; x++)
  {
    for(size_t y=0; y<row; y++)
    {
      action(&matrix[x][y]);
    }
  }
}

答案 2 :(得分:0)

感谢各位帮助我弄清楚

int highest_mark[MAX_SU];
int highest_student[MAX_SU];
int curr_sub;
for(int i  = 0; i < MAX_SU; i++)        
{

       highest_mark[i] = 0;
    for(int j = 0; j < MAX_ST; j++)
    {

            if(student[j][i] >  highest_mark[i])
            {
                highest_mark[i] = student[j][i];
                highest_student[i] = j+1;
                curr_sub = i+1;
            }

    }
     printf("the highest score subject %d is %d  by student %d\n", curr_sub, highest_mark[i],highest_student[i]);   
}