mercredi 1 février 2017

Value of variable changes

In the code below, I am trying to store the value of array at index 0 in the temp variable. In this line of code: a[i-1]=a[i]-a[i-1]; when i=0, a[i-1] becomes a[-1].

  1. Why is compiler not giving any error?
  2. Why does the value of temp variable is affected and becomes zero after the first iteration, though it is assigned a value only when i=0 and temp is not used anywhere else?

For example, when I gave input as:

3 1 2 3

Output:

i:0
a[0]: 1
TEMP: 1
TEMP: 0
TEMP: 0

TEMP: 0

What's actually happening? Please explain with reference to the working of compiler. I know that if I put a condition if(i!=0) a[i-1]=a[i]-a[i-1]; the code will work normally. But I want to know why is this happening with the given scenario.

#include<bits/stdc++.h>

using namespace std;

int main()
{
    int a[10],i,n,temp;
    cin>>n;
    for(i=0;i<n;i++){
        cin>>a[i];
        if(i==0){
            temp=a[i];
            cout<<"i: "<<i<<endl;
            cout<<"a[0]: "<<a[i]<<endl;
        }
        cout<<"TEMP: "<<temp<<endl;
        a[i-1]=a[i]-a[i-1];
    }
    cout<<endl<<"TEMP: "<<temp;
}

Aucun commentaire:

Enregistrer un commentaire