'i am only getting the output right if i say i is int specially in for loop

#include <iostream>

using namespace std;
                    // finding the required sum of subarray
int main()
{
    
int n,s;
int i=0,j=0,st=-1,en=-1,sum=0;
cin>>s;                            //input required sum
cin>>n;
int a[n];
for(int i=0;i<n;i++){     // here if i only mention int again i //am getting the output or else the values of st and en are printing //out the same as i initialize
    cin>>a[i];
}
while (j<n){
    sum+=a[j];
    while(sum>s){
        sum-=a[i];
        i++;
    }
    if(sum==s){
        st=i+1;
        en=j+1;
        break;
    }
    j++;
}
cout<<st<<" "<<en<<" ";

return 0;

the output is -1 -1 and if i mention "int i" again in for loop of inputing array i a getting the answer. i want to know the reason i already intialize i before why do i need to do it again



Solution 1:[1]

The problem statement is unclear, I'm assuming you simply want the indexes of the repeating numbers in array a. You are correct for the most part, using b[i] = i is the problem. If you understand what a vector is, then simply create a vector like this and push the indexes in the vector. For example,

vector<int> b;

and inside the a[i] == a[j] condition,

b.push_back(i);

then finally print out result like,

for(int i = 0 ; i < b.size() , i++)
    cout << b[i] << " ";

If you're unfamiliar with vectors, simply use another variable cnt to update index of array b

int a[n], i, b[n], j, cnt = 0;

and inside the a[i] == a[j] condition,

b[cnt] = i;
cnt++;

and finally

for(int i = 0 ; i < cnt ; i++)
    cout << b[i] << ' ';

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1