Precedence and Associativity
Pointers and arrays, pointers and strings, pointers and functions, pointers and structures, handling files, command line arguments, dynamic memory allocation, c - two dimensional arrays.
C Programming

In this tutorial we will learn about two dimensional array in C programming language.
We have already covered about what are arrays in the previous tutorial. Now, lets explore the two dimensional arrays.
So, from the previous tutorial we know that when we want to store one dimensional data like score of a single player in 5 matches we use one dimensional array.
Now, if we want to store two dimensional data like storing respective scores of 4 players for the 5 matches then we need the two dimensional array.

Syntax of a 2D Array
To create a two dimensional array we use the following syntax.
In the above example we are creating an array named score of type int . It has 4 rows and 5 columns i.e., total 4x5 = 20 elements.
So, the above code will instruct the computer to allocate memory to store 20 elements of type int and we can represent the score array as shown below.

Array indexing starts from 0 so, in the above image there are 4 rows having index 0, 1, 2 and 3. And there are 5 columns having index 0, 1, 2, 3 and 4.
Assigning value to a 2D Array
We can assign value to a 2D array by targeting the cell using the row-index and col-index.
For example, if we want to assign 10 to element at row-index 0 and column-index 0 then we will write the following code.
Similarly, if we want to assign lets say 50 to an element of an array at row-index 1 and column-index 3 then we will write the following code.
Creating and initialising 2D array
There are a couple of ways we can create and initialise a 2D array in C.
In the following code we are creating a 2D array bonus of type int having 2 rows and 3 columns.
In the above code 1, 2, 3 is for the first row and 4, 5, 6 is for the second row of the array bonus.
We can achive the same result by separating the rows with curly brackets { } as show below.
We can also skip elements and they will be auto filled with 0s.
In the following example we are creating an array bonus of type int having 2 rows and 3 columns but this time we are initialising only few elements.
The above code will create the bonus array having 2 rows and 3 columns and we will get the following initialisation.
If we want to initialise all elements of a row to lets say 0 then we can write the following.
So, the above code will give us the following result.
Now, before we end this tutorial lets write a program in C to take score of 4 players for 5 matches and print them out.
© 2014 - 2023 dyclassroom . All rights reserved.
C Data Types
C operators.
- C Input and Output
- C Control Flow
- C Functions
- C Preprocessors
C File Handling
- C Cheatsheet
C Interview Questions

