How to fill Array using fill() function in C++

In this tutorial, we will be learning about how to fill an array in C++ using the fill function.

Basically, we just traverse the whole array and we mark each array index with the value we want. But, traversing the whole array and marking each element takes a high amount of time. So, here we are reducing that by fill() function.

Fill C++ array using fill() function

Before moving into fill() function, if you are a beginner, please go through the below simple example and then learn the fill() function.

C++ program to print 1 to 10 numbers using for loop

Description

The std::array::fill() sets a default value(i.e. which is given by user) to the all elements of the array.

Header Files

we require two header files which are

<iostream>(Standard input-output stream)

<array>(For declaring array in our code)

Syntax

In C++:

First, declare the array by using the following syntax:

array<datatype, size>array_name;

Here  array is the declaration keyword for array,

datatype is array of which type like int, float, etc..,

size is the size of the array which we declare,

array_name is name of the array.

Comsider a simple example

array<int,10>arr;

The above statement declares an array of int type which can store 10 elements whose name is arr.

Return Value

None

This does not return any value.

 Time Complexity

O(n)

Let’s learn with simple example.

The code before using fill function

#include <iostream>
#include<array> 
using namespace std;
int main() { 
    //creating a array with size 10 
    array<int,10>arr; 
    //filling the array with its index 
    for(int i=0;i<10;i++)
    { 
        arr[i]=i; 
        
    } 
    cout<<"Array before using fill()\n"; 
    for(int i=0;i<10;i++) 
    { 
        cout<<arr[i]<<" "; 
        
    } 
    cout<<"\n"; 
    return 0;
    
}

if you run the above code the below output will be produced.

Output:

Array before using fill()
0 1 2 3 4 5 6 7 8 9

The code after using fill function

#include <iostream>
#include<array>
using namespace std;

int main()
{
    //creating a array with size 10
    array<int,10>arr;
    //filling the array with its index
    for(int i=0;i<10;i++)
    {
        arr[i]=i;
    }
    //filling array with default value as 2
    arr.fill(2);
    cout<<"Array after using fill()\n";
    for(int i=0;i<10;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

If you run above code, the below output will be produced.

Output:

Array after using fill()
2 2 2 2 2 2 2 2 2 2

Here we can see each and every element of the array is 2. This is done using fill() function. Even if we intialize the array elements with any values if we use fill function then all elements will be defaulted with given value.

Leave a Reply

Your email address will not be published.