Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to declare, initialize and print two dimensional (2D) int array (matrix) in C

3 Answers

0 votes
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
 
int main(void)
{
   /* 2D array declaration*/
   int arr2d[3][5];
   int i, j;
   
   srand((unsigned)time(NULL));

   for(i = 0; i <= 2; i++)
   {
        for(j = 0;j <= 4; j++)
        {
            arr2d[i][j] = rand() % 100 + 1;
            printf("arr2d[%d][%d] = %d ", i, j, arr2d[i][j]);
        }
        printf("\n");
    }
        
    return 0;
}

  
/*
 
run:
 
arr2d[0][0] = 74 arr2d[0][1] = 66 arr2d[0][2] = 41 arr2d[0][3] = 49 arr2d[0][4] = 60
arr2d[1][0] = 35 arr2d[1][1] = 19 arr2d[1][2] = 39 arr2d[1][3] = 19 arr2d[1][4] = 39
arr2d[2][0] = 19 arr2d[2][1] = 19 arr2d[2][2] = 56 arr2d[2][3] = 57 arr2d[2][4] = 58

*/

 



answered Nov 20, 2015 by avibootz
0 votes
#include <stdio.h>
 
int main(void)
{
   /* 2D array declaration*/
   int arr2d[2][4] = { {13, 10, 17, 29}, 
                       {16, 18, 37, 95} };
   int i, j;

   for(i = 0; i < 2; i++)
   {
        for(j = 0;j < 4; j++)
            printf("arr2d[%d][%d] = %d ", i, j, arr2d[i][j]);
        printf("\n");
    }
        
    return 0;
}

  
/*
 
run:
 
arr2d[0][0] = 13 arr2d[0][1] = 10 arr2d[0][2] = 17 arr2d[0][3] = 29
arr2d[1][0] = 16 arr2d[1][1] = 18 arr2d[1][2] = 37 arr2d[1][3] = 95

*/

 



answered Nov 20, 2015 by avibootz
edited Nov 20, 2015 by avibootz
0 votes
#include <stdio.h>
 
int main(void)
{
   // 2D array declaration
   // The row determine according to braces blocks
   int arr2d[][4] = { {13, 10, 17, 29}, 
                      { 16, 18, 37, 95} };
   int i, j;

   for(i = 0; i < 2; i++)
   {
        for(j = 0;j < 4; j++)
            printf("arr2d[%d][%d] = %d ", i, j, arr2d[i][j]);
        printf("\n");
    }
        
    return 0;
}

  
/*
 
run:
 
arr2d[0][0] = 13 arr2d[0][1] = 10 arr2d[0][2] = 17 arr2d[0][3] = 29
arr2d[1][0] = 16 arr2d[1][1] = 18 arr2d[1][2] = 37 arr2d[1][3] = 95

*/

 



answered Nov 20, 2015 by avibootz
...