- Explore Our Geeks Community
- C Programming Language Tutorial
- C Language Introduction
- Features of C Programming Language
- C Programming Language Standard
- C Hello World Program
- Compiling a C Program: Behind the Scenes
- Tokens in C
- Keywords in C
C Variables and Constants
- C Variables
- Constants in C
- Const Qualifier in C
- Different ways to declare variable as constant in C and C++
- Scope rules in C
- Internal Linkage and External Linkage in C
- Global Variables in C
- Data Types in C
- Literals in C/C++ With Examples
- Escape Sequence in C
- Integer Promotions in C
- Character arithmetic in C and C++
- Type Conversion in C
C Input/Output
- Basic Input and Output in C
- Format Specifiers in C
- printf in C
- Scansets in C
- Formatted and Unformatted Input/Output functions in C with Examples
- Operators in C
- Arithmetic Operators in C
- Unary operators in C/C++
- Operators in C | Set 2 (Relational and Logical Operators)
- Bitwise Operators in C/C++
- C Logical Operators
- Assignment Operators in C/C++
- Increment and Decrement Operators in C
- Conditional or Ternary Operator (?:) in C
- sizeof operator in C
- Operator Precedence and Associativity in C
C Control Statements Decision-Making
- Decision Making in C / C++ (if , if..else, Nested if, if-else-if )
- C - if Statement
- C if...else Statement
- C if else if ladder
- Switch Statement in C
- Using range in switch case in C/C++
- while loop in C
- do...while Loop in C
- For Versus While
- Continue Statement in C
- Break Statement in C
- goto Statement in C
- User-Defined Function in C
- Parameter Passing Techniques in C/C++
- Function Prototype in C
- How can I return multiple values from a function?
- main Function in C
- Implicit return type int in C
- Callbacks in C
- Nested functions in C
- Variadic functions in C
- _Noreturn function specifier in C
- Predefined Identifier __func__ in C
- C Library math.h Functions
C Arrays & Strings
- Properties of Array in C
- Multidimensional Arrays in C
- Initialization of a multidimensional arrays in C/C++
- How Arrays are Passed to Functions in C/C++?
- How to pass a 2D array as a parameter in C?
- What are the data types for which it is not possible to create an array?
- How to pass an array by value in C ?
- Strings in C
- Array of Strings in C
- What is the difference between single quoted and double quoted declaration of char array?
- C String Functions
- Pointer Arithmetics in C with Examples
- C - Pointer to Pointer (Double Pointer)
- Function Pointer in C
- How to declare a pointer to a function?
- Pointer to an Array | Array Pointer
- Difference between constant pointer, pointers to constant, and constant pointers to constants
- Pointer vs Array in C
- Dangling, Void , Null and Wild Pointers
- Near, Far and Huge Pointers in C
- restrict keyword in C
C User-Defined Data Types
- C Structures
- dot (.) Operator in C
- Structure Member Alignment, Padding and Data Packing
- Flexible Array Members in a structure in C
- Bit Fields in C
- Difference Between Structure and Union in C
- Anonymous Union and Structure in C
- Enumeration (or enum) in C
C Storage Classes
- Storage Classes in C
- extern Keyword in C
- Static Variables in C
- Initialization of static variables in C
- Static functions in C
- Understanding "volatile" qualifier in C | Set 2 (Examples)
- Understanding "register" keyword in C
C Memory Management
- Memory Layout of C Programs
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- Difference Between malloc() and calloc() with Examples
- What is Memory Leak? How can we avoid?
- Dynamic Array in C
How to dynamically allocate a 2D array in C?
- Dynamically Growing Array in C
C Preprocessor
- C/C++ Preprocessors
- C/C++ Preprocessor directives | Set 2
- How a Preprocessor works in C?
- Header Files in C/C++ and its uses
- What’s difference between header files "stdio.h" and "stdlib.h" ?
- How to write your own header file in C?
- Macros and its types in C/C++
- Interesting Facts about Macros and Preprocessors in C
- # and ## Operators in C
- How to print a variable name in C?
- Multiline macros in C
- Variable length arguments for Macros
- Branch prediction macros in GCC
- typedef versus #define in C
- Difference between #define and const in C?
- Basics of File Handling in C
- C fopen() function with Examples
- EOF, getc() and feof() in C
- fgets() and gets() in C language
- fseek() vs rewind() in C
- What is return type of getchar(), fgetc() and getc() ?
- Read/Write Structure From/to a File in C
- C Program to print contents of file
- C program to delete a file
- C Program to merge contents of two files into a third file
- What is the difference between printf, sprintf and fprintf?
- Difference between getc(), getchar(), getch() and getche()
Miscellaneous
- time.h header file in C with Examples
- Input-output system calls in C | Create, Open, Close, Read, Write
- Signals in C language
- Program error signals
- Socket Programming in C/C++
- _Generics Keyword in C
- Multithreading in C
- Top 50 C Programming Interview Questions and Answers
- Commonly Asked C Programming Interview Questions | Set 1
- Commonly Asked C Programming Interview Questions | Set 2
- Commonly Asked C Programming Interview Questions | Set 3
- Discuss(90+)
Following are different ways to create a 2D array on the heap (or dynamically allocate a 2D array). In the following examples, we have considered ‘ r ‘ as number of rows, ‘ c ‘ as number of columns and we created a 2D array with r = 3, c = 4 and the following values
1) Using a single pointer and a 1D array with pointer arithmetic: A simple way is to allocate a memory block of size r*c and access its elements using simple pointer arithmetic.
Time Complexity : O(R*C), where R and C is size of row and column respectively. Auxiliary Space: O(R*C), where R and C is size of row and column respectively. 2) Using an array of pointers We can create an array of pointers of size r. Note that from C99, C language allows variable sized arrays. After creating an array of pointers, we can dynamically allocate memory for every row.
Time Complexity: O(R*C)
Here R and C is size of row and column respectively.
Auxiliary Space: O(R*C)
The extra space is used to store the elements of the matrix.
3) Using pointer to a pointer We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.
Time Complexity: O(R*C)
The extra space is used to store the elements of the matrix. 4) Using double pointer and one malloc call
The extra space is used to store the elements of the matrix. Thanks to Trishansh Bhardwaj for suggesting this 4th method. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
5) Using a pointer to Variable Length Array.
The dimensions of VLA are bound to the type of the variable. Therefore one form a pointer to an array with run-time defined shape. The pointer has to be dereferenced before subscripting with syntax (*arr)[i][j].
6) Using a pointer to the first row of VLA
Similar to 5 but allows arr[i][j] syntax.
Please Login to comment...

- NileshAwate
- sohampc4756
- garvitsingh1401
- stanislawskitomasz
- abhijeet19403
- akshaytripathi19410
- C Array and String
- cpp-pointer
Please write us at contrib[email protected] to report any issue with the above content
Improve your Coding Skills with Practice

- Design Pattern
- Interview Q
C Control Statements
C functions, c dynamic memory, c structure union, c file handling, c preprocessor, c command line, c programming test, c interview.
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials

Transact-SQL

Reinforcement Learning

R Programming

React Native

Python Design Patterns

Python Pillow

Python Turtle

Preparation

Verbal Ability

Interview Questions

Company Questions
Trending Technologies

Artificial Intelligence

Cloud Computing

Data Science

Machine Learning

B.Tech / MCA

Data Structures

Operating System

Computer Network

Compiler Design

Computer Organization

Discrete Mathematics

Ethical Hacking

Computer Graphics

Software Engineering

Web Technology

Cyber Security

C Programming

Control System

Data Mining

Data Warehouse
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week

PrepBytes Blog
ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING
Sign in to your account
Forgot your password?
Login via OTP
We will send you an one time password on your mobile number
An OTP has been sent to your mobile number please verify it below
Register with PrepBytes
Two dimensional array in c.
Last Updated on March 28, 2023 by Prepbytes

