c++ - reduce a 5x5 matrix to an 25 element array in c -
i have following homework problem witch can't seem find solution. problem: create 5x5 matrix of integers , check if of elements of matrix in interval [-10,15], , ones belong interval add array of 25 elements. program should implemented in c/c++. question: have written following code , problem have when try transfer elements have found fit condition, in nested for-loop. trouble when cycle through 5 elements , @ same time iterate 25 elements. how can this? here code:
#include <stdio.h> #include "stdafx.h" void main() { int i, j, k, l, m; int a[5][5]; int b[25]; printf("please enter elements of matrix:\n"); ( = 0; < 5; i++) { ( k = 0; k < 5; k++) { scanf_s("%d", &a[i][k]); } } ( k = 0; k < 25; k++) { ( l = 0; l < 5; l++) { if (a[k][l] > -10 && a[k][l] < 15) { b[k] = a[k][l]; } } } printf("the elements in range [-10, 15], following:\n"); (m = 0; m < 25; m++) { printf("%d\n", b[m]); } }
i think, have squeezed both loops one. please see below. while accepting input, there checking condition , putting new 1d array. since,i have counter 1d array(which increments new numbers inserted), while displaying; can use well.
#include <stdio.h> int main() { int a[5][5]; int b[15]; int c=0; printf("please enter elements of matrix:\n"); for(int i=0;i<5; i++){ for(int j=0;j<5;j++){ scanf("%d",&a[i][j]); if(a[i][j]>-10 && a[i][j]<15){ b[c++]=a[i][j]; } } } printf("\nthe numbers meet condition are:\n"); for(int i=0;i<c;i++) printf("%d,",b[i]); return 0; }
Comments
Post a Comment