Rama
Rama

Reputation: 9

Filling the second column of a 2d array in c

I filled the first column with random numbers in the range of [20,25], now I want the user to fill the second column with random numbers in the range of [20,25]. How can I do that?

#include <stdio.h>

void main()
{
    int Temperature[5][2] = {{20},{21},{22},{23},{24}};

    printf("I created a 2D array of size 5x2,");
    printf("and I filled the first column with random values in the range [20,25]\n");

    for(int i=0; i<5; i++)
    {
        printf("%d ",Temperature[i][0]);
        printf("\n");
    }

    printf("Please fill the second column with values in the range [0,20]\n");

    int i, j;
    for(j=0;j<5;j++)
    {
        printf("Value[%d]:",j);
        scanf("%d", &Temperature[0][j]);
    } 
}

Upvotes: 0

Views: 753

Answers (3)

Milan
Milan

Reputation: 88

For a two dimensional array in C, array[x][y] ---> denotes xth row and yth column

Since arrays are 0-indexed, 2nd column in your example implies column number should be 1 (0 is the first column)

Modified code

#include <stdio.h>

void main()
{
    int Temperature[5][2]={{20},{21},{22},{23},{24}};
    printf("I created a 2D array of size 5x2,");
    printf("and I filled the first column with random values in the range [20,25]\n");
    for(int i=0; i<5; i++)
    {
        //correction done here
        printf("%d ",Temperature[i][0]);
        printf("\n");
    }
    printf("Please fill the second column with values in the range [0,20]\n");
    int i, j;
    for(j=0;j<5;j++)
    {
        printf("Value[%d]:",j);
        scanf("%d", &Temperature[j][1]);
    } 
}

Upvotes: 2

safakeskin
safakeskin

Reputation: 718

I have modified your code a little bit assuming that you expect the user input numbers between 20 and 25, and added some logs in order to help your understanding.

#include <stdio.h>

int main()
{
  int i, Temperature[5][2] = {{20}, {21}, {22}, {23}, {24}};

  printf("I created a 2D array of size 5x2,");
  printf("and I filled the first column with random values in the range [20,25] (inclusive)\n");
  for (i = 0; i < 5; i++)
  {
    printf("%d ", Temperature[i][0]);
    printf("\n");
  }
  printf("\nPlease fill the second column with values in the range [20,25] (inclusive)\n");
  for (i = 0; i < 5; i++)
  {
    do
    {
      printf("Value[%d]:", i);
      scanf("%d", &Temperature[i][1]);
    } while (Temperature[i][1] < 20 || Temperature[i][1] > 25);
  }

  printf("and the user filled the second column with values in the range [20,25] (inclusive)\n");
  for (i = 0; i < 5; i++)
  {
    printf("%d \n", Temperature[i][1]);
  }
}

Note that values are not random, first column consists of the values I initialized and the second column consists of the values user entered.

Upvotes: 0

bipll
bipll

Reputation: 11940

&Temperature[0][j]

The actual element would be under Temperature[j][1].

Upvotes: 1

Related Questions