C programming language is one of the most used programming languages around the world due to the many features it provides. C language provides a data structure array that is used to store the data. Arrays are widely used in any programming language and there are many types of arrays. We are going to discuss one such type of array known as two dimensional array in c, we will discuss all 2d array in c, with their syntax, and initialization, how to declare them, and some features that we can perform on them.
What is a 2D Array?
A two dimensional array in c is one type of array. The 2d array is an array that is organized in rows and columns. We can identify each element in a 2d array using the position of rows and columns, we also call them indices. For example, in a 3×3 2D array, the element in the second row and third column would be accessed using the indices (1, 2) or row 1, column 2.
Syntax of 2D Array
In this blog section, we will explain the syntax of the two dimensional array in c.
- data_type: It will tell the type of data that has to be stored in each element.
- array_name: It will tell the name of the array with which it will be referenced in the whole program.
- m: It is the number of rows.
- n: It is the number of columns.
The array will have a total of m x n elements. For example, the 2D array in c of 20 rows and 10 columns will be declared like this.
Declaration and Initialization of Two Dimensional Array in C
We can declare the 2D array in c by using two methods.
- Using Initializer List
- Using Loops
Initializing using Initializer List In the initializer list we have two methods to declare the two dimensional array in C.
First Method In the first method we can write all the elements together as shown in the below example.
Here the array contains 4 rows and 3 columns. We read the elements in the matrix from left to right so in this also the elements are read from left to right so after every 3 elements we go to the new row, and the new row starts to be filled.
Second Method This method is comparatively better as we have clearly specified the elements in each row. Let’s look at the example shown below.
In the above example we have nested brackets which shows the element of each row individually.
Initializing Two Dimensional Array in C using Loops We can declare the array as normal after that we can initialize them with the help of loops.
Example of two-dimensional array in C Let’s understand this better with the help of an example.
In the above example we have declared the array with of size m x n and we have initialized it by using loops.
Accessing the Elements of the 2D Array in C
You can access the elements of Two dimensional array in C using the rows and columns or indices shown below.
- x: is the row index.
- y: is the column index
Pointers and 2D Array in C
We can use the pointers for accessing the elements of the array. The single pointer points to an entire 1D array so to use the pointer in 2D array we have to create a new pointer for every row.
Example Let’s understand the relations between pointers and 2D array with the help of an example.
Code Implementation
Explanation of the above example Here we have used pointers to traverse in the row and for every new row we have created a new pointer.
Examples of Two Dimensional Array in C
In this section, we will discuss various examples of two dimensional arrays in c.
Example 1: Taking the Input from the user and printing it. In the above example, we will see the implementation of the above-mentioned example.
Explanation of the above example In the above example we have declared an array of size 3 x 3. Then we have asked the user to give the input after receiving each input we have shown the matrix in the output.
Example 2: Summation in Two Dimensional Array in C Now we will discuss the implementation of the above-mentioned example.
Explanation of the above example In the above example we have taken two matrixes as input and then have added the two matrixes and printed the resulting matrix as output.
Common Applications of 2D Arrays
2D arrays in c have many applications that make them so useful. Some of the applications are explained below.
- Storing and manipulating images or other graphical data.
- Manipulating and storing matrices in linear algebra computations.
- Implementing board games like checkers and chess.
- Manipulating and representing data in spreadsheet programs.
Conclusion In this article we have studied two dimensional array in c. We have understood how to declare them using the syntax, and along with this, we have studied various methods for their initialization. We have also discussed the relationship between pointers and two dimensional arrays. After that, we have ended with the applications of two dimensional array in c.
Frequently Asked Questions
Below are some of the frequently asked questions on two dimensional arrays.
1. Can a 2D array have different types of elements? No, a 2D array in C can only have elements of the same data type.
2. How do you find the size of a 2D array in C? To find the size of a 2D array in C, you can multiply the number of rows by the number of columns.
3. How do you free memory allocated to a 2D array in C? To free the memory allocated to a 2D array in C, you use the free() function.
4. How do you pass a 2D array to a function in C? To pass a 2D array to a function in C, you must specify the dimensions of the array in the function parameter.
5. How do you return a 2D array from a function in C? You cannot directly return a 2D array from a function in C. Instead, you must return a pointer to the array.
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
- Linked List
- Segment Tree
- Backtracking
- Dynamic Programming
- Greedy Algorithm
- Operating System
- Company Placement
- Interview Tips
- General Interview Questions
- Data Structure
- Other Topics
- Computational Geometry
- Game Theory
Related Post
Null character in c, assignment operator in c, ackermann function in c, median of two sorted arrays of different size in c, number is palindrome or not in c, implementation of queue using linked list in c.
Find Study Materials for
Business studies, combined science.
- Computer Science
English Literature
Environmental science, human geography, macroeconomics, microeconomics.
- Social Studies
- Browse all subjects
- Exam Revision
- Career Advice for Students
- Student Life
- Study Guide
- University Advice
- Read our Magazine
Create Study Materials

Select your language

Dive into the fascinating world of 2D arrays in C by gaining a comprehensive understanding of their basics, practical applications, and various operations. Start by grasping the fundamental concepts such as structure and memory allocation, as well as the differences between row-major and column-major ordering. Then, explore practical examples of…

