- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
C array declaration and assignment?
I've asked a similar question on structs here but I'm trying to figure out how C handles things like assigning variables and why it isn't allowed to assign them to eachother if they are functionally the same.
Lets say I have two arrays:
Why won't x = y compile? If they are both the same "signature" like that, then shouldn't you be able to assign them back and forth?
Can I declare these in a way that would allow me to do that in C? It makes sense to me that you would be able to, but maybe there is a way that this can be done? Typedefs for structs seemed to be the solution, would it be the same for array declaration and assignment?
I appreciate your guys help, I'm new to Stackoverflow but it has been a really good resource for me so far!
- variable-assignment
7 Answers 7
Simply put, arrays are not assignable. They are a "non-modifiable lvalue". This of course begs the question: why? Please refer to this question for more information:
Why does C++ support memberwise assignment of arrays within structs, but not generally?
Arrays are not pointers. x here does refer to an array, though in many circumstances this "decays" (is implicitly converted) to a pointer to its first element. Likewise, y too is the name of an array, not a pointer.
You can do array assignment within structs:
But you can't do it directly with arrays. Use memcpy .
- That code still doesn't do what he was wanting it to do though, does it? Perhaps I'm wrong, but I got the impression he was hoping to copy the contents of the y array into x. – T.E.D. Apr 13, 2009 at 18:18
- True. Fortunately, lots of other replies have indicated memcpy() is the correct choice. I'll add it in... – user82238 Apr 13, 2009 at 18:21
- 6 "The name of an array is actually the address of the first element of that array. \ The example code you provide here is attempting to assign to something which is not an l-value.": for the sake of posterity I thought I'd note that both of these sentences from the most highly voted answer are wrong. First, the name of an array most definitely is not a pointer (e.g. think sizeof()), it simply decays to a pointer in many cases. Second, the array name is an lvalue, just not a modifiable lvalue. – Alexandros Gezerlis Oct 31, 2011 at 23:32
- 3 I'm high-jacking this answer. It's top-voted and accepted, yet contained incorrect information and the user is long-gone. Hopefully this clears things up. – GManNickG Oct 5, 2016 at 6:16
This compiles and y will be the same as x .
- 3 y will be a pointer equivalent to &x[0] , due to array-to-pointer conversion, but it won't be "the same" as x is an array, not a pointer. – GManNickG Oct 5, 2016 at 6:05
Some messages here say that the name of an array yields the address of its first element. It's not always true:
In order to assign arrays you will have to assign the values inside the array.
ie. x=y is equivalent to
- thats why I am giving the equivalent! – aJ. Apr 13, 2009 at 16:55
- it gives the impression that x=y is a valid statement – Naveen Apr 13, 2009 at 16:57
- Actually in the OP its already mentioned that x=y doesn't compile. – aJ. Apr 13, 2009 at 16:58
- x=y being impossible for arrays is the entire context for this question, Naveen. – Chuck Apr 13, 2009 at 17:02
In an attempt to complement Blank's answer, I devised the following program:
When executed, the following is output:
The point is to illustrate how the copy of structures' values occurs.
When saying "int x[10]" is saying, "reserve some room for 10 integers and pass me a pointer to the location". So for the copy to make sense you'd need to operate on the memory pointed by, rather than 'the name of the memory location'.
So for copying here you'd use a for loop or memcpy().
I've used C compilers where that would compile just fine...and when run the code would make x point to y's array.
You see, in C the name of an array is a pointer that points to the start of the array. In fact, arrays and pointers are essentially interchangable. You can take any pointer and index it like an array.
Back when C was being developed in the early 70's, it was meant for relatively small programs that were barely above assembly language in abstraction. In that environment, it was damn handy to be able to easily go back and forth between array indexing and pointer math. Copying whole arrays of data, on the other hand, was a very expensive thing do do, and hardly something to be encouraged or abstracted away from the user.
Yes, in these modern times it would make way more sense to have the name of the array be shorthand for "the whole array", rather than for "a ponter to the front of the array". However, C wasn't designed in these modern times. If you want a language that was, try Ada. x := y there does exactly what you would expect; it copies one array's contents to the other.

- Friendly random ping. :) As you undoubtedly (now) know, the name of an array is not a pointer. – GManNickG Oct 5, 2016 at 6:05
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged c arrays variable-assignment or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Why is there a voltage on my HDMI and coaxial cables?
- Checking system vs. SEPA and the like
- Why do many companies reject expired SSL certificates as bugs in bug bounties?
- How to match a specific column position till the end of line?
- What Is the Difference Between 'Man' And 'Son of Man' in Num 23:19?
- The difference between the phonemes /p/ and /b/ in Japanese
- Latex Table Missing Border Lines
- What did Ctrl+NumLock do?
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- Can archive.org's Wayback Machine ignore some query terms?
- How do you ensure that a red herring doesn't violate Chekhov's gun?
- Did this satellite streak past the Hubble Space Telescope so close that it was out of focus? If so, how close was it?
- How can this new ban on drag possibly be considered constitutional?
- Bulk update symbol size units from mm to map units in rule-based symbology
- Is it possible to create a concave light?
- Seeing exoplanets with glare
- How to follow the signal when reading the schematic?
- Counting Letters in a String
- Why do academics stay as adjuncts for years rather than move around?
- How does fire heat air?
- Styling contours by colour and by line thickness in QGIS
- Seal script identification/translation
- About an argument in Famine, Affluence and Morality
- How to notate a grace note at the start of a bar with lilypond?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Coding Ground
- Corporate Training

