K value is not incrementing

#include
using namespace std;
int main(){
int n;
cin>>n;
int key;
cin>>key;

int arr[n];
for(int i=0 ; i<n ; i++){
    cin>>arr[i];
}

int i=0;
int j=n-1;
int k=1;
while(k<(n-1)){
    int sum=0;  
    sum = arr[i] + arr[k] + arr[j];

    while(i<k && j>k){
        cout<<"sum= "<<sum<<"i= "<<i<<" j= "<<j<<"k= "<<k<<endl;
        if(sum == key){
            cout<<(i+1)<<","<<(k+1)<<" and "<<(j+1)<<"sum= "<<sum<<endl;
            j++;
            i--;
        }
        else if(sum<key){
            // cout<<"test"<<endl;
            j--;
        }
        else{
            i++;
        }
    }
    k++;
}
return 0;

}

Please share your code by saving it on cb ide

ma’am I don’t know how to do that

Paste the code in ide.codingblocks.com save the code and share the generated link

Inside the first condition shouldnt you increase i and decrease j?

sorry maam not getting you

I am talking about this thing here
image

got it , that’s my mistake but still k value is not increasing

@debojyoti.koley.dk the logic is not completely correct, dry run on some test cases
5 6
1 2 3 4 5
See for this case, value of k is increasing but the logic is not correct so answer is not coming

but ma’am if you run the code , it will print i , j , k values also with the sum in each iteration. But there the value of k is 1 , it means the external while loop is running only one time. But am not understanding why

Can you please tell me what’s wrong in this logic ?

yes ma’am for 5 6 … 1 2 3 4 5 the value of K is increasing . But for 5 12 … -2 1 5 6 8 , its not increasing

got the ans ma’am thank you

just had to change 3 lines. https://ide.codingblocks.com/s/576615

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

You have reopened your doubt is there any confusion still?

sorry ma’am but I thought I got the ans as the code was working fine for some tc. But most of the cases I am getting “core dumped” error. Please look into it.

Okay let me check it

  1. Input format is not matching the question. Take input for key after the array.
  2. The logic you are following needs you to
    i) Sort the array
    ii) Reset values of i and j so you can cover all possible triplets
  3. This approach will still not work because the output is in sorted manner.

Fixed code with your approach: https://ide.codingblocks.com/s/578771
You can see the output is not matching what is given in the question.

What you need to do is:

  1. Sort the array
  2. Run nested loops to find and print the triplets in sorted manner
  3. (Optional) You can try reducing the time complexity with the help of unordered_map, but if you are not familiar with that concept yet you can skip that for now.