Explore our app and discover over 50 million learning materials for free.
- 2d Array in C
- Explanations
- StudySmarter AI
- Textbook Solutions
- Algorithm Analysis
- Big O Notation
- Binary Search
- Bubble Sort
- Complexity analysis
- Fibonacci Algorithm
- Genetic Algorithm
- Linear Search
- Recursive Algorithm
- Search Algorithms
- Sorting Algorithms
- Tower of Hanoi Algorithm
- Big Data Analytics
- Big Data Challenges
- Big Data Technologies
- Big Data Variety
- Big Data Velocity
- Big Data Volume
- Data Mining
- Data Privacy
- Data Quality
- Data Security
- Machine Learning Models
- Spark Big Data
- Supervised Learning
- Unsupervised Learning
- Client Server Networks
- HTTP and HTTPS
- Local Area Network
- Network Protocols
- Network Security
- Peer to Peer Network
- Public Key Infrastructure
- SSL encryption
- Types of Network
- Wide Area Network
- Arithmetic Logic Unit
- CPU Components
- CPU Function
- CPU Registers
- Cache Memory
- Computer Architecture
- Computer Memory
- Control Unit
- Harvard Architecture
- Magnetic Storage
- Optical Storage
- RAM and ROM
- Secondary Storage
- Solid State Storage
- Virtual Memory
- Von Neumann Architecture
- AND Operator in C
- Access Modifiers
- Algorithm in C
- Array as function argument in c
- Assignment Operator in C
- Automatically Creating Arrays in Python
- Bitwise Operators in C
- C Arithmetic Operations
- C Array of Structures
- C Functions
- C Math Functions
- C Memory Address
- C Plus Plus
- C Program to Find Roots of Quadratic Equation
- C Programming Language
- Change Data Type in Python
- Classes in Python
- Comments in C
- Common Errors in C Programming
- Compound Statement in C
- Concurrent Programming
- Conditional Statement
- Data Types in Programming
- Declarative Programming
- Distributed Programming
- Do While Loop in C
- Dynamic allocation of array in c
- Encapsulation programming
- Event Driven Programming
- Exception Handling
- For Loop in C
- Formatted Output in C
- Functions in Python
- How to return multiple values from a function in C
- Identity Operator in Python
- Imperative programming
- Increment and Decrement Operators in C
- Inheritance in Oops
- Insertion Sort Python
- Integration in C
- Linear Equations in C
- Log Plot Python
- Logical Error
- Logical Operators in C
- Loop in programming
- Matrix Operations in C
- Membership Operator in Python
- Nested Loops in C
- Nested if in C
- Numerical Methods in C
- OR Operator in C
- Object orientated programming
- One Dimensional Arrays in C
- Oops concepts
- Operators in Python
- Parameter Passing
- Plot in Python
- Plotting in Python
- Pointer Array C
- Pointers and Arrays
- Pointers in C
- Polymorphism programming
- Procedural Programming
- Programming Control Structures
- Programming Languages
- Programming Paradigms
- Python Arithmetic Operators
- Python Array Operations
- Python Arrays
- Python Assignment Operator
- Python Bar Chart
- Python Bitwise Operators
- Python Bubble Sort
- Python Comparison Operators
- Python Data Types
- Python Indexing
- Python Infinite Loop
- Python Loops
- Python Multi Input
- Python Range Function
- Python Sequence
- Python Sorting
- Python Subplots
- Python while else
- Quicksort Python
- R Programming Language
- Ruby programming language
- Scatter Chart Python
- Secant Method
- Shift Operator C
- Single Structures in C
- Statements in C
- Storage Classes in C
- String Formatting C
- String in C
- Strings in Python
- Structures in C
- Swift programming language
- Syntax Errors
- Variable Program
- Variables in C
- While Loop in C
- Write Functions in C
- exclusive or operation
- for Loop in Python
- if else in C
- if else in Python
- scanf Function with Buffered Input
- switch Statement in C
- while Loop in Python
- Disk Cleanup
- Memory Management
- Open Source Software
- Operating Systems
- Process Management in Operating Systems
- Proprietary Software
- Software Licensing
- Types of Operating Systems
- Utility Software
- What is Antivirus Software
- Binary Arithmetic
- Binary Conversion
- Binary Number System
- Bitmap Graphics
- Data Encoding
- Hexadecimal Conversion
- Hexadecimal Number System
- Image Representation
- Numeral Systems
- Sample Rate
- Sound Representation
- What is ASCII
- What is Unicode
- What is Vector Graphics
- Binary Tree
- Graph Data Structure
- Hash Structure
- Hash Tables
- Heap data structure
- List Data structure
- Priority Queue
- Queue data structure
- Stack in data structure
- Tree data structure
- Compound SQL Statements
- Constraints in SQL
- Control Statements in SQL
- Create Table SQL
- Creating SQL Views
- Creating Triggers in SQL
- Data Encryption
- Data Recovery
- Database Management System
- Database Normalisation
- Database Security
- Delete Trigger SQL
- GROUP BY SQL
- Grant and Revoke in SQL
- Integrity Constraints in SQL
- Join Operation in SQL
- Looping in SQL
- Modifying Data in SQL
- Nested Subqueries in SQL
- NoSQL Databases
- Oracle Database
- Relational Databases
- Revoke Grant SQL
- SQL BETWEEN
- SQL Conditional Join
- SQL Conditional Statements
- SQL Data Types
- SQL Database
- SQL Datetime Value
- SQL Expressions
- SQL FOREIGN KEY
- SQL Functions
- SQL Invoked Functions
- SQL Invoked Routines
- SQL Join Tables
- SQL Numeric
- SQL ORDER BY
- SQL PRIMARY KEY
- SQL Predicate
- SQL Server Security
- SQL String Value
- SQL Subquery
- SQL Transaction
- SQL Transaction Properties
- SQL Trigger Update
- SQL Triggers
- SQL Value Functions
- UPDATE in SQL
- Using Predicates in SQL Statements
- Using Subqueries in SQL Predicates
- Using Subqueries in SQL to Modify Data
- What is MongoDB
- What is SQL
- Clojure language
- First Class Functions
- Functional Programming Languages
- Haskell Programming
- Higher Order Functions
- Immutability functional programming
- Map Reduce and Filter
- Pure Function
- Recursion Programming
- Scala language
- Computer Health and Safety
- Computer Misuse Act
- Computer Plagiarism
- Computer program copyright
- Cyberbullying
- Digital Divide
- Energy Consumption of Computers
- Environmental Impact of Computers
- Ethical Issues in Computer Science
- Legal Issues Computer science
- Privacy Issues
- Repetitive Strain Injury
- Abstraction Computer Science
- Agile Methodology
- Agile Scrum
- Breakpoints
- Computational Thinking
- Decomposition Computer Science
- Kanban Boards
- Pattern Recognition
- Software Development Life Cycle
- Step Into Debugging
- Step Over Debugging
- Watch Variable
- Waterfall Model
- Automata Theory
- Complexity Theory
- Context Free Grammar
- Finite Automata
- Formal Language computer science
- Halting Problem
- NP Complete
- NP Hard Problems
- Pushdown Automata
- Regular Expressions
- Turing Machines
Save the explanation now and read when you’ve got time to spare.
Lerne mit deinen Freunden und bleibe auf dem richtigen Kurs mit deinen persönlichen Lernstatistiken
Nie wieder prokastinieren mit unseren Lernerinnerungen.
Dive into the fascinating world of 2D arrays in C by gaining a comprehensive understanding of their basics, practical applications, and various operations. Start by grasping the fundamental concepts such as structure and memory allocation, as well as the differences between row-major and column-major ordering. Then, explore practical examples of 2D arrays in C through matrix multiplication and the use of pointers for dynamic memory allocation. But it doesn't end there; further enhance your knowledge by learning about additional operations such as 2D array in C addition for adding two matrices, searching, sorting techniques and a deeper explanation of the concept. Finally, discover the different methods and syntaxes for 2D array declaration in C, ensuring you're equipped with the necessary knowledge to work confidently with 2D arrays in your programs.
Basics of 2D Array in C
When learning about the basics of 2D arrays in C programming, it's essential to understand how they work and enable you to manipulate data in a structured format. A 2D array, as the name suggests, is a two-dimensional array that consists of rows and columns. It is essentially an array of arrays , where each row is represented by an array. Some common applications of 2D arrays include representing matrices, tables, and grids of data.
A 2D array is a data structure that stores data in a grid format with rows and columns. Each element in a 2D array can be accessed using two indices, the first one representing the row number and the second one representing the column number.
Structure and Memory Allocation
Understanding the structure and memory allocation of a 2D array is crucial for working effectively with this data structure. When declaring a 2D array, you need to specify the number of rows and columns using the following syntax:
For example, the following code declares a 2D array of integers with 3 rows and 4 columns:
Memory allocation for a 2D array is contiguous, meaning that it is stored in consecutive memory locations. The layout of the 2D array in memory depends on the ordering used, which can be either row-major or column-major.
Row-Major and Column-Major Ordering
Row-major and column-major orderings are two common ways to represent 2D arrays in memory. Deciding which one to use depends on the specific requirements of your program.
Row-major ordering, also known as row-wise storage, stores the elements of an array in memory such that each row is stored as a contiguous block of memory. Column-major ordering, also known as column-wise storage, stores the elements of an array in memory such that each column is stored as a contiguous block of memory.
By default, C language uses row-major ordering when allocating memory for 2D arrays. To illustrate, consider the following 3x3 array:
In row-major ordering, memory for this 2D array would be allocated as follows:
Here, you can see that each row is stored as a contiguous block, and the first element of each subsequent row follows immediately after the last element of the previous row.
As an example of column-major ordering, let's consider the same 3x3 array. In column-major ordering, the memory would be allocated as follows:
Here, you can see that each column is stored as a contiguous block, and the first element of each subsequent column follows immediately after the last element of the previous column.
It is important to note that row-major ordering is more commonly used in C programming, as it is the default method. However, understanding column-major ordering can be helpful for working with other programming languages or libraries that may use column-major ordering.
Practical Examples of 2D Array in C
In this section, we will dive into practical examples of using 2D arrays in C programming to solve various problems. These examples will help you understand how to work effectively with 2D arrays and apply your skills in real-world situations.
2D Array in C Example: Matrix Multiplication
Matrix multiplication is a common operation in linear algebra and computer science applications. Let's explore how to implement matrix multiplication using 2D arrays in C. Suppose we have two matrices A and B, where A has dimensions m×n and B has dimensions n×p. The product matrix C will have dimensions m×p.
The formula for matrix multiplication is:
Here's a step-by-step guide to implementing matrix multiplication using 2D arrays in C:
Here's a sample code to demonstrate matrix multiplication using 2D arrays:
2D Array in C with Pointers: Dynamic Memory Allocation
Dynamic memory allocation is an essential feature when working with 2D arrays in C, as it allows you to create arrays with size determined at runtime. To perform dynamic memory allocation, you can combine pointers with the malloc function, which allocates a block of memory with the specified size in bytes and returns a pointer to that memory.
To allocate memory, use the following syntax:
Let's look at a step-by-step guide to allocating and deallocating memory for a 2D array in C:
Here's a sample code to demonstrate dynamic memory allocation with 2D arrays using pointers in C:
This code demonstrates how to allocate memory for a 2D array using pointers and the malloc function, and then how to free up memory after completing necessary computations using the free function.
Additional Operations with 2D Array in C
2d array in c addition: adding two matrices.
Matrix addition is another common operation in computer programming and linear algebra. The process of adding two matrices involves adding the corresponding elements of each matrix to create a new matrix with the same dimensions. Let's explore how to implement matrix addition using 2D arrays in C.
Suppose we have two matrices A and B with dimensions m×n. The resulting matrix C after adding the two matrices will also have dimensions m×n. The operation can be represented mathematically as:
Here's a step-by-step guide to implementing matrix addition using 2D arrays in C:
1. Declare and initialize matrices A and B, and their dimensions (m, n) according to the problem requirements.
2. Declare matrix C with dimensions m×n to store the result of the addition.
3. Loop through each element in matrix A using a variable i ∈ [0, m - 1] and loop through each element in matrix B using a variable j ∈ [0, n - 1].
4. For each combination of i and j, compute the sum c[i][j] = a[i][j] + b[i][j].
5. Output matrix C as the result.
Here's a sample code to demonstrate matrix addition using 2D arrays :

