Generate a random array in C or C++

assign random values to array c

Today, in this tutorial, we will get to know how to generate a random array with random values in C and C++. So you will learn how to generate a random number and store the corresponding number in an array. Below you can see source codes of generating random numbers in C and C++.

Method to Generate random array in C or C++

Follow the steps::

  • Get the size of an array and declare it
  • Generate random number by inbuilt function rand()
  • Store randomly generated value in an array
  • Print the array

Rand() function::

Random value can be generated with the help of rand() function. This function does not take any parameters and use of this function is same in C and C++. Syntax to get random one digit number::

C++ program to generate a random array

Now, we will see a C++ program to generate a random array. Here we generate values between 0 and 99 by using inbuilt function rand() and assign it to a particular position in an array. Here we take the size of an array and then declares an array of particular size. Random numbers are generated by using rand() function and that number is divided by 100 and the remainder is stored in an array at a particular location. After initializing, the array is printed.

Run this code online Output::

C program to generate a random array

Now, we will see a C program to generate a random array. Here we generate values between 0 and 99 by using the inbuilt function rand() and assign it to a particular position in an array. Here we take the size of an array and then declares an array of a particular size. Random numbers are generated by using rand() function and that number is divided by 100 and the remainder is stored in an array at a particular location. After initializing, the array is printed.

Run the above program online Output::

Also read:  Find smallest prime divisor of a number in C++

7 responses to “Generate a random array in C or C++”

The C++ example doesn’t work for me. It says sz has to be a constant value. How did you get it to work?

I have just checked the code and everything is fine and working well. You can use online C++ compilers if you wish

You need to declare it as const int sz. For all future folks who dont know.

How to write float value of random number between a range in an array lets say, “300.15 to 330.55”

How to find the largest number from using the same method?

It generates the same numbers every single time for me is that not the case for everyone?

Rand function generates random number. Please check on online compilers

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Please enable JavaScript to submit this form.

Related Posts

  • Pick a random card from a deck of cards in C++
  • QuickSort Using Random Pivoting in C++
  • Pick a random element from an array in C++

Generate array with random values

I am trying to generate an array of 12 random numbers (integers) from 1-12 and there are no double values allowed (so each number from 1-12 should be in the array). I have tried a a couple of things but somehow double numbers keep being generated. Any ideas? Please help!

you make an array filled with the numbers 1..12 and swap randomly pairs. I have chosen for generating the pairs to take the index i, but you could also generate 2 random numbers and swap those. The advantage of this version is that it is a bit faster.

I don't think this code generates 12 unique numbers...

The array starts with 12 unique numbers. The code simply shuffles the order of elements in the array. At the end, the elements still contain unique values.

Lotte, you are 100% right, the code does not generate 12 unique numbers, I hardcoded them unique in the array. And as PaulS correctly states, I shuffle the contents of the array randomly. This gives you very fast a random array with those 12 unique number. (you can use 12 other numbers if you like)

If you want to generate the numbers randomly, and check if they are allready in the array, give the code below a try and check the difference in terms of speed, then try changing SIZE to 50,200 or 800 to see the scalability. Furthermore look at the difference in footprint

lotte1990: I am trying to generate an array of 12 random numbers (integers) from 1-12 and there are no double values allowed (so each number from 1-12 should be in the array).

I must be missing something - if you want 12 random integers from 1-12 without duplicates, you MUST use the numbers 1-12, and robtillaart's first solution works fine. Why didn't you like his code? If it's because of the shuffling, the random values used there makes the list random.

Related Topics

Close

Welcome.please sign up.

By signing up or logging in, you agree to our Terms of service and confirm that you have read our Privacy Policy .

Already a member? Go to Log In

Welcome.please login.

Forgot your password

Not registered yet? Go to Sign Up

  • Introduction
  • Let's start
  • Variables and literals
  • Decide if/else
  • Controlling loop
  • Inline function
  • Scope of variables
  • Std::vector
  • Std::string
  • Pre-processor
  • Classes and objects
  • Destructors
  • Initialization list
  • Constructor overloading
  • Array of objects
  • More about functions
  • Multiple inheritance
  • Virtual and abstract
  • Encapsulation
  • Friend class and function
  • Const keyword
  • Dynamic memory
  • Storage classes

