Samurai Technique to Learn Arrays in C and C++

Arrays in C and C++ are a collection of similar data types that are accessed using a common name. For a clear understanding, let’s consider a problem, where we want to store and display the salary of 10 employees in an organization. Before learning the concept of arrays, you would find this problem a tedious task and would probably come up with the solution: “Declare 10 floating-type variables, each representing the salary of the 10 employees respectively, use scanf/cin statement to store their respective values and printf/cout statement to display it.”

Now, what if the number of employees whose salary to be stored and displayed goes up to 100? It is practically not feasible to go by this conventional method. The simple solution to this onerous problem is by the implementation of arrays. In a nutshell, arrays in C/C++ are used when we have a large number of objects in hand. It proves to be quite helpful to manage data.

Arrays in C and C++ tutorial cover the following topics-

Arrays in C and C++

1. Arrays in C and C++

An array is a data structure, a sequential collection of similar data types that can easily be accessed using a common variable name. It is similar to the concept of a list in Python when talking about a single-dimensional array. 

Arrays in C/C++ can have multiple dimensions, starting from one-dimension to numerous. Dimensions are positive integral numbers. It cannot have a floating-type value.

The trivial names of the various dimensions of arrays are as follows:

  1. One-dimensional array – Vectors
  2. Two-dimensional array – Matrix

An array is a generalized term when its dimension is unspecified.

2. Declaration of Arrays in C/C++

Arrays are declared in a similar fashion like any other variable of the same data type with addition to the use of square brackets, which is followed by the variable name. As soon as an array is declared in C and C++, a block of memory is reserved for it. The total size of an array is the product of the number of elements it has in its square bracket and the size of the data type it stores.

Don’t forget to check, how to declare variables in C/C++

When an array is multidimensional, let’s say:

data_type array_name [order-1] [order-2] [order-3]……….[order-n]

The total size occupied by the array would be:

(Number of bytes occupied by data_type) x (order-1 x order-2 x order-3 x ……….order-n)

Once the orders of the array are specified, it cannot be changed. In other words, the size of an array remains constant which is used in static memory allocation i.e. it is not dynamic in nature.

Syntax of Arrays

data_type array_name [ size ];

For example- float marks [10];

3. Data Type of an Array

An array can have any data type like int, float, char but there are 2 exceptions in the C language which do not support arrays. They are:

  • void data type: It is not supported in C and hence would display a compilation error.
  • Functions: Array of pointers and function pointers are not possible

Take a break of 4 min and learn data types in C and C++

4. Initializing Arrays in C and C++

Arrays in C/C++ may or may not be initialized at the time of declaration.

This is how an array looks like if it is initialized at the time of declaration.

  • Without size specification
int array [ ] = {4 , 9 , 2 , 1};
  • With size specification
int array [10] = {4 , 9, 2 , 1};

Let us now try to understand how elements are stored when they are initialized.

Since there are 4 elements in the array, 4 x 4 bytes, that is, 16 bytes of memory is reserved for the array which can be visualized as:

array[ 0 ]array [ 1 ]array[ 2 ]array[ 3 ]
4921

The indexing of an array starts from 0. Hence the indexing of the elements goes from 0 to size of the array – 1.

5. Accessing Arrays

Elements in an array are accessed with the help of their index. The index helps us in traversing the array.

How to Access Arrays in C?

Let’s discuss with an example, how elements are accessed in an array:

#include<stdio.h>
int main()
{

printf("Welcome to DataFlair tutorials!\n\n");

int size_of_array, iteration;
int array [30];
printf("Enter the size of the array: ");
scanf("%d", &size_of_array);
printf("Enter the elements of the array:\n");
for(iteration = 0 ; iteration < size_of_array ; iteration ++ )
{
scanf("%d", &array[iteration]);
}
printf("The array is:\n");
for(iteration = 0 ; iteration < size_of_array ; iteration ++ )
{
printf("The element at index %d is: %d\n",iteration, array[iteration]);
}
return 0;
}

Struggling with programs in C? Get a free tutorial for the basic structure of C program

Code on Screen-

How to access an array in C

Output-

Accessing Arrays in C

How to Access Arrays in C++?

Here is a code in C++ that illustrates how elements are accessed in an array:

#include <iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

int size_of_array, iteration;
int array [30];
cout<<"Enter the size of the array: ";
cin>>size_of_array;
cout<<"Enter the elements of the array: "<<endl;
for(iteration = 0 ; iteration < size_of_array ; iteration ++ )
{
cin>>array[iteration];
}
cout<<"The array is: "<<endl;
for(iteration = 0 ; iteration < size_of_array ; iteration ++ )
{
cout<<"The element at index "<< iteration << "is:" << array[iteration] <<endl;
}
return 0;
}

Code – 

Accessing Arrays in C++

Output-

Output of Accessing Arrays in C++

We declare a variable size_of_array, so that the user can specify the length of the array and a variable iteration to traverse the array with the help of a for loop. We know that the indexing of the array starts from 0. Hence, we initialize the variable ‘iteration’ to 0 till ‘iteration’ becomes less than the size of the array. Thereafter, we increment the variable ‘iteration’ so that the loop continues to run until the condition is satisfied.

Loops in C and C++ – The Survival Guide for Every Beginner

6. Multidimensional Arrays

The most popular form of multidimensional arrays is the two-dimensional arrays by which matrices can be implemented. Three-dimensional arrays and other higher dimensions aren’t as popularly used and hence we will restrict our discussion to simply two-dimensional arrays.

7. Passing Array to a Function

