m1031
m1031

Reputation: 15

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]);

Upvotes: 0

Views: 9793

Answers (3)

ItayB
ItayB

Reputation: 11337

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

Upvotes: 0

Rustam
Rustam

Reputation: 6515

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;
}

Upvotes: 0

user4875884
user4875884

Reputation:

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.

Upvotes: 1

Related Questions