Arrays in C++

In simple English, array means collection. In C++ also, an array is a collection of similar types of data. eg.- an array of int will contain only integers, an array of double will contain only doubles, etc.

Suppose we need to store the marks of 50 students in a class and calculate the average marks. Declaring 50 separate variables will do the job but no programmer would like to do so. And here comes the array in action.

How to declare an array

datatype array_name [ array_size ] ;

For example, take an integer array 'n' .

n[ ] is used to denote an array named 'n' .

So, n[6] means that 'n' is an array of 6 integers. Here, 6 is the size of the array i.e., there are 6 elements of array 'n'.

Giving array size i.e. 6 is necessary because the compiler needs to allocate space to that many integers. The compiler determines the size of an array by calculating the number of elements of the array.

Here 'int n[6]' will allocate space to 6 integers.

We can also declare an array by another method.

int n[ ] = { 2,3,15,8,48,13 };

In this case, we are declaring and assigning values to the array at the same time. Hence, no need to specify the array size because the compiler gets it from { 2,3,15,8,48,13 }.

Following is the pictorial view of the array.

0,1,2,3,4 and 5 are the indices. It is like these are the identities of 6 different elements of the array. Index starts from 0. So, the first element has index 0. We access the elements of an array by writing array_name[index] .

Here, n[0] is 2 n[1] is 3 n[2] is 15 n[3] is 8 n[4] is 48 n[5] is 13

Initializing an array

By writing int n[ ]={ 2,4,8 }; , we are initializing the array.

But when we declare an array like int n[3]; , we need to assign the values to it separately. Because 'int n[3];' will definitely allocate the space of 3 integers in the memory but there are no integers in that.

To assign values to the array, assign a value to each of the element of the array.

n[0] = 2; n[1] = 4; n[2] = 8;

It is just like we are declaring some variables and then assigning the values to them.

int x,y,z; x=2; y=4; z=8;

Thus, the two ways of initializing an array are:

int n[ ]={ 2,4,8 };

and the second method is declaring the array first and then assigning the values to its elements.

int n[3]; n[0] = 2; n[1] = 4; n[2] = 8;

You can understand this by treating n[0], n[1] and n[2] as different variables you used before.

Just like a variable, an array can be of any other data type also.

float f[ ]= { 1.1, 1.4, 1.5};

Here, f is an array of floats.

First, let's see the example to calculate the average of the marks of 3 students. Here, marks[0], marks[1] and marks[2] represent the marks of the first, second and third student respectively.

Here, you have seen a working example of array. We treated the array in the exact similar way as we had treated normal variables.

We can also use for loop as in the next example.

The above code was just to make you familiar with using loops with an array because you will be doing this many times later.

The code is simple, i and j starts from 0 because index of an array starts from 0 and goes up to 9 ( for 10 elements ). So, i and j goes up to 9 and not 10 ( i<10 and j<10 ) . So in the above code, n[i] will be n[0], n[1], n[2], ...., n[9].

There are two for loops in the above example. In the first for loop, we are taking the values of the different elements of the array from the user one by one. In the second for loop, we are printing the values of the elements of the array.

Let's go to the first for loop. In the first iteration, the value of i is 0, so 'n[i]' is 'n[0]'.Thus by writing cin >> n[i]; , the user will be asked to enter the value of n[0]. Similary in the second iteration, the value of 'i' will be 1 and 'n[i]' will be 'n[1]'. So 'cin >> n[i];' will be used to input the value from the user for n[1] and so on. 'i' will go up to 9, and so indices of the array ( 0,1,2,...,9).

Suppose we initialize an array as

int n[5] = { 12, 13, 5 };

This means that n[0]=12, n[1]=13 and n[2]=5 and rest all elements are zero i.e. n[3]=0 and n[4]=0.

int n[5]; n[0] = 12; n[1] = 13; n[2] = 5;

In the above code, n[0], n[1] and n[2] are assigned values 12, 13 and 5 respectively. Therefore, n[4] and n[5] are both 0.

Pointer to Arrays

