Home > Mobile >  program that store integer values into a 2D array
program that store integer values into a 2D array

Time:03-28

It just creates random values

I tried using a separate value for the variable of the array and I also don't know why it starts counting at element 6.

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

int main()
{
int i;
int array[3][5];

for (i = 0; i<5; i  );
    {
    printf("Input a whole number for row 1 element %d:\n", i 1);
    scanf("%d", &array[0][i]);
    }

printf("Row 1 elements:\n");
for(i = 0; i<5; i  )
{
    printf("%d\n", array[0][i]);
}

return 0;
}

Ouput:

> Input a whole number for row 1 element 6: 4 Row 1 elements: 0 0 0 0
> 1897665488
> 
> Process returned 0 (0x0)   execution time : 1.969 s Press any key to
> continue.

CodePudding user response:

It starts counting from 6 because the line for (i = 0; i < 5; i );, is iterating (incrementing) i 5 times so, i becomes 5, then you print i 1 to stdout.

So, basically your call to printf() and scanf() functions were never a part of any sort of loop.

NOTE: Adding a semi-colon ;, after any loop means that there is no body for the loop. Basically it's an empty loop. It can be useful for finding the length of a string, and so on.

Some tips:

  • Also instead to using bare return 0;, use return EXIT_SUCCESS;, which is defined in the header file stdlib.h.
  • use int main(void) { }, instead of int main() { }
  • always check whether scanf() input was successful or not

Correct Code

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

int main(void)
{
    int i;
    int array[3][5];

    for (i = 0; i < 5; i  )
    {
        printf("Input a whole number for row 1 element %d:\n", i   1);
        if (scanf("%d", &array[0][i]) != 1)
        {
            perror("bad input: only numbers are acceptable\n");
            return EXIT_FAILURE;
        }
    }

    printf("Row 1 elements:\n");
    for (i = 0; i < 5; i  )
    {
        printf("%d\n", array[0][i]);
    }

    return EXIT_SUCCESS;
}

Output:

Input a whole number for row 1 element 1:
1
Input a whole number for row 1 element 2:
2
Input a whole number for row 1 element 3:
3
Input a whole number for row 1 element 4:
5
Input a whole number for row 1 element 5:
7
Row 1 elements:
1
2
3
5
7
  • Related