Clear my doubt please

My issue

i solved this problem when i assigned ans=0 inside while loop , earlier i was directly assigning ans=0 in the first line of code like int t,n,x,s,r,ans=0; and the output was coming wrong , what was the issue earlier please explain in detail why it worked only after that .

My code

#include <iostream>
using namespace std;

int main() {
	// your code goes here
	int t,n,x,s,r,ans;
	cin>>t;
	while(t--){
	    cin>>n>>x;
	    ans=0;
	    for(int i=0;i<n;i++){
	        cin>>s>>r; 
	        if(x>=s){
	            ans=max(ans,r);
	        }
	    }     
	    cout<<ans<<endl;
	}
	return 0;
}

Problem Link: CodeChef: Practical coding for everyone

When you were writing ans = 0 outside, your ans variable was initialized to 0 once. Then, when it went inside the loop, it would update once. But when it went for the second loop, instead of starting from 0 again, it would directly take the updated value of ans from solving test case 1 because When a variable is declared outside a loop and its value is modified inside the loop, the updated value is reflected both inside and outside the loop because the variable is accessible within the loop’s scope. However, if the variable is declared inside the loop, it is only accessible within the loop’s scope and cannot be accessed or modified outside the loop.

When a variable is declared outside a loop and its value is modified inside the loop, the updated value is reflected both inside and outside the loop because the variable is accessible within the loop’s scope. However, if the variable is declared inside the loop, it is only accessible within the loop’s scope and cannot be accessed or modified outside the loop.

jab tum bahar ans =0 likhte the to tumara ans variable ek baar 0 se initialiazed ho jaata tha or fir jab wo loop ke andar jaata tha to ek baar update hojata tha
but again jab second loop ke liye jaata tha to wo ans 0 se start na hokar directly test case 1 ka updated ans value ko leke solve karta tha kyoki bahr declare wala jab change hota hai to dono taraf effect padta hai bahr bi andar bhi but jab andar declare hota hai to sirf andar hi change karta hai bahar nhi.

tumhare case me tum bahar declare karrahe the jiske wajah se jab tum 0 se initialize kiye aur jab wo for loop ke andar gaya aur update hua to andar bahar dono effect pada jiske wajah se bahar wala ka value 0 se change ho ke jo tumhar answer aya tha test case 1 bhi bahar wale se replace hogaya aur jab second testcase call ho raha tha tab ans =0 se na hoke ans= updated ans ke saath value leraha tha har testcase case me galat tarike se update ja raha tha ans ka value.

Did your doubt get cleared?

ohhh yes thanks brother , it helped i understood.