2D Array in C Explained: Searching and Sorting Techniques
Searching and sorting are fundamental operations that can be applied to 2D arrays in C. Understanding these techniques can help improve the efficiency of your program when handling large datasets. In this section, we will discuss two types of searching techniques (linear search and binary search) and one sorting technique (selection sort) that can be applied to 2D arrays in C.
Linear Search in 2D Array
Linear search is a searching technique that iterates through each element in the 2D array until the desired element is found or the array is fully traversed. The algorithm can be implemented using nested loops, which allows us to access each element of the 2D array.
Here is a step-by-step guide to implement linear search in a 2D array:
Binary Search in 2D Array
Binary search is a more efficient searching technique for sorted arrays. It works by repeatedly dividing the search interval in half. When working with 2D arrays, you can use binary search on a sorted row or column. Here is the implementation of binary search in a 2D row-sorted array:
Selection Sort in 2D Array
Selection sort is a simple sorting technique that works by repeatedly selecting the minimum element from the unsorted part of the array. Here's a step-by-step guide to implementing selection sort on a 2D array:
The selection sort algorithm can be easily adapted to sort the columns of a 2D array instead of the rows by swapping the loop variables.
2D Array Declaration in C: Different Methods and Syntaxes
Several methods and syntaxes can be used to declare and initialize 2D arrays in C. Each method serves a particular purpose and provides different levels of control and flexibility when working with 2D arrays. Let's examine some common methods:
Declare a 2D array with a fixed size and initialize its elements.
Each of these methods has its advantages and limitations. Static allocation is simple and easy to use but doesn't provide flexibility to change the size of the array during runtime. Variable-length arrays (VLAs) provide a level of runtime flexibility but are not available in all C compilers. Dynamic memory allocation using pointers offers the greatest flexibility and control but requires managing memory allocation and deallocation manually.
Choosing the appropriate method for declaring and initializing 2D arrays in C depends on your specific programming needs and constraints. Each method offers a unique balance between simplicity, flexibility, and control, making it suitable for different situations.
2d Array in C - Key takeaways
A 2D array in C is a two-dimensional array with rows and columns, used for storing data in a grid format.
Memory allocation for 2D arrays in C can use row-major or column-major ordering, with row-major being the default in C language.
Examples of 2D arrays in C can be found in matrix multiplication and dynamic memory allocation using pointers.
Additional operations with 2D arrays in C include addition (adding two matrices), searching (linear and binary search ), and sorting (selection sort).
2D array declaration methods in C include static allocation, static allocation with initialization, variable-length arrays (C99), and dynamic memory allocation with pointers.
Frequently Asked Questions about 2d Array in C
--> what is a 2d array in c, --> how can i use a 2d array in c, --> how do you declare a 2d array in c, --> how can i read data into a 2d array in c, --> how do you write a 2d array, final 2d array in c quiz, 2d array in c quiz - teste dein wissen.
What is a 2D array in C programming?
Show answer
A 2D array is a data structure that stores data in a grid format with rows and columns. Each element can be accessed using two indices: the row number and the column number.
Show question
How do you declare a 2D array in C?
Use the syntax `data_type array_name[row_size][column_size];` where `data_type` is the type of data, `array_name` is the name of the 2D array, and `row_size` and `column_size` are the number of rows and columns, respectively.
What is row-major ordering in C?
Row-major ordering, also known as row-wise storage, is a method for representing 2D arrays in memory such that each row is stored as a contiguous block of memory. C language uses row-major ordering by default.
What is column-major ordering?
Column-major ordering, also known as column-wise storage, is a method for representing 2D arrays in memory such that each column is stored as a contiguous block of memory.
How does memory allocation for a 2D array work in C?
Memory allocation for a 2D array in C is contiguous, meaning it is stored in consecutive memory locations. The layout of the 2D array in memory depends on the ordering used, which can be either row-major or column-major.
What is the formula for matrix multiplication using 2D arrays in C?
\[c_{ij} = \sum_{k=1}^{n} a_{ik} * b_{kj}\]
How do you declare a 2D array using double pointers in C?
data_type** array_name;
How do you allocate memory for rows in a dynamically allocated 2D array in C?
array_name = (data_type**)malloc(sizeof(data_type*) * row_size);
How do you allocate memory for columns in a dynamically allocated 2D array in C?
array_name[i] = (data_type*)malloc(sizeof(data_type) * column_size);
How do you deallocate memory for a dynamically allocated 2D array in C?
Loop through rows, call free(array_name[i]) for each row, then call free(array_name).
How to perform matrix addition using 2D arrays in C?
1. Declare and initialize matrices A and B, and their dimensions (m, n). 2. Declare matrix C with dimensions m×n to store the result. 3. Loop through each element in matrix A using variable i ∈ [0, m - 1] and in matrix B using variable j ∈ [0, n - 1]. 4. Compute sum c[i][j] = a[i][j] + b[i][j]. 5. Output matrix C as the result.
What are the three main techniques for searching and sorting 2D arrays in C?
Linear search, binary search, and selection sort.
How is linear search implemented in a 2D array?
1. Declare and initialize the 2D array and the target element. 2. Loop through the array using nested loops with variables i ∈ [0, row_size - 1] and j ∈ [0, column_size - 1]. 3. Check if the current element matches the target. If so, return position (i, j). 4. If target is not found, return an appropriate message or value to indicate failure.
How to implement binary search in a 2D row-sorted array?
1. Declare and initialize 2D row-sorted array and target element. 2. Loop through each row using variable i ∈ [0, row_size - 1]. 3. Perform binary search for each row, keeping track of starting index left (0) and ending index right (column_size - 1). 4. Compute middle index mid = (left + right) / 2. Return position (i, mid) if target is found; update left or right as necessary.
What are the four common methods to declare and initialize 2D arrays in C?
Static allocation, static allocation with initialization, variable-length array (C99), and dynamic memory allocation with pointers.
Test your knowledge with multiple choice flashcards
Join the studysmarter app and learn efficiently with millions of flashcards and more.
Already have an account? Log in
Save explanations that you love in your personalised space, Access Anytime, Anywhere!
- Computer Network
- Data Structures
of the users don't pass the 2d Array in C quiz! Will you pass the quiz?
How would you like to learn this content?
Free computer-science cheat sheet!
Everything you need to know on . A perfect summary so you can easily remember everything.
More explanations about Computer Programming
Discover the right content for your subjects, engineering, no need to cheat if you have everything you need to succeed packed into one app.
Be perfectly prepared on time with an individual plan.
Test your knowledge with gamified quizzes.
Create and find flashcards in record time.
Create beautiful notes faster than ever before.
Have all your study materials in one place.
Upload unlimited documents and save them online.
Study Analytics
Identify your study strength and weaknesses.
Weekly Goals
Set individual study goals and earn points reaching them.
Smart Reminders
Stop procrastinating with our study reminders.
Earn points, unlock badges and level up while studying.
Magic Marker
Create flashcards in notes completely automatically.
Smart Formatting
Create the most beautiful study materials using our templates.
Join millions of people in learning anywhere, anytime - every day
Sign up to highlight and take notes. It’s 100% free.
This is still free to read, it's not a paywall.
You need to register to keep reading, start learning with studysmarter, the only learning app you need..

