0

I've initialized arr to -1 when I print them every element is initialized to 0 except the first element.

This is the small code of a bigger problem. I'm just struck here

#include <bits/stdc++.h>

using namespace std;

int fibo()
{
    int static arr[100] = {-1};
    for (int i = 0; i < 100; ++i)
    {
        cout << "arr[" << i <<"] : " << arr[i] << endl;
    }
    return -2;
}

int main(void)
{  
    cout << "Result : " << fibo() << endl;
    return 0;
}
4
  • 2
    Related: stackoverflow.com/questions/201101/… Commented Feb 2, 2019 at 10:50
  • The simplest thing is to stop using an array and use static std::vector<int>, where the initialization semantics aren't cumbersome as with an array. Commented Feb 2, 2019 at 10:52
  • Did the same sir. I don't know why every element of it is not initialized to -1. Commented Feb 2, 2019 at 10:52
  • @AshishSiwal because they are not supposed to be. You are declaring a fixed array that holds 100 values, but you are specifing only 1 value for the first element. The other elements are thus value-initialized, which for int means 0. std::vector, on the other hand, has a constructor that initializes all elements to the same value: static vector<int> arr(100, -1); Commented Feb 2, 2019 at 19:00

2 Answers 2

1

Simplest solution -- use std::vector<int>, and the initialization of all elements becomes available to you in a very easy form (I know there are template tricks that can be done, but IMO there is no need for that level of complexity for this in your code).

Example:

#include <vector>
#include <iostream>

int fibo()
{
    static std::vector<int> arr(100,-1);
    for (int i = 0; i < 100; ++i)
    {
        std::cout << "arr[" << i <<"] : " << arr[i] << "\n";
    }
    return -2;
}

int main(void)
{  
    std::cout << "Result : " << fibo() << "\n";
    return 0;
}

Live Example

Sign up to request clarification or add additional context in comments.

Comments

0
#include <bits/stdc++.h>

using namespace std;

int fibo()
{
    int static arr[100];
    for (int i = 0; i < 100; ++i)
      {
        arr[i] = -1;
      }
    for (int i = 0; i < 100; ++i)
    {
        cout << "arr[" << i <<"] : " << arr[i] << endl;
    }
    return -2;
}

int main(void)
{  
    cout << "Result : " << fibo() << endl;
    return 0;
}

Try using this code

1 Comment

I know this sir. But I'm using static array so that the value of array once initialized will not be initialized again and again during recursion. Your code will initialize my array to -1 every time the function is called.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.