- C Programming Tutorial
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Functions
- C - Scope Rules
- C - Pointers
- C - Strings
- C - Structures
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows −
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement −
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −
You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −
The above statement assigns the 5 th element in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above −

Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −
The above statement will take the 10 th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays −
When the above code is compiled and executed, it produces the following result −
Arrays in Detail
Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer −
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Arrays (C# Programming Guide)
- 3 minutes to read
- 15 contributors
You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object .
The following example creates single-dimensional, multidimensional, and jagged arrays:
Array overview
An array has the following properties:
- An array can be single-dimensional , multidimensional or jagged .
- The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.
- The default values of numeric array elements are set to zero, and reference elements are set to null .
- A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null .
- Arrays are zero indexed: an array with n elements is indexed from 0 to n-1 .
- Array elements can be of any type, including an array type.
- Array types are reference types derived from the abstract base type Array . All arrays implement IList , and IEnumerable . You can use the foreach statement to iterate through an array. Single-dimensional arrays also implement IList<T> and IEnumerable<T> .
Default value behaviour
- For value types, the array elements are initialized with the default value , the 0-bit pattern; the elements will have the value 0 .
- All the reference types (including the non-nullable ), have the values null .
- For nullable value types, HasValue is set to false and the elements would be set to null .
Arrays as Objects
In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members that Array has. An example of this is using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5 , to a variable called lengthOfNumbers :
The Array class provides many other useful methods and properties for sorting, searching, and copying arrays. The following example uses the Rank property to display the number of dimensions of an array.
- How to use single-dimensional arrays
- How to use multi-dimensional arrays
- How to use jagged arrays
- Using foreach with arrays
- Passing arrays as arguments
- Implicitly typed arrays
- C# Programming Guide
- Collections
For more information, see the C# Language Specification . The language specification is the definitive source for C# syntax and usage.
Submit and view feedback for
Additional resources
Trending now
.net developer job description, 10 best javascript books for 2023, blockchain career guide: a comprehensive playbook to becoming a blockchain developer, top css interview questions you should prepare for in 2023, top 12 uses of c++, top 10 python ides in 2023: choosing the best one, 20 most popular programming languages to learn in 2023, list to string in python, create a blockchain career with the iit kanpur professional certificate program, top 50+ salesforce interview questions and answers for 2023, array in c: definition, advantages, declare, initialize and more.

Table of Contents
Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures. However, in order to be stored together in a single array, all the elements should be of the same data type . The elements are stored from left to right with the left-most index being the 0th index and the rightmost index being the (n-1) index.
Basics to Advanced - Learn It All!

Array in C are of two types; Single dimensional arrays and Multidimensional arrays.
- Single Dimensional Arrays: Single dimensional array or 1-D array is the simplest form of arrays that can be found in C. This type of array consists of elements of similar types and these elements can be accessed through their indices.

- Multi-dimensional Arrays: The most common type of multi-dimensional array that is used in the C language is a 2-D array. However, the number of dimensions can be more than 2 depending upon the compiler of the user’s system. These arrays consist of elements that are array themselves.

Why Do We Need Arrays?
If we have a small number of elements, let us say we want 3 variables, then we can declare them separately like var1, var2, and var3. But if we have a large number of variables then we can use arrays to store them.
Let us take a real-life example. Suppose you want to make a program that prints 1-100 digits. Now in C language, you can achieve this by 2 methods. The first one is to make 100 variables and store the numbers from 1-100 in those variables separately and then print each digit. The second method is to create an array of size 100 and store the numbers in that array using a loop. These digits can be printed using a single loop in linear complexity. It is clear that the second method is more optimized and desirable than the first one as it is more convenient to store these values in a single array rather than creating 100 variables.
Learn the Ins & Outs of Software Development

Declaration and Initialization of Array in C
There are various ways in which an array can be declared and initialized in various ways. You can declare an array of any data type (i.e. int, float, double, char) in C. The following ways can be used to declare and initialize an array in C.
Array Declaration by Specifying the Size
Arrays can be declared by specifying the size or the number of array elements. The size of the array specifies the maximum number of elements that the array can hold. In the latest version of C, you can either declare an array by simply specifying the size at the time of the declaration or you can provide a user-specified size. The following syntax can be used to declare an array simply by specifying its size.
Image Reference
When an array is declared without allocating any value, then it stores a garbage value. If you access any uninitialized array value, then just like any uninitialized variable, it will give you a garbage value.
Learn from the Best in the Industry!

Array Declaration by Initializing Elements
An array can be initialized at the time of its declaration. In this method of array declaration, the compiler will allocate an array of size equal to the number of the array elements. The following syntax can be used to declare and initialize an array at the same time.
// initialize an array at the time of declaration.
int my_array[] = {100, 200, 300, 400, 500}
In the above syntax, an array of 5 elements is created and even though the array size has not been specified here, the compiler will allocate a size of 5 integer elements.
Array Declaration by Specifying the Size and Initializing Elements
An array can also be created by specifying the size and assigning array elements at the time of declaration. This method of array creation is different from the previous one. Here, if the number of initialized elements is less than the size of the array specified, then the rest of the elements will automatically be initialized to 0 by the compiler. See the following syntax to understand this.
// declare an array by specifying size and
// initializing at the time of declaration
int my_array1[5] = {100, 200, 300, 400, 500}; // my_array1 = {100, 200, 300, 400, 500}
int my_array2[5] = {100, 200, 300}; // my_array2 = {100, 200, 300, 0, 0}
In the above array syntax, my_array1 is an array of size 5 with all five elements initialized. Whereas, my_array2 is an array of size 5 with only three of its elements initialized. The remaining two elements of the second array will be initialized to 0 by the compiler.
Here's How to Land a Top Software Developer Job

Array Initialization Using a Loop
An array can also be initialized using a loop. The loop iterates from 0 to (size - 1) for accessing all indices of the array starting from 0. The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C.
// declare an array.
int my_array[5];
// initialize array using a "for" loop.
for(i = 0; i < 5; i++)
my_array[i] = 2 * i;
// my_array = {0, 2, 4, 6, 8}
In the above syntax, an array of size 5 is declared first. The array is then initialized using a for loop that iterates over the array starting from index 0 to (size - 1).
Access Array Elements
Since an array is stored contiguously in the memory, it has indices starting from ”0” to “array_size - 1”, also known as zero-based indexing. This indexing represents the position in the array.
The array indices are used to access any element of the array in the following way:
array_name[index]
The index of the element to be accessed is specified within square brackets “[]”. The range of the index is- integers in the range [0, size).
int my_array[6];
// access 1st element
my_array[0] = 100;
// access 4th element
my_array[2] = 300;
// access last element
my_array[5] = 600;
Get All Your Questions Answered Here!

Input and Output Array Elements
Array values can be stored by taking input from the user and storing them in the array. The following example illustrates this:
// input an integer element and store it
// in 1st position of the array
scanf("%d", &my_array[0]);
// input a float element and store it
// in ith position of the array
scanf("%f", &my_array[i-1]);
Similarly, array elements can also be displayed in the output using the printf() method. The index is specified indicating the position of the element to be printed. The following example illustrates this:
// print the element stored at 1st position or 0th index
printf("%d", my_array[0]);
// print the element stored at ith position or (i - 1)th index
printf("%d", my_array[i-1]);
Advantages of Array in C
Arrays have a great significance in the C language. They provide several advantages to the programmers while programming. Some of them are:
- Arrays make the code more optimized and clean since we can store multiple elements in a single array at once, so we do not have to write or initialize them multiple times.
- Every element can be traversed in an array using a single loop.
- Arrays make sorting much easier. Elements can be sorted by writing a few lines of code.
- Any array element can be accessed in any order either from the front or rear in O(1) time.
- Insertion or deletion of the elements can be done in linear complexity in an array.
Also Read: Difference Between Coding and Programming
Create and Showcase Your Portfolio from Scratch!

Disadvantages of Array in C
Every advantageous thing comes with some disadvantages as well. This stands true for arrays as well. Below are some of the disadvantages of the array in C:
- Accessing an array out of bounds: The first disadvantage of arrays is that they are statically allocated. This means that once their size is initialized, it can not be increased or decreased. To understand this point, consider the example given below:
#include <stdio.h>
//declaring the array of size 20
int my_array[20];
//initialising the array elements
for (int i = 0; i < 20; i++)
//i will be the value of e
//very ith element of the array
my_array[i] = i;
// Print value at index 5 of the array
printf("Element at index 5"
" is %d\n",
my_array[5]);
// Print value at index 13 of the array
printf("Element at index 13"
my_array[13]);
// Print value at index 21 of the array
printf("Element at index 21"
" is %d",
my_array[21]);
return 0;

Become a Skilled Web Developer in Just 9 Months!

In the above example, the initial value of the array arr is 20, so by printing the value of elements up to the index 20, we are getting the desired output. But when we try to print the element at the 21st index, it is giving a garbage value. This is because the array was accessed out of the bound index.
This issue can be resolved using malloc() and calloc() functions. These functions allocate the memory dynamically. We have a free() function that allows us to free the unwanted memory at our will. The below example illustrates the same:
#include <stdlib.h>
//*ptr will be storing the base
//address of the array elements
int *ptr;
int size, i;
// size of the array will be 5
size = 5;
printf("Size of the array is: %d\n", size);
// allocating the array memory
//dynamically using malloc()
ptr = (int *)malloc(size * sizeof(int));
// Checking whether the memory has
//been successfully allocated by malloc
if (ptr == NULL)
printf("Memory has not been allocated allocated\n");
exit(0);
// Memory has been successfully allocated
printf("Memory has been allocated successfully\n");
// initializing the array elements
for (i = 0; i < size; ++i)
ptr[i] = i + 1;
// Print the elements of the array
printf("The elements of the array are: ");
printf("%d ", ptr[i]);

- Homogeneity: We can store only a single type of element in the array i.e., arrays are homogeneous. We can not use it as a template. For example, if the array data type is char, then only characters can be stored in the array. If you try to store integers or any other element of a different data type, it will throw an error. To understand this point, consider the example given below:
// such declaration will throw
// Compilation Error
int my_array[6] = {1, 2, "mango", 4, 5, 6.2};
printf("Elements of the array are: ");
for (i = 0; i < 6; i++)
printf("%d ", my_array[i]);

In the above example, the data type of the array is int. But when we try to declare string and float values to the array, it throws a compilation error.
This issue can be resolved by creating a structure to store heterogeneous (non-homogeneous) values. Consider the below example to understand this concept:
// create a structure
struct example
int fruit_quant;
float fruit_rate;
char fruit_name[30];
int main()
// s1 - object of the structure
struct example s1 = {10, 90.45, "Mango"};
// accessing structure members
// using structure object
printf("%d\n", s1.fruit_quant);
printf("%f\n", s1.fruit_rate);
for (i = 0; s1.fruit_name[i] != '\0'; i++)
printf("%c", s1.fruit_name[i]);

Examples of the 1-D Array in C
The following programs illustrate declaration, initialization, input/output operations, and basic operations like insertion, deletion, sorting, and searching in the 1-D array in C.
Example 1: Array Declaration, Input, and Output
// declare an array.
int my_array[6];
printf("Enter array elements:\n");
// input array elements.
scanf("%d", &my_array[i]);
printf("\nArray elements are:\n");
// print array elements.
for (i = 0; i <= 5; i++)

In the above example, an integer array of size 6 is declared. This array can hold at most 6 integer elements. A “for loop” is used to input the array elements from the user. Similarly, a “for loop” is used to print these elements in the output. Both times the loop runs from 0 to 5, to iterate over all the array elements.
Example 2: Insertion and Deletion in an Array.
// initialize an array.
int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
// input index where the element is to be inserted.
int pos;
printf("Enter the position: ");
scanf("%d", &pos);
// input the element to be inserted.
int element;
printf("Enter the element: ");
scanf("%d", &element);
if (pos > 10)
printf("Input is invalid !");
// right shifting array elements.
for (i = 9; i >= pos - 1; i--)
my_array[i + 1] = my_array[i];
// insert the element at "pos".
my_array[pos - 1] = element;
printf("Array after insertion is:\n");
// print array elements.
for (i = 0; i <= 10; i++)
printf("% d ", my_array[i]);

In the above example, an element that needs to be inserted is taken as input. The position where this element is to be stored is also taken as input. The array elements are shifted to the right to make space for the new element. After insertion, the size of the array is incremented.
Example 3: Search an Element in the Array.
int i, element;
int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
printf("Enter element to be searched:\n");
// input element to be searched.
// traverse the array to search the element.
for (i = 0; i <= 9; i++)
if (my_array[i] == element)
// print the index at which
// the element is found.
printf("Element found at index %d", i);
break;
// if the element is not found.
if (i == 10)
printf("\nElement not found!");

In the above example, an element is taken as input from the user. The array is traversed to search this element linearly by comparing all array elements with the element to be found. If the element exists, then its index is printed and the “for loop” is exited. If the element does not exist, then the “for loop” is iterated interrupted from 0 to 9, and “i” will be equal to 10.
Example 4: Sorting Elements of an Array
int i, j, temp;
// print unsorted array.
printf("Original array is: \n");
for (i = 0; i < 10; i++)
// sort the array elements in descending order.
for (j = i + 1; j < 10; j++)
if (my_array[j] > my_array[i])
{
temp = my_array[i];
my_array[i] = my_array[j];
my_array[j] = temp;
}
// print the sorted elements.
printf("\n\nSorted array in descending order is: \n");

In the above example, an array of size 10 is initialized. The array elements are sorted in descending order using the bubble sort algorithm.
Example 5: Finding the Largest and the Smallest Element in a 1-D Array in C
#include<stdio.h>
// declare the array
int i, smallest, largest;
// assign the value of first array element
// to smallest and largest.
smallest = largest = my_array[0];
// traverse the array.
for(i = 0; i < 10; i++)
// if current element is larger than largest,
// then update the value of largest.
if(my_array[i] > largest)
largest = my_array[i];
// if current element is smaller than smallest,
// then update the value of smallest.
if(my_array[i] < smallest)
smallest = my_array[i];
// print the smallest and the largest element.
printf("The smallest element in the array is: %d", smallest);
printf("\nThe largest element in the array is: %d", largest);
printf("\n\n");

In the above program, the largest and the smallest element in an unsorted array is printed. The two variables largest and smallest are created to store the results. These variables are initialized to the first array elements. The array is traversed linearly and each element is compared with the current largest and smallest, and their values are updated if a new largest or smallest element is found.
2 Dimensional Array in C

A 2-dimensional array or 2-D array is the simplest form of multi-dimensional array in C. Each element in a 2-D array can be represented as a separate 1-D array. A 2-D array contains a certain number of rows and columns and the total number of array elements can be found by multiplying the number of rows and columns. For example, if the array is my_array[2][3], then the total number of elements in the array is 6.
A matrix is said to be a square matrix when the number of rows is equal to the number of columns. When the number of rows differs from the number of columns, the matrix is said to be a rectangle matrix. Processing a 2-D array requires a nested loop. The outer loop signifies the number of rows and the inner loop signifies the column of elements of each row. However, the significance of the outer and inner loops can be interchanged depending on whether the user wants a row order matrix or a column order matrix.

Declaration of 2-D Array in C
Syntax to declare a 2-dimensional array in c:.
// declaring a 2-d array
dataType arrayName[no_of_rows][no_of_columns];
Description of the syntax:
- dataType: This is the data type that specifies the type of elements to be stored in the array. It can be int, float, double, char.
- arrayName: This is the name of the array. To specify the name of an array, you must follow the same rules which are applicable while declaring a usual variable in C.
- no_of_rows: This is the first dimension of the array. It is an integer specifying the number of rows to be held by the array.
- no_of_columns: This is the second dimension of the array. It’s an integer value representing the number of columns of the array.
// 5 x 10 matrix.
int my_array1[5][10];
// 3 x 3 square matrix.
float my_array2[3][3];
// 2 x 1 matrix.
char my_array3[2][1];
Note: The total number of elements that the array can hold is (no_of_rows * no_of_columns). For example, an array arr[2][4] can have at most 8 elements.
Initialization of 2-D Array in C
In 1-D arrays, when an array is initialized at the time of its declaration, you can skip specifying its size. However, this scenario is different with 2-D arrays. Only the first dimension can be skipped and the second dimension is mandatory at the time of initialization.
The following ways can be used to initialize a 2-D array in C:
- The conventional way: This is the most common way to initialize an array in C. 1-D arrays equal to the number of the first dimension (or rows) are created having elements equal to the number of the second dimension (or columns).
int my_array[3][2] = {
{11, 12},
{21, 22},
{31, 32}
In the above example, 3 1-D arrays (3 = number of rows) are there with 2 elements each (2 = number of columns).
- The compact way: In this method, all array elements are written in the same line separated by commas. It looks like a 1-D array initialization. This way is not recommended as the initialized array has less readability.
int my_array[3][2] = {11, 12, 21, 22, 31, 32};
In the above example, all array elements are written inside a single pair of braces “{}”. This type of initialization is less readable.
- Using a loop: Like the 1-D arrays, 2-D arrays can also be initialized using a loop. The most commonly used loop is the “for loop”. Two nested loops are required to initialize the array.
int my_array[2][3];
// The first loop runs till the number of rows.
for(i = 0; i < 2; i++)
// second loop runs till number of columns.
for (j = 0; j < 3; j++)
my_array[i][j] = i + j;
/* my_array = {
{0, 1, 2},
{1, 2, 3}
} */
In the above example, two “for loops” are used to initialize a 2-D array. The first loop runs from 0 to the number of rows. And the second loop runs from 0 to the number of columns.
Points to Remember While 2-D Array Initialization
The second dimension is mandatory while declaring a 2-D array, whereas the first dimension can be optional. The following examples illustrate the possible mistakes that can be made while initializing a 2-D array in C:
int my_array[3][3] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}
int my_array[][3] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}
// invalid: second dimension must be specified.
int my_array[][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}
int my_array[3][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}
Examples of 2-D Array in C
The following examples illustrate the basic implementation of a 2-D array including input and output operations in a 2-D matrix and finding the transpose of a matrix.
Example 1: 2-D Array Declaration, Input, and Output.
// declaring and initializing the 2-D array.
// 2-D array with 5 rows and 2 columns.
int x[5][2] = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};
int i, j;
// print the value of each array element.
// outer loop- for rows.
for (i = 0; i < 5; i++)
// inner loop- for columns.
for (j = 0; j < 2; j++)
printf("Element at x[ %d", i);
printf("][ %d", j);
printf("] :");
printf("%d", x[i][j]);
printf("\n");

