user5927645
user5927645

Reputation:

C++ algebraic calculation

I had to write a program to ease our burden in finding linear curve fitting for our physics lab works. My program computes upto sigma xi and sigma (xi^2) correctly. I have used similar code for computing rest few values. But Afterwards, It is displaying all values as 0. I couldn't find any mistakes in the remaining part as the same codes i used worked before.

I'm attaching the cpp file.Cpp file here

Sample part giving value 0

   float * yl;
yl= new float[N];

cout << "Enter values for Y (total "<<N<<")\n"<<endl;
for(j=1;j<N+1;j++)
{
 cin >> yl[i];
}

sigyi=0;
for(o=1;o<N+1;o++)
{
sigyi=sigyi+yl[o];
}

But this one works correctly

float * xl;
xl= new float[N];

cout << "Enter values for X (total "<<N<<")\n"<<endl;
for(i=1;i<N+1;i++)
{
 cin >> xl[i];
}

sigxi=0;
for(l=1;l<N+1;l++)
{
sigxi=sigxi+xl[l];
}

Please help me with this.

Upvotes: 0

Views: 66

Answers (1)

bames53
bames53

Reputation: 88155

First off, neither code snippet you posted is correct. The appearance of working is not sufficient. The code is accessing outside the boundaries that are legal, and in C++ that means anything could happen at any time. It might appear to work sometimes and other times it might not.

However the most immediate reason why the first snippet probably doesn't appear to work is because you are incorrectly reusing the index i when you switched the loop declarations to use j:

for(j=1;j<N+1;j++) // <--- j
{
 cin >> yl[i];    // <--- i
}

This is one of the reasons that predeclaring the loop indices is a bad practice. You should always declare the loop variable in the loop itself. Had you done this, then there would not have been any i in the outer scope for you to accidentally use in the j loop.

Upvotes: 1

Related Questions