Search code examples
c++loopsvariables

How to get the real value of variable declared outside the loop, after using that varible in loop


I was working with loops and stuck with this problem.

I had declared a variable outside the main code and then used it in the loop, but when I am returning the value of that variable after that loop, I am unable to get that value again.

int n;

int main () {

    // Sum of N natural numbers using FOR LOOP

    // 1st METHOD

    cin>>n;

    int sum = 0;

    for(int i=1 ; i<=n ; i++){
        sum=sum+i;
    }

    cout<<"\nThe sum of first "<<n<<" natural number is : "<<sum<<endl;


    // 2nd METHOD

    int sum4=0;
    for( n ; n>0 ; n--){
        sum4+=n;
    }

    cout<<"\nThe sum of first "<< :: n<<"  natural number is : "<<sum4<<endl;


    // Sum of N natural numbers using WHILE LOOP

    int sum1=0;
    while(n>0){
        sum1+=n;
        n--;
    }

    cout<<"\nThe sum of first "<<n<<" natural number is : "<<sum1<<endl;


    // Sum of N natural numbers using DO WHILE LOOP

    int sum2=0;
    do{
        sum2+=n;
        n--;
    } while(n>0);

    cout<<"\nThe sum of first "<<n<<" natural number is : "<<sum2<<endl;


    return 0;
}

Output:

The sum of first 55 natural number is : 1540
The sum of first **0**  natural number is : 1540
The sum of first **0 **natural number is : **0**
The sum of first **-1** natural number is : **0**

Can I declare a universal variable and use it in a loop, and at the same time after the loop quits it does not change the value of that variable and give the output as declared?


Solution

  • Can I declare a universal variable and use it in a loop and at the same time after loop quits it does not change the value of that variable and gives the output as declared.

    Let me rephrase that as: "Can I modify something, and at the same time, ensure it is not modified?"

    No, you can't. What you can do is copy something, and modify the copy.

    for(int i=n; i>0 ; i--){
        sum4+=i;
    }
    
    int sum1=0;
    int i = n;
    while(i>0){
        sum1+=i;
        i--;
    }
    
    int sum2=0;
    i = n;
    do{
        sum2+=i;
        i--;
    } while(i>0);