In the following example, a 2-D array of 5 rows and 2 columns has been declared and initialized. For printing, we are using two “for loops”. The outer “for loop” is printing the rows while the inner “for loop” is printing columns for every row.
Example 2: Finding Sum and Product of Two 2 Matrices
// declaring arr1 and arr2.
int arr1[2][2], arr2[2][2];
int sum[2][2], product[2][2];
// reading input for arr1 from the user.
printf("Enter the elements of arr1 : \n");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
printf("arr1[%d][%d] :", i, j);
scanf("%d", &arr1[i][j]);
printf("\n");
// reading input for arr2 from the user.
printf("Enter the elements of arr2: \n");
printf("arr2[%d][%d] :", i, j);
scanf("%d", &arr2[i][j]);
// adding the corresponding array elements.
printf("Sum array is : \n");
sum[i][j] = arr1[i][j] + arr2[i][j];
//print the sum array
printf("%d\t", sum[i][j]);
// multiplying the corresponding array elements.
printf("Product array is : \n");
product[i][j] = arr1[i][j] * arr2[i][j];
// print the product array.
printf("%d\t", product[i][j]);

For finding the addition of two matrices, the number of rows and columns should be the same in both the matrices. And for finding the product of two matrices, the number of columns in the first matrix should be the same as the number of rows in the second matrix.
To get the sum of the two matrices, a resultant matrix of the same order is declared. To get the product of the two matrices, a resultant matrix having rows equal to the first matrix and columns equal to the second matrix is declared.
Example 3: Transpose of a Matrix
Square matrix.
// declaring the matrices.
int arr[10][10], transpose[10][10];
// reading the input from the user.
printf("Enter elements of the arr\n");
scanf("%d", &arr[i][j]);
// copy the array element into another element.
transpose[j][i] = arr[i][j];
printf("Transpose of the arr:\n");
//print the transpose of the arr
printf("%d\t", transpose[i][j]);

