开发者

assigning and printing from 2d arrays C

/*
Program to calculate trip and plan flights
*/
#define TRIP 6 
#define DEST 1
#include <stdio.h>

int main(void)
{
  int type_num, cont_num, index, i, dest_code, trip_num, row, col;
  int travelint[TRIP][DEST]= {{0}};

  printf("Please enter the number of trips:");
  scanf("%d", &trip_num);
  for (i=0; i < trip_num ; i++)
  {
      printf("Please enter destination code:");
      scanf("%d", &dest_code); 

      cont_num = dest_code / 10000;
      type_num = dest_code/1000 - cont_num*10;

      if ( (cont_num <= 7) && (cont_num > 0) &&  (type_num <= 5) && (type_num >=0) )
          dest_code = travelint[i][0];  
      else
          printf("Invalid code\n");

   }
   printf("%2d", travelint[0][0]);  
   return 0;  
}

I'm having trouble printing from the array I'm not sure if I'm either printing it wrong or that the number isn't actu开发者_Go百科ally being assign in the array. I'm still having trouble with the concept of assign values from input into the array..


An array dimension with only one element in the row is a trifle pointless. You normally only use dimensions with more than one element in each row.

Additionally, you are never assigning to the travelint array - only reading from it. So, since it is initialized to all zeroes, all you will ever see when you print it are zeroes.

You probably simply need to change this:

  if ( (cont_num <= 7) && (cont_num > 0) &&  (type_num <= 5) && (type_num >=0) )
      dest_code = travelint[i][0];  

to:

  if ( (cont_num <= 7) && (cont_num > 0) &&  (type_num <= 5) && (type_num >=0) )
      travelint[i][0] = dest_code; 

This assigns to travelint.

To print out a full 2D array, you would normally use:

for (int j = 0; j < TRIP; j++)
{
    for (int k = 0; k < DEST; k++)
        printf("Trip[%d][%d] = %d\n", j, k, travelint[j][k]);
}

Given that the inner loop will be executed just once per iteration of the outer loop (in your example, where DEST is 1), you could simplify that to:

for (int j = 0; j < TRIP; j++)
{
    printf("Trip[%d][%d] = %d\n", j, 0, travelint[j][0]);
}

You should validate the trip_num after the user enters it. You should check that scanf() actually converted a value; if the user types 'A', then your program will go into a rapid loop printing out "Invalid code" every time. Always check that inputs succeed. In theory, you should also check that outputs succeed, but that rule is more often ignored than honoured. Also, if the user is nasty and types 200, then your program is not going to be happy after the user enters the sixth trip destination. It should be between 0 and TRIP (inclusive), of course. You should handle the degenerate (0) case properly, of course. And the printing loop becomes:

for (int j = 0; j < trip_num; j++)
{
    printf("Trip[%d][%d] = %d\n", j, 0, travelint[j][0]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