0

I'm trying to initialize a single value to whole array in c++. For ex:- I want to initialize 1 in whole array by writing it by only once

I have tried to initializing 1 in whole array but it throws error , I'm expecting 1 in whole array.

ex- int array[5]={0}; output- 0 0 0 0 0

int array[5]={1}; output- 1 0 0 0 0 expecting- 1 1 1 1 1

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271

1 Answers1

-1

if you want 1 value at very index you can do this by

int arr[5] = {1,1,1,1,1}; or 
int arr[5];
arr[0] = 1;
arr[1] = 1;
arr[2] = 1;
arr[3] = 1;
arr[4] = 1;

otherwise if you write arr[5] = {1}; only first index will have value 1 rest will be assigned zero automatically like this {1,0,0,0,0}

or #include <iostream>
using namespace std;
int main()
{
    int arr[5];
    memset(arr, 1, sizeof(arr));
    cout << arr;
    return 0;
}

so type this code this memset function will fill all the index with value 1 by writing it only once.

hope this answer helps you. Edited, try this code snippet working perfectly fine

#include <iostream>
#include <array>

int main () {
  std::array<int,5> myarray;

  myarray.fill(1);

  std::cout << "myarray contains:";
  for ( int& x : myarray) { std::cout << ' ' << x; }

  std::cout << '\n';

  return 0;
}