In the above example, the transpose of a square matrix is printed. For printing the transpose of the matrix, first, the matrix elements are copied in another matrix and then the rows and the columns of the copied matrix are reversed.
Rectangular Matrix
int arr[10][10], transpose[10][10];
for (int j = 0; j < 3; j++)
scanf("%d", &arr[i][j]);
}
}
// print the transpose of the array.
for (int i = 0; i < 3; i++)

In the above example, the matrix is a rectangle matrix which means that the number of the rows is not equal to the number of the columns. The logic is the same as that in the previous example.
Example 4: Check if the Given Matrix is Sparse or Not
int row, col, a[10][10], count = 0;
// read the number of rows and columns from the user.
printf("Enter the number of rows: \n");
scanf("%d", &row);
printf("Enter the number of columns: \n");
scanf("%d", &col);
// read the elements of the matrix from the user.
printf("Enter the matrix elements: \n");
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
scanf("%d", &a[i][j]);
// print the matrix.
printf("Matrix is:\n");
printf("%d\t", a[i][j]);
// check if the matrix is sparse or not.
if (a[i][j] == 0)
count++;
if (count > ((row * col) / 2))
printf("Matrix is a sparse matrix \n");
printf("Matrix is not sparse matrix\n");

In the above example, it is checked whether the matrix is sparse or not. A sparse matrix is the one in which the number of 0’s is greater than the non-zero elements. A counter is maintained to count the number of 0’s. At last, the count of 0’s is compared with half the total number of elements of the matrix.
Arrays vs. Pointers
Arrays can behave like pointers in many circumstances such as when an array is passed to function, it is treated as a pointer. Also, pointer arithmetic is applicable to arrays. However, these two differ from each other in many ways. The following comparison chart summarizes the key differences between a pointer and an array in C.
Passing an Array to a Function
When an array in C is passed to a function, only the address of the array’s first element is passed to the function. And being contiguous in nature, the whole array can be accessed by the function using the address of the first element.
Passing an Array Element to a Function
We can pass a single array element to a function as its argument. The following examples illustrate how we can pass an array element to a function. Here, we have made a function that is simply printing the element passed to it.
//function having an int type parameter
void func(int a)
printf("Array element passed to the function is: %d", a);
//initialized 1-D array
int arr[] = { 1, 2, 3, 4, 5 };
//function call
func(arr[2]); //passing arr[2] i.e., 3 to the func.

