C two-dimensional array based on user input -
i'm trying assign user input using two-dimensional array takes 5 numbers , squares them. program should calculate , store squared values each user in array.
i'm getting right output current code can't figure out how assign input array, without getting errors in output.
#include <stdio.h> int main(void) { int disp[2][5]; int x, y; printf("please enter 5 integer values:\n"); for(x=0; x<=2; x++) { (y=0; y<=5; y++) { scanf("%d", &x); printf("[ %d ][ %d ]\n", x, x*x); } } return 0; }
the following code scans 5 numbers, , stores squares in array (which never used again):
#include <stdio.h> #define num_items 5 // store number of items in 1 place int main() { int disp[2][num_items]; int i; printf("please enter %d integer values:\n", num_items); (i = 0; < num_items; ++i) { if ( scanf("%d", &disp[0][i]) == 1 ) { // check return value of scanf() disp[1][i] = disp[0][i] * disp[0][i]; // store squares in array printf("[ %d ][ %d ]\n", disp[0][i], disp[1][i]); } else { printf("error in scanf()\n"); break; } } return 0; } i'm trying assign user input using two-dimensional array takes 5 numbers , squares them. program should calculate , store squared values each user in array.
some issues code:
for(x=0; x<=2; x++) { // overflows array (0, 1 , 2) // should x < 2 (y=0; y<=5; y++){ // idem -> y < 5 scanf("%d", &x); // scanf() called 10 times // x used loop counter! printf("[ %d ][ %d ]\n", x, x*x); // squares never stored in array } }
Comments
Post a Comment