Create a free account to save this explanation.
Save explanations to your personalised space and access them anytime, anywhere!
By signing up, you agree to the Terms and Conditions and the Privacy Policy of StudySmarter.
StudySmarter bietet alles, was du für deinen Lernerfolg brauchst - in einer App!
Privacy overview.
Learn C practically and Get Certified .
Popular Tutorials
Popular examples, reference materials, learn c interactively, c introduction.
- Keywords & Identifier
- Variables & Constants
- C Data Types
- C Input/Output
- C Operators
- C Introduction Examples
C Flow Control
- C if...else
- C while Loop
- C break and continue
- C switch...case
- C Programming goto
- Control Flow Examples
C Functions
- C Programming Functions
- C User-defined Functions
- C Function Types
- C Recursion
- C Storage Class
- C Function Examples
- C Programming Arrays
- C Multi-dimensional Arrays
- C Arrays & Function
- C Programming Pointers
- C Pointers & Arrays
- C Pointers And Functions
- C Memory Allocation
- Array & Pointer Examples
C Programming Strings
- C Programming String
- C String Functions
- C String Examples
Structure And Union
- C Structure
- C Struct & Pointers
- C Struct & Function
- C struct Examples
C Programming Files
- C Files Input/Output
- C Files Examples
Additional Topics
- C Enumeration
- C Preprocessors
- C Standard Library
- C Programming Examples
- Add Two Matrices Using Multi-dimensional Arrays
- Multiply Two Matrices Using Multi-dimensional Arrays
- Find Transpose of a Matrix
- Multiply two Matrices by Passing Matrix to a Function
Pass arrays to a function in C
C Multidimensional Arrays
In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example,
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns.

