简体   繁体   中英

Copy one dimensional array to two dimensional array in C

I have a code something like this, but I want to display it in two dimensional array like 4*10. I'm thinking of copying the elements of one dimensional array to two dimensional. But how can i edit this below code. Thank you.

long int arr[40];

printf("The Fibonacci range is: ");

arr[0]=0;
arr[1]=1;

for(i=2;i<range;i++){
     arr[i] = arr[i-1] + arr[i-2];
}

  for(i=0;i<range;i++)
     printf("%ld ",arr[i]);

You have all of the one dimensional completed. Using the same process you can add it to array[x][y] , and loop through. The only thing is you would need to keep track of two indexes instead of one. Code it all and you will get it.

If its only for display reasons you don't have to copy the array just fix it in the print:

for(i=0;i<range;i++) {
   if (i%10 == 0)
       printf("\n");
   printf("%ld ",arr[i]);
}

Thats will print the array in 4 diff lines as I guess you wanted.

Hope that's help

check out this

#include <stdio.h>

int main(void) {

long int arr[40];
long int twoD[4][10];
int i,range,j,k;
printf("The Fibonacci range is:\n ");
scanf("%d",&range);  // getting range value from user

arr[0]=0;
arr[1]=1;

for(i=2;i<range;i++){
     arr[i] = arr[i-1] + arr[i-2];
}

 i=0; // reinitialize i to 0.
     for(j=0;j<4;j++){
        for(k=0;k<10;k++){
            twoD[j][k]=arr[i++];  // coping 1D to 2D array
        }
     }

     for(j=0;j<4;j++){
        for(k=0;k<10;k++){
        printf("%ld ",twoD[j][k]); // printing 2D array
        }
        printf("\n");
     }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM