Site icon DataFlair

Samurai Technique to Learn Arrays in C and C++ [Quiz included]

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.

Make sure to test your learnings with interactive quizzes at the of article.

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.

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:

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.

int array [ ] = {4 , 9 , 2 , 1};
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 ]
4 9 2 1

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;
}

Code on Screen-

Output-

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 – 

Output-

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.

 

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-

Output-

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-

Output-

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-

Output-

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-

Output-

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-

Output-

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-

Output-

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-

Output-

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-

Output-

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.

Quiz on Arrays in C and C++

It’s a nice way to see how much you know, or don’t know, about Arrays in C, C++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    #include

    using namespace std;
    int main()
    {
    int arr[5]={1,2,3,4,5};
    cout<<arr[4]<<", "<<sizeof(arr);
    return 0;
    }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    #include

    using namespace std;
    int main()
    {
    char c[]={‘D’, ‘E’, ‘L’, ‘H’, ‘I’};
    cout<<c[3]<<", "<<sizeof(c);
    return 0;
    }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    #include

    using namespace std;
    int add(int a[])
    {
    a[2]= a[1]-a[0];
    }
    int main()
    {
    int a[2]={1,3};
    int b= add(a);
    cout<<a[2];
    return 0;
    }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    #include

    using namespace std;

    int main()
    {
    int a[]={1,3,4,5};
    for(int i=0; i<=2; i++)
    {
    cout<<i[a]<<" ";
    }
    return 0;
    }

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    #include
    #include
    using namespace std;

    int main()
    {
    char arr[]=”Mumbai”;
    int l=sizeof(arr);
    cout<<l<<" "<<arr[6];
    return 0;
    }

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    #include
    #include
    using namespace std;

    int main()
    {
    int a[]={1,2,3,4};
    cout<<a[20];
    return 0;
    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    #include
    #include
    using namespace std;

    int main()
    {
    int a[]={1,2,3,4};
    int l =sizeof(a)/sizeof(a[0]);
    cout<<l;
    return 0;
    }

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    #include

    using namespace std;
    int main()
    {
    int arr[5]={1,2,3,4,5,6};
    cout<<arr[3]<<", "<<sizeof(arr);
    return 0;
    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    #include
    #include
    using namespace std;
    int main()
    {
    char mystring[]= “this is a string”;
    int l= sizeof(mystring);
    int l2= strlen(mystring);
    cout<<l<<", "<<l2;
    return 0;
    }

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    #include

    using namespace std;
    int main()
    {
    char str[]= “Japan”;
    char *s=str; int count;
    while(*s!= ‘\0’)
    {
    count++; s++;
    }
    cout<<"length is "<<count;
    return 0;
    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    what among the following is not a possible feature for arrays in c/c++?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    One advantage of vector over arrays would be:

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    what should be the disadvantage of an array among the following?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    What class is needed to be included in c++ to use vectors?

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    What is not true for arrays having the same functionality as pointers?

    Correct
    Incorrect

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.

Exit mobile version