Similarly, you can declare a three-dimensional (3d) array. For example,
Here, the array y can hold 24 elements.
- Initializing a multidimensional array
Here is how you can initialize two-dimensional and three-dimensional arrays:
Initialization of a 2d array
Initialization of a 3d array.
You can initialize a three-dimensional array in a similar way to a two-dimensional array. Here's an example,
Example 1: Two-dimensional array to store and print values
Example 2: sum of two matrices, example 3: three-dimensional array, table of contents.
- Multidimensional array (Introduction)
- Example: 2d array to store and print values
- Example: Sum of two matrices
- Example: Three Dimensional Array
Video: C Multidimensional Arrays
Sorry about that.
Related Tutorials
C if...else Statement
Relationship Between Arrays and Pointers
C Functions
C structures, c multidimensional arrays, multidimensional arrays.
In the previous chapter, you learned about arrays , which is also known as single dimension arrays . These are great, and something you will use a lot while programming in C. However, if you want to store data as a tabular form, like a table with rows and columns, you need to get familiar with multidimensional arrays .
A multidimensional array is basically an array of arrays.
Arrays can have any number of dimensions. In this chapter, we will introduce the most common; two-dimensional arrays (2D).
Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
To create a 2D array of integers, take a look at the following example:
To create a two-dimensional array of integers, add each array within its own set of curly braces:
numbers is now an array with two arrays that contains three integers each.
The first dimension represents the number of rows [2] , while the second dimension represents the number of columns [3] . The values are placed in row-order, and can be visualized like this:
To visualize the example above, think of the numbers array as a table with two rows , where each row has three columns :