Till now, you have seen how to declare and assign values to an array. Now, you will see how we can have pointers to arrays too. But before starting, we are assuming that you have gone through Pointers. If not, then first read the topic Pointers and practice some problems from the Practice section.

As we all know that pointer is a variable whose value is the address of some other variable i.e., if a variable y points to another variable x means that the value of the variable 'y' is the address of 'x'.

Similarly, if we say that a variable y points to an array n , then it means that the value of 'y' is the address of the first element of the array i.e., n[0]. So, y is the pointer to the array n.

If p is a pointer to the array age , then it means that p(or age) points to age[0].

int age[50]; int *p; p = age;

The above code assigns the address of the first element of age to p.

Now, since p points to the first element of the array age , *p is the value of the first element of the array.

So, *p is age[0], *(p+1) is age[1], *(p+2) is age[2].

Similarly, *age is age[0] ( value at age ), *(age+1) is age[1] ( value at age+1 ), *(age+2) is age[2] ( value at age+2 ) and so on.

That's all in pointer to arrays.

Now let's see some examples.

Since p is pointing to the first element of array, so, *p or *(p+0) represents the value at p[0] or the value at the first element of p . Similarly, *(p+1) represents value at p[1] . So *(p+3) and *(p+4) represent the values at p[3] and p[4] respectively. So, accordingly, we will get the output.

The above example sums up the above concepts. Now, let's print the address of the array and also individual elements of the array.

In the above example, we saw that the address of the first element of n and p is the same. We also printed the values of other elements of the array by using (p+1), (p+2) and (p+3).

Passing the whole Array in Function

In C++, we can pass an element of an array or the full array as an argument to a function.

Let's first pass a single array element to a function.

Passing an entire Array in a Function

We can also pass a whole array to a function by passing the array name as argument. Yes, the trick is that we will pass the address of array, that is the address of the first element of the array. Thus, by having the pointer of the first element, we can get the entire array as we have done in the above examples.

passing array to function in C++

Let's see an example to understand this.

average(float a[]) - It is the function that is taking an array of float. And rest of the body of the function is performing accordingly.

b = average(n) - One thing you should note here is that we passed n . And as discussed earlier, n is the pointer to the first element or pointer to the array n[] . So, we have actually passed the pointer.

In the above example in which we calculated the average of the values of the elements of an array, we already knew the size of the array i.e., 8.

Suppose, we are taking the size of the array from the user. In that case, the size of the array is not fixed. Here, we need to pass the size of the array as the second argument to the function.

The code is similar to the previous one except that we passed the size of array explicitly - float average(float a[], int size) .

We can also pass an array to a function using pointers. Let's see how.

In the above example, the address of the array i.e., address of n[0] is passed to the formal parameters of the function.

void display(int *p) - This means that the function 'display' is taking a pointer of an integer and not returning any value.

Now, we passed the pointer of an integer i.e., pointer of array n[] - 'n' as per the demand of our function 'display'. Since p is the address of the array n[] in the function 'display', i.e., the address of the first element of the array (n[0]), therefore *p represents the value of n[0]. In the for loop in the function, p++ increases the value of p by 1. So when i=0, the value of *p gets printed. Then p++ increases *p to *(p+1) and thus in the second loop, the value of *(p+1) i.e. n[1] gets printed. This loop continues till i=7 when the value of *(p+7) i.e. n[7] gets printed.

passing array to function

For-each loop

There is a new form of for loop which makes iterating over arrays easier. It is called for-each loop. It is used to iterate over an array. Let's see an example of this.

This is very simple. Here, the variable m will go to every element of the array ar and will take its value. So, in the first iteration, m is the 1 st element of array ar i.e. 1. In second iteration, it is the 2 nd element i.e. 2 and so on. Just focus on the syntax of this for loop, rest of the part is very easy.

What if arrays are 2 dimensional?

Yes, 2-dimensional arrays also exist and are generally known as matrix . These consist of rows and columns.

Before going into its application, let's first see how to declare and initialize a 2 D array.

Similar to one-dimensional array, we define 2-dimensional array as below.

int a[2][4];

Here, a is a 2-D array of type int which consists of 2 rows and 4 columns .

Now let's see how to initialize a 2-dimensional array.