Passing a 1-D Array to a Function
In the above section, we saw passing an array element to a function. In this section, we are going to have a look at how a 1-D array can be passed to a function through a simple example given below. Here a function has been made to which we are passing an array and its size and the function is returning the maximum element of that array.
// function find the greatest array element
int maximum(int arr[], int size)
int large = arr[0];
for(i = 0; i<size; i++)
if(arr[i]>large)
large = arr [i];
return large;
int result;
// 1-D array initialization
int arr[] = {100, 2, 1, 120, 55, 41};
int size = sizeof(arr) / sizeof(int);
// function call
result = maximum(arr, size); // 1-D array is passed to the function.
printf("The greatest array element is: %d", result);

Passing a Multidimensional Array to a Function
We can pass a matrix or a 2-D array to a matrix as well. The below example illustrates the same where a matrix is passed to a function and the function is printing that matrix.
// function to print the matrix elements
void printMatrix(int arr[3][3])
int i, j;
printf("The Matrix thus formed is: \n");
for (i = 0; i < 3; ++i)
// change the line
for (j = 0; j < 3; ++j)
{
printf("%d\t", arr[i][j]);
int arr[3][3], i, j;
// reading input from user
printf("Enter the elements: \n");
{
// passing 2-D array or a
// Matrix as an argument
printMatrix(arr);

Pointers to Array
As we have already discussed in the earlier section the relationship and difference between arrays and pointers in C. In this section, we are going to discuss how a pointer can be declared to store the address of an array.
The following advantages are achieved by declaring a pointer to an array:
- The array elements can now be accessed in multiple ways.
- The time and space complexity of the program can be reduced.
- Arrays can be manipulated more efficiently.
#include<stdio.h>
int my_array[8] = {10, 20, 30, 40, 50, 60, 70, 80};
// declare a pointer pointing to the above array.
int *my_ptr = my_array;
my_ptr = my_array;
// access an array element using the pointer.
*(my_ptr + 1) = 100;
// print array elements using the pointer.
printf( "Array elements are: \n");
for ( i = 0; i < 8; i++ ) {
printf("*(my_ptr + %d) = %d\n", i, *(my_ptr + i) );
return 0;

In the above program, a pointer *my_ptr is pointing to the array my_array. This simply means that the address of the array’s first element (i.e. my_array[0]) is stored in the pointer. The pointer now has access to all elements of the array.
That was all about Array in C
Final Thoughts!
To sum up, in this article you have learned the concept of array in C. You started with a brief introduction to the array data structure and gradually moved ahead to discuss the need, advantages, and disadvantages of arrays. Next, you saw the different ways to declare and initialize arrays in C.
Next, you learned how to access array elements and input or output elements to/from an array. Moving ahead, you saw some examples of 1D and 2D arrays. Finally, you learned how to pass an array to a function, a concept called pointers to an array, and the differences between an array and a pointer.
Why stop here? If you want to learn full-stack web development, you should definitely check out Simplilearn’s 9-month instructor-led certification training course on Full Stack Web Development. This will get you started in professional web development and you will be able to learn advanced concepts such as Agile methodologies, DevOps practices, Java and its frameworks such as Spring, Hibernate, etc., JS, CSS , HTML, etc. If you have a knack for learning new courses, you should definitely check out Simplilearn’s complete list of free courses.
If you have any queries in this “Array in C” article or suggestions for us, please mention them in the comment box and our experts answer them for you as soon as possible.
Happy Learning!
Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:
About the author.

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.
Recommended Programs
Post Graduate Program in Full Stack Web Development
*Lifetime access to high-quality, self-paced e-learning content.

What is C Programming?
Recommended resources.

The Ultimate Guide to Top Front End and Back End Programming Languages for 2021

C# Programming for Beginners

An Easy Guide To Understand The C++ Array

Combating the Global Talent Shortage Through Skill Development Programs

C Program for Prime Number

A One Stop Solution to Understand C# Arrays
- PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- Arrays in C/C++
- std::sort() in C++ STL
- Bitwise Operators in C/C++
- Core Dump (Segmentation fault) in C/C++
- Multidimensional Arrays in C / C++
- Left Shift and Right Shift Operators in C/C++
- Substring in C++
- Converting Strings to Numbers in C/C++
- rand() and srand() in C++
- Different Methods to Reverse a String in C++
- What is Memory Leak? How can we avoid?
- Command line arguments in C/C++
- Enumeration (or enum) in C
- std::string class in C++
- Function Pointer in C
- fork() in C
- C Language Introduction
- Strings in C
- Data Types in C
- Structures in C
- Power Function in C/C++
- INT_MAX and INT_MIN in C/C++ and Applications
- Taking String input with space in C (4 Different Methods)
- Modulo Operator (%) in C/C++ with Examples
- Pointer to an Array | Array Pointer
- Memory Layout of C Programs
- Static Variables in C
- TCP Server-Client implementation in C
Array of Strings in C
- Difficulty Level : Medium
- Last Updated : 02 Dec, 2022
In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array.
- var_name is the name of the variable in C.
- r is the maximum number of string values that can be stored in a string array.
- c is a maximum number of character values that can be stored in each string array.
Example:
Below is the Representation of the above program
We have 3 rows and 10 columns specified in our Array of String but because of prespecifying, the size of the array of strings the space consumption is high. So, to avoid high space consumption in our program we can use an Array of Pointers in C.
Invalid Operations in Arrays of Strings
We can’t directly change or assign the values to an array of strings in C.
Here, arr[0] = “GFG”; // This will give an Error which says assignment to expression with an array type.
To change values we can use strcpy() function in C
Array of Pointers of Strings
In C we can use an Array of pointers. Instead of having a 2-Dimensional character array, we can have a single-dimensional array of Pointers. Here pointer to the first character of the string literal is stored.
Below is the C program to print an array of pointers:
Please Login to comment...
- simmytarika5
Improve your Coding Skills with Practice
Start your coding journey now.
Learn C++ interactively.
Learn C++ practically and Get Certified .
Popular Tutorials
Popular examples, reference materials.
Learn C++ Interactively
Interactive C++ Course
C++ introduction.
- C++ Variables and Literals
- C++ Data Types
- C++ Basic I/O
- C++ Type Conversion
- C++ Operators
- C++ Comments
C++ Flow Control
- C++ if...else
- C++ for Loop
- C++ do...while Loop
- C++ continue
- C++ switch Statement
- C++ goto Statement
- C++ Functions
- C++ Function Types
- C++ Function Overloading
- C++ Default Argument
- C++ Storage Class
- C++ Recursion
- C++ Return Reference
C++ Arrays & String
- Multidimensional Arrays
- C++ Function and Array
- C++ Structures
- Structure and Function
- C++ Pointers to Structure
- C++ Enumeration
C++ Object & Class
- C++ Objects and Class
- C++ Constructors
- C++ Objects & Function
- C++ Operator Overloading
- C++ Pointers
C++ Pointers and Arrays
- C++ Pointers and Functions
- C++ Memory Management
- C++ Inheritance
- Inheritance Access Control
- C++ Function Overriding
- Inheritance Types
- C++ Friend Function
- C++ Virtual Function
- C++ Templates
Related Topics
- Access Elements of an Array Using Pointer
- Calculate Average of Numbers Using Arrays
C++ Multidimensional Arrays
- Find Largest Element of an Array
C++ Ranged for Loop
In this tutorial, we will learn to work with arrays. We will learn to declare, initialize, and access array elements in C++ programming with the help of examples.
In C++, an array is a variable that can store multiple values of the same type. For example,
Suppose a class has 27 students, and we need to store the grades of all of them. Instead of creating 27 separate variables, we can simply create an array:
Here, grade is an array that can hold a maximum of 27 elements of double type.
In C++, the size and type of arrays cannot be changed after its declaration.
- C++ Array Declaration
For example,
- int - type of element to be stored
- x - name of the array
- 6 - size of the array
Access Elements in C++ Array
In C++, each element in an array is associated with a number. The number is known as an array index. We can access elements of an array by using those indices.
Consider the array x we have seen above.

Few Things to Remember:
- The array indices start with 0 . Meaning x[0] is the first element stored at index 0 .
- If the size of an array is n , the last element is stored at index (n-1) . In this example, x[5] is the last element.
- Elements of an array have consecutive addresses. For example, suppose the starting address of x[0] is 2120 . Then, the address of the next element x[1] will be 2124 , the address of x[2] will be 2128 , and so on. Here, the size of each element is increased by 4 . This is because the size of int is 4 bytes.
C++ Array Initialization
In C++, it's possible to initialize an array during declaration. For example,

Another method to initialize array during declaration:
Here, we have not mentioned the size of the array. In such cases, the compiler automatically computes the size.
C++ Array With Empty Members
In C++, if an array has a size n , we can store upto n number of elements in the array. However, what will happen if we store less than n number of elements.
Here, the array x has a size of 6 . However, we have initialized it with only 3 elements.
In such cases, the compiler assigns random values to the remaining places. Oftentimes, this random value is simply 0 .

How to insert and print array elements?
Example 1: displaying array elements.
Here, we have used a for loop to iterate from i = 0 to i = 4 . In each iteration, we have printed numbers[i] .
We again used a range-based for loop to print out the elements of the array. To learn more about this loop, check C++ Ranged for Loop .
Note: In our range-based loop, we have used the code const int &n instead of int n as the range declaration. However, the const int &n is more preferred because:
- Using int n simply copies the array elements to the variable n during each iteration. This is not memory-efficient. &n , however, uses the memory address of the array elements to access their data without copying them to a new variable. This is memory-efficient.
- We are simply printing the array elements, not modifying them. Therefore, we use const so as not to accidentally change the values of the array.
Example 2: Take Inputs from User and Store Them in an Array
Once again, we have used a for loop to iterate from i = 0 to i = 4 . In each iteration, we took an input from the user and stored it in numbers[i] .
Then, we used another for loop to print all the array elements.
Example 3: Display Sum and Average of Array Elements Using for Loop
In this program:
- We have initialized a double array named numbers but without specifying its size. We also declared three double variables sum , count , and average . Here, sum =0 and count = 0 .
- Then we used a range-based for loop to print the array elements. In each iteration of the loop, we add the current array element to sum .
- We also increase the value of count by 1 in each iteration, so that we can get the size of the array by the end of the for loop.
- After printing all the elements, we print the sum and the average of all the numbers. The average of the numbers is given by average = sum / count;
Note: We used a ranged for loop instead of a normal for loop.
A normal for loop requires us to specify the number of iterations, which is given by the size of the array.
But a ranged for loop does not require such specifications.
- C++ Array Out of Bounds
If we declare an array of size 10 , then the array will contain elements from index 0 to 9 .
However, if we try to access the element at index 10 or more than 10 , it will result in Undefined Behaviour.
Table of Contents
- Introduction
- Access Array Elements
- Array Initialization
- Array With Empty Members
- Example: Displaying Array Elements
- Example: Store User Inputs in Array
- Example: Calculate Sum and Average
Sorry about that.
Related Tutorials
C++ Tutorial
Passing Array to a Function in C++ Programming
Try PRO for FREE

IMAGES
VIDEO
COMMENTS
Arrays in C An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it. int data [100]; How to declare an array? dataType arrayName [arraySize]; For example, float mark [5]; Here, we declared an array, mark, of floating-point type. And its size is 5.
You can do array assignment within structs: struct data { int arr [10]; }; struct data x = {/* blah */}; struct data y; y = x; But you can't do it directly with arrays. Use memcpy. Share Follow edited Nov 13, 2017 at 0:31 Jakob 343 5 15 answered Apr 13, 2009 at 16:50 user82238
An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type.
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type.
You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. C# type [] arrayName; Example
Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures. However, in order to be stored together in a single array, all the elements should be of the same data type .
In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array.
In C++, each element in an array is associated with a number. The number is known as an array index. We can access elements of an array by using those indices. // syntax to access array elements array[index]; Consider the array x we have seen above. Elements of an array in C++ Few Things to Remember: The array indices start with 0.