Access the Elements of a 2D Array
To access an element of a two-dimensional array, you must specify the index number of both the row and column.
This statement accesses the value of the element in the first row (0) and third column (2) of the matrix array.
Remember that: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change Elements in a 2D Array
To change the value of an element, refer to the index number of the element in each of the dimensions:
The following example will change the value of the element in the first row (0) and first column (0) :
Loop Through a 2D Array
To loop through a multi-dimensional array, you need one loop for each of the array's dimensions.
The following example outputs all elements in the matrix array:
Good To Know
Omit first dimension size.
Sometimes, when looking at other people's code, you will see that the size of the first dimension of a multidimensional array is not specified. This is valid, as C is smart enough to understand how big it is by looking at the values inside the curly braces. However, you cannot omit the size of other dimensions.
A Three-Dimensional Array
An example on how to declare a three-dimensional array:
When To Use Multidimensional Arrays
Multi-dimensional arrays are great at representing grids.

COLOR PICKER

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top Tutorials
Top references, top examples, get certified.
C Multidimensional Arrays (Two Dimensional Array in C)

Dimension of an array refers to a particular direction in which array elements can be varied. An array with a single dimension is known as a one dimensional array. An array that has a dimension greater than one, is known as a multidimensional array.
Multidimensional Arrays
In C, a multidimensional array is an array with more than one dimension, allowing you to create complex data structures to store and manipulate data efficiently. While two-dimensional arrays are the most common form of multidimensional arrays, C provides flexibility to work with arrays of higher dimensions as well.
Two-Dimensional Arrays
Two Dimensional Arrays can be thought of as an array of arrays, or as a matrix consisting of rows and columns.
Following is an example of a 2D array:
This array has 2 2 2 rows and 3 3 3 columns.
Two dimensional array in C, will follow zero-based indexing, like all other arrays in C.
Declaration of two dimensional Array in C
Now we will go over the syntax for declaring a Two-dimensional array in C.
Here i and j are the size of the two dimensions, i.e., i denotes the number of rows while j denotes the number of columns.
Here we declare a two-dimensional array in C, named A, which has 10 rows and 20 columns.
Initialization of 2D Array in C
We can initialize a two dimensional array in C in any one of the following two ways:
Method 1 To initialize a two dimensional array in C of size x * y, without using any nested brace, we can use the syntax below.
Method 2 Two dimensional array in C can also be initialized using nested braces, which makes the visualization of each row and column a bit more easier.
The syntax is as follows-
Two-dimensional array example in C
Consider a scenario where you want to store the scores of students in a small classroom. You have 4 students, and each student has taken 3 tests. This data can be efficiently represented using a 2D array.
Let's declare and initialize a 2D integer array for this purpose:
In this example:
- We declare a 2D integer array called scores with dimensions [4][3] . This represents 4 students and 3 test scores for each student.
- We initialize the array with the scores for each student using nested braces.
- We then use nested loops to access and print the scores for each student and each test.
When you run this program, it will output:
Accessing the Elements of a 2D Array
Suppose we have a 2D array representing a 3x3 grid, and we want to access and print the values of its elements.
Consider the following 2D array:
Changing Elements in a 2D Array
Suppose we have a 2D array representing a 3x3 grid, and we want to change the value of an element at a specific row and column in the grid.
As you can see, we successfully changed the value of an element in the 2D array.
Looping Through a 2D Array
- Two dimensional array in c provide a structured form to handle data in a matrix-like format, useful for various applications such as game boards, spreadsheets, and image processing.
- Declaring and initializing multidimensional array in c is straightforward, with options for single-line or nested-brace initializations to cater to different programming styles and requirements.
- Accessing and altering data within a multidimensional array is achieved through simple indexing, making it easy to update the array's contents as needed.
- Employing nested loops allows for comprehensive traversal and manipulation of array elements, which is fundamental for tasks like algorithm implementation and data analysis.

IMAGES
COMMENTS
2D refers to objects or images that show only two dimensions; 3D refers to those that show three dimensions. Because reality exists in three physical dimensions, 2D objects do not exist. However, they can be portrayed in images and art.
Autocad is a powerful computer-aided design (CAD) software used by engineers, architects, and other professionals to create detailed 2D and 3D drawings. With its vast array of features, Autocad is an invaluable tool for designing and creati...
Art limited in composition to the dimensions of depth and height is called 2D art. This includes paintings, drawings and photographs and excludes three-dimensional forms such as sculpture and architecture.
We can assign value to a 2D array by targeting the cell using the row-index and col-index. For example, if we want to assign 10 to element at row-index 0 and
But printf("%c ", t1[i][j]); does. You're not assigning @ character in the array anywhere. Let's re-write your code: Initialize the
We can calculate how many elements a two dimensional array can have by using this formula: The array arr[n1][n2] can have n1*n2 elements. The array that we have
Auxiliary Space: O(R*C), where R and C is size of row and column respectively. ... We can create an array of pointers of size r. Note that from
Two-dimensional array example in C · #include<stdio.h> · int main(){ · int i=0,j=0; · int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; · //traversing 2D array · for(i
Examples of Two Dimensional Array in C · int main() · { · float a[3][3], b[3][3], result[3][3]; · printf("Enter elements of 1st matrix\n");.
2-D or two dimensional array are represented as 'datatype variable[n][n]', where datatype can be an int, char, etc, and the [n][n] is n*n to
To write a 2D array in C, you first declare it using the syntax: `data_type array_name[row_size][column_size]`. Then, you can initialise the array by assigning
In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];.
To access an element of a two-dimensional array, you must specify the index number of both the row and column. This statement accesses the value of the element
Two dimensional array in C can also be initialized using nested braces, which makes the visualization of each row and column a bit more easier. The syntax is as