Initialization of 2 D Array

Same as in one-dimensional array, we can assign values to a 2-dimensional array in 2 ways as well.

In the first method, just assign a value to the elements of the array. If no value is assigned to any element, then its value is assigned zero by default.

Suppose we declared a 2-dimensional array a[2][2] . Then to assign it values, we need to assign a value to its elements.

int a[2][2]; a[0][0]=1; a[0][1]=2; a[1][0]=3; a[1][1]=4;

The second way is to declare and assign values at the same time as we did in one-dimensional array.

int a[2][3] = { 1, 2, 3, 4, 5, 6 };

Here, value of a[0][0] is 1, a[0][1] is 2, a[0][2] is 3, a[1][0] is 4, a[1][1] is 5 and a[1][2] is 6.

We can also write the above code as:

int a[2][3] = {     {1, 2, 3},     {4, 5, 6 } };

Let's consider different cases of initializing an array.

int a[2][2] = { 1, 2, 3, 4 }; /* valid */ int a[ ][2] = { 1, 2, 3, 4 }; /* valid */ int a[2][ ] = { 1, 2, 3, 4 }; /* invalid */ int a[ ][ ] = { 1, 2, 3, 4 }; /* invalid */

Why use 2 D Array?

Suppose we have 3 students each studying 2 subjects (subject 1 and subject 2) and we have to display the marks in both the subjects of the 3 students. Let's input the marks from the user.

In the above example, firstly we defined our array consisting of 3 rows and 2 columns as float marks[3][2];

Here, the elements of the array will contain the marks of the 3 students in the 2 subjects as follows.

In our example, firstly we are taking the value of each element of the array using a for loop inside another for loop.

In the first iteration of the outer for loop, value of 'i' is 0. With the value of 'i' as 0, when the inner for loop first iterates, the value of 'j' becomes zero and thus marks[i][j] becomes marks[0][0]. By writing cin >> marks[i][j]; , we are taking the value of marks[0][0].

After that, the inner for loop again iterates and the value of 'j' becomes 1. marks[i][j] becomes marks[0][1] and its value is taken from the user.

Then, the outer loop iterates for the second time and the value of 'i' becomes 1 and the whole process continues.

After assigning the values to the elements of the array, we are printing the values of the elements of the array, in the same way, using another for loop inside for loop.

Let's see one more example of 2 D Array

Suppose there are 2 factories and each of these factories produces items of 4 different types like some items of type 1, some items of type 2 and so on. We have to calculate the total product of each factory i.e. sum of the items of each type that a factory produces.

Here, s[0][i] represents the number of items of the first factory and type i, where i takes value from 0 to 3 using for loop and s[1][i] represents the nunmber of items of the second factory of type i. E.g. - s[0][2] represents the third type of item of first factory and s[1][2] represents the third type of item of second factory. sum1 is the sum of all these items of factory 1. Similar is the case of the second factory.

So, initally, sum1 is 0. Now in first iteration, s[0][i] is s[0][0]. This means that it will represent number of first item of first factory. So, sum1 += s[0][i] will become sum1 += s[0][0] . So, sum1 will become 2. Similarly in second iteration, s[0][i] will become s[0][1] and will represent the second type of items of first factory. Now, sum1 will become 2+5 i.e. 7 . Similarly things will go further.

You practice and you get better. It's very simple. -Phillip Glass

  • Making a stack using an array in C
  • Making a queue using an array in C
  • Sorting an array using bubble sort in C
  • Sorting an array using selection sort in C
  • Sorting an array using insertion sort in C
  • Generating permutations of all elements of an array

BlogsDope App

Learn C++ practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c++ interactively, 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

C++ Tutorials

  • Calculate Average of Numbers Using Arrays
  • Access Elements of an Array Using Pointer
  • Find Largest Element of an Array

C++ Ranged for Loop

C++ Multidimensional Arrays

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 all their grades. 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.

C++ Array Declaration

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,

C++ Array Initialization

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 up to 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. Often, this random value is simply 0 .

C++ Array with empty members

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 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 behavior.

Also Read :

  • C++ Pointer and Arrays

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

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • Properties of Array in C
  • Length of Array in C