Before we begin our discussion on passing arrays to a function, it is important to understand functions in C/C++.

Functions are nothing but a group of statements designed to serve a specific purpose. It helps the user to divide the code into smaller fragments instead of loading everything inside the main function. It even offers the benefit of code reusability.

An array can be passed to a function in 2 ways, namely:

1. Call by value

In this method, the actual parameter gets copied to the formal parameters. As the name itself suggests, the actual value is passed to the function. Any changes made to the formal parameters are not reflected in the actual parameters passed to the function

2. Call by reference

In this method, instead of the actual parameter, the address of the actual parameters is passed to the formal parameters. Hence, any changes made in the actual parameters are reflected in the formal parameters.

Let us consider some problems that involve the use of passing an array to the function using call by value and call by reference.

7.1 Example of Call By Value (Passing Single/Entire Element)

C program to pass a single element to the function

Here is a code in C that illustrates the use of call by value to pass an array to the function:

#include <stdio.h>
void output(int values)
{
printf("The value of the 5th element of the array is: %d\n", values);
}
int main()
{
printf("Welcome to DataFlair tutorials!\n\n");
int array[6] = {10, 20, 30, 40, 50, 60};
output(array[5]); // Passing the 5th element of the array
return 0;
}

Code on Screen-

 pass a single element to the function

Output-

Output of Pass a array to the function

2. C++ program to pass a single element to the function
#include <iostream>
using namespace std;

void output(int values)
{
cout<<"The value of the 5th element of the array is: "<< values <<endl;
}

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
int array[6] = {10, 20, 30, 40, 50, 60};
output(array[5]); // Passing the 5th element of the array
return 0;
}

Code-

Pass single element to function in C++

Output-

Pass single element to function in C++ with result

3. C program to pass the entire array to the function
#include <stdio.h>
void display( char c)
{
  printf("%c ", c);
}
int main()
{
printf("Welcome to DataFlair tutorials!\n\n");
int i;
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
for (i=0; i<5; i++)
{
display(vowels[i]);
}
return 0;
}

Code on Screen-

pass the entire array to the function

Output-

pass the entire array to the function

4. C++ program to pass the entire array to the function
#include <iostream>
using namespace std;

void display( char c)
{
cout<<c;
}
int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

int i;
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
for (i=0; i<5; i++)
{
display(vowels[i])<<endl;
}
return 0;
}

Code-

Pass Entire element to function in C++

Output-

Pass Entire element to function in C++ with result

7.2 Example of Call by Reference

Call by reference to pass an array to the function in C-
#include <stdio.h>
void display( int *powers)
{
printf("%d ", *powers);
}
int main()
{
printf("Welcome to Dataflair tutorials!\n\n");
int i;
int array[] = {1, 2, 4, 9, 25, 36, 49, 64, 81, 100};
for (i=0; i<10; i++)
{
display(&array[i]); // Passing the address of array to the function
}
return 0;
}

Code on Screen-

 call by reference to pass an array to the function

Output-

call by reference to pass an array

Call by reference to pass an array to the function in C++
#include <iostream>
using namespace std;

void display( int *powers)
{
cout<<*powers;
}

int main()
{

cout<<"Welcome to Dataflair tutorials!"<<endl<<endl;

int i;
int array[] = {1, 2, 4, 9, 25, 36, 49, 64, 81, 100};
for (i=0; i<10; i++)
{
display(&array[i]); // Passing the address of array to the function
cout<<"\t";
}

return 0;
}

Code-

Call by reference to pass an array to the function in C++

Output-

Call by reference to pass an array to the function in C++ with result

8. Pointer to an Array

Before we begin our discussion on a pointer to an array, it is important to understand pointers in C and C++.

Pointers are nothing but simple variables that allow you to access the memory address of another variable to which the pointer points to.

In C, you can access the value of an element of an array, or better, the entire array with the help of a pointer.

Example of Implementation of a pointer to an array in C:
#include<stdio.h>
int main()
{
printf("Welcome to DataFlair tutorials!\n\n");
int i;
double array[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
double *p;
p = array;
printf( "The array is:\n");
for ( i = 0; i < 5; i++ )
{
printf("%0.2f\n", *(p + i) ); // Pointer to an array
}
return 0;
}

Code on Screen-

Pointer to an Array

Output-

Pointer to an Array in C

Example of Implementation of a pointer to an array in C++:
#include <iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

int i;
double array[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
double *p;
p = array;
cout<<"The array is: "<<endl;
    
for ( i = 0; i < 5; i++ )
{
cout<<*(p + i); // Pointer to an array
cout<<endl; 
}
return 0;
}

Code-

Implementation of a pointer to an array in C++

Output-

Output of a pointer to an array in C++

It is important to note that the address of the first element is stored in ‘p’. Thereafter, you can easily access the elements of the array with the help of *p, *(p+1), *(p+2) to get the address of the 1st, 2nd, 3rd element respectively.

Key takeaway: The pointer to the array *(p+i) will give you the value of the array with each iteration whereas (p+i) will give you the address of the array with each iteration.

9. Summary

After completing Arrays in C and C++ tutorial, we got a firm understanding of Arrays, one of the most important and significant topics in C/C++ programming.

We discussed the meaning of arrays, how they are declared, the different data types associated with it, how they are initialized and accessed. Further, we carried on our discussion by giving a brief insight on the multidimensional array, array implementation in C and C++ like passing an array to a function and pointer to an array by intertwining the concepts of arrays and functions and arrays and pointers respectively.

Enhance your fundamental skills with Operators in C

For any further queries leave your comment below.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.