Multidimensional Arrays in C

  • Initialization of Multidimensional Array in C
  • Jagged Array or Array of Arrays in C with Examples
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • How to pass an array by value in C ?
  • Variable Length Arrays (VLAs) in C
  • What are the data types for which it is not possible to create an array?
  • Strings in C
  • Array of Strings in C
  • C Library - <string.h>
  • C String Functions
  • What is the difference between single quoted and double quoted declaration of char array?
  • Array C/C++ Programs
  • String C/C++ Programs

Prerequisite: Arrays in C

A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays is generally stored in row-major order in the memory.

The general form of declaring N-dimensional arrays is shown below.

  • data_type : Type of data to be stored in the array.
  • array_name : Name of the array.
  • size1, size2,…, sizeN : Size of each dimension.

Size of Multidimensional Arrays:

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example:

  • The array int x[10][20] can store total (10*20) = 200 elements.
  • Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

To get the size of the array in bytes, we multiply the size of a single element with the total number of elements in the array. For example:

  • Size of array int x[10][20] = 10 * 20 * 4  = 800 bytes.      (where int = 4 bytes)
  • Similarly, size of int x[5][10][20] = 5 * 10 * 20 * 4 = 4000 bytes.      (where int = 4 bytes)

The most commonly used forms of the multidimensional array are:

  • Two Dimensional Array
  • Three Dimensional Array

Two-Dimensional Array in C

A two-dimensional array or 2D array in C is the simplest form of the multidimensional array. We can visualize a two-dimensional array as an array of one-dimensional arrays arranged one over another forming a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and the column number ranges from 0 to (y-1).

graphical representation of two dimensional array

Graphical Representation of Two-Dimensional Array of Size 3 x 3

Declaration of Two-Dimensional Array in C

The basic form of declaring a 2D array with x rows and y columns in C is shown below.

  • data_type: Type of data to be stored in each element.
  • array_name: name of the array
  • x: Number of rows.
  • y: Number of columns.

We can declare a two-dimensional integer array say ‘x’ with 10 rows and 20 columns as:

Note: In this type of declaration, the array is allocated memory in the stack and the size of the array should be known at the compile time i.e. size of the array is fixed. We can also create an array dynamically in C by using methods mentioned here.

Initialization of Two-Dimensional Arrays in C

The various ways in which a 2D array can be initialized are as follows:

  • Using Initializer List
  • Using Loops

1. Initialization of 2D array using Initializer List

We can initialize a 2D array in C by using an initializer list as shown in the example below.

First Method:

The above array has 3 rows and 4 columns. The elements in the braces from left to right are stored in the table also from left to right. The elements will be filled in the array in order: the first 4 elements from the left will be filled in the first row, the next 4 elements in the second row, and so on.

Second Method (better) :

This type of initialization makes use of nested braces. Each set of inner braces represents one row. In the above example, there is a total of three rows so there are three sets of inner braces. The advantage of this method is that it is easier to understand.

Note: The number of elements in initializer list should always be less than or equal to the total number of elements in the array.

We can also declare the array without defining the size of the row if we are using list initialization. The compiler will automatically deduce the size of the array in this case:

It is still compulsory to define the number of columns.

2. Initialization of 2D array using Loops

We can use any C loop to initialize each member of a 2D array one by one as shown in the below example.

This method is useful when the values of each element have some sequential relation.

Accessing Elements of Two-Dimensional Arrays in C

Elements in 2D arrays are accessed using row indexes and column indexes. Each element in a 2D array can be referred to by:

  • i: The row index.
  • j: The column index.

The above example represents the element present in the third row and second column.

Note : In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for row index 2 row number is 2+1 = 3. To output all the elements of a Two-Dimensional array we can use nested for loops. We will require two ‘ for ‘ loops. One to traverse the rows and another to traverse columns.

For printing the whole array, we access each element one by one using loops. The order of traversal can be row-major order or column-major order depending upon the requirement. The below example demonstrates the row-major traversal of a 2D array.

Time Complexity: O(N*M) , where N(here 3) and M(here 2) are numbers of rows and columns respectively.

Space Complexity:O(1)

How 2D Arrays are Stored in the Memory?

The elements of the 2-D array have to be stored contiguously in memory. As the computers have linear memory addresses, the 2-D arrays must be linearized so as to enable their storage. There are two ways to achieve linearization of array elements:

  • Row-major- The linearization technique stores firstly the first row of the array, then the second row of the array, then the third row, and so on. (i.e. elements are stored row-wise. Rows are listed on the basis of columns)
  • Column-major – This linearization technique stores first the first column, then the second column, then the third column, and so on i.e. (elements are stored column-wise. Columns are listed on the basis of rows)

The computer does not keep track of the addresses of all the elements of the array but does keep track of the Base Address (starting address of the very first element) and calculates the addresses of the elements when required.

To know more, refer to the article – Calculation of address of element of 1-D, 2-D, and 3-D

Three-Dimensional Array in C

A Three Dimensional Array or 3D array in C is a collection of two-dimensional arrays. It can be visualized as multiple 2D arrays stacked on top of each other.

graphical representation of three dimensional array

Graphical Representation of Three-Dimensional Array of Size 3 x 3 x 3

Declaration of Three-Dimensional Array in C

We can declare a 3D array with x 2D arrays each having y rows and z columns using the syntax shown below.

  • x: Number of 2D arrays.
  • y: Number of rows in each 2D array.
  • z: Number of columns in each 2D array.

Initialization of Three-Dimensional Array in C

Initialization in a 3D array is the same as that of 2D arrays. The difference is as the number of dimensions increases so the number of nested braces will also increase.

A 3D array in C can be initialized by using:

  • Initializer List

Initialization of 3D Array using Initializer List

Method 2(Better) :  

Again, just like the 2D arrays, we can also declare the 3D arrays without specifying the size of the first dimensions if we are using initializer list for initialization. The compiler will automatically deduce the size of the first dimension. But we still need to specify the rest of the dimensions.

Initialization of 3D Array using Loops

It is also similar to that of 2D array with one more nested loop for accessing one more dimension.

Accessing elements in Three-Dimensional Array in C

Accessing elements in 3D Arrays is also similar to that of 2D Arrays. The difference is we have to use three loops instead of two loops for one additional dimension in 3D Arrays.

  • x: Index of 2D array.
  • y: Index of that 2D array row.
  • z: Index of that 2D array column.

In similar ways, we can create arrays with any number of dimensions. However, the complexity also increases as the number of dimensions increases. The most used multidimensional array is the Two-Dimensional Array.

Arrays are also closely related to pointers in C language. To know more about the Relationship of Arrays with Pointers in C, refer to this article.

Please Login to comment...

  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Using a pointer to assign random numbers

  Using a pointer to assign random numbers to array.

assign random values to array c

IMAGES

  1. Fill An Array With Random Numbers

    assign random values to array c

  2. How to Assign and Re-assign Values to Arrays in C++

    assign random values to array c

  3. How to fill an array with a random numbers in C++?

    assign random values to array c

  4. C Language

    assign random values to array c

  5. How to generate random numbers for a given range in C++

    assign random values to array c

  6. Arrays in C#

    assign random values to array c

VIDEO

  1. How to generate random strings from a set of characters in C

  2. How to generate random numbers in C++

  3. Python Variables

  4. 3D render of a rotating the beam in a circular phased array

  5. PHP Assign Multiple Values

  6. PHP Array Extract & Compact Function Tutorial in Bangla #phpbanglatutorial #phpbangla

COMMENTS

  1. c

    Now, once you have the random numbers, you need to assign it to the each array member like numbers[i] = randNumber; inside the loop, but there's more to it. Your loop, at present is off by one. Your loop, at present is off by one.

  2. Generate a random array in C or C++

    C program to generate a random array. Now, we will see a C program to generate a random array. Here we generate values between 0 and 99 by using the inbuilt function rand() and assign it to a particular position in an array. Here we take the size of an array and then declares an array of a particular size.

  3. C program to generate random numbers within a range

    Generate random numbers using srand () function. The srand () function is used to set the starting value for the series of random integers. You can use the srand () to set the seed of the rand function to a different starting point. The parameters that are passed into the srand () function are the starting values for the rand method.

  4. Generating random number in a range in C

    C does not have an inbuilt function for generating a number in the range, but it does have rand function which generates a random number from 0 to RAND_MAX. With the help of rand () a number in range can be generated as num = (rand () % (upper - lower + 1)) + lower. C. // random number in a given range. #include <stdio.h>.

  5. Fill An Array With Random Numbers

    Example of initializing an array with random integers between 1 and a max integer using C. Source code: https://github.com/portfoliocourses/c-example-code/b...

  6. C Arrays

    Initialization in C is the process to assign some initial value to the variable. When the array is declared or allocated memory, the elements of the array contain some garbage value. ... The array in C provides random access to its element i.e we can get to a random element at any index of the array in constant time complexity just by using its ...

  7. C Arrays (With Examples)

    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. ... Change Value of Array elements int mark[5] = {19, 10, 8, 17, 9} // make the value of the third element to -1 mark[2] = -1; // make the value of the fifth element to 0 mark[4] = 0;

  8. Arrays in C

    Assigning Values to Array. By writing int n[ ]={ 2,4,8 };, we are declaring and assigning values to the array at the same time, thus initializing it. But when we declare an array like int n[3];, we need to assign values to it separately. Because 'int n[3];' will definitely allocate space of 3 integers in memory but there are no integers in that ...

  9. rand() in C

    The rand () function in the C programming language is used to generate pseudo-random numbers. It is used in C to generate random numbers in the range 0 to RAND_MAX. The rand () function is part of the standard C library <stdlib.h> so to use this function, we need to include the <stdlib.h> library.

  10. Assign Random Values to Index of Array : r/C_Programming

    Assign Random Values to Index of Array . Can someone please explain to me if it is possible and if so, how to assign a set of numbers to the index of an array and print them randomly. For example: int a[5]={1,2}; Can I create a for loop that prints out 1 and 2 in a random order instead of the following?

  11. Integer Array in C

    The general syntax for declaring an array in C looks as you can see it in the code snippet below: data_type array_name[array_size]; Let's take the following example: int my_numbers[5]; Let's break it down: I first defined the data type of the array, int. I then specified the name, my_numbers, followed by a pair of opening and closing square ...

  12. Generate array with random values

    If you want to generate the numbers randomly, and check if they are allready in the array, give the code below a try and check the difference in terms of speed, then try changing SIZE to 50,200 or 800 to see the scalability. Furthermore look at the difference in footprint. #define SIZE 12 // change this to 800.

  13. Dynamic Array in C

    1. Dynamic Array Using malloc () Function. The "malloc" or "memory allocation" method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It is defined inside <stdlib.h> header file. Unmute.

  14. C++ array: declare, initialize, passing array to function, pointer to

    In the first method, just assign a value to the elements of the array. If no value is assigned to any element, then its value is assigned zero by default. Suppose we declared a 2-dimensional array a [2] [2]. Then to assign it values, we need to assign a value to its elements. int a [2] [2]; a [0] [0]=1; a [0] [1]=2;

  15. C++ Arrays (With Examples)

    C++ Arrays. 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 all their grades. Instead of creating 27 separate variables, we can simply create an array: double grade[27]; Here, grade is an array that can hold a maximum of 27 elements of double type.

  16. How do I input random numbers in C++ array?

    The secret sauce of getting the random numbers into your array is a loop. Make your loop visit every element and assign a new random number. Either directly, as in my first example, or by using a function as in my second example. const int minValue = -100; const int maxValue = 100; const int size = 10;

  17. Multidimensional Arrays in C

    Three Dimensional Array; Two-Dimensional Array in C. A two-dimensional array or 2D array in C is the simplest form of the multidimensional array. We can visualize a two-dimensional array as an array of one-dimensional arrays arranged one over another forming a table with 'x' rows and 'y' columns where the row number ranges from 0 to (x ...

  18. Using a pointer to assign random numbers to array.

    Write a program that queries the user for the size and then declares an integer array of that size. Create a pointer to the first element of the array and then use the pointer to fill the array with random integer values in the range 3-17. Then print each element of the array with its address to the screen. And this is what I have so far: 1. 2. 3.

  19. C array declaration and assignment?

    "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.