I am very new to programming and was wondering about the scope of variables in for loops.
I was attempting to make something that asked the user to enter a number that would represent the amount of numbers to be added together. So if they entered 3 it would add three numbers together.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
int nTarget;
cout <<"Enter the amount of numbers you wish to add: ";
cin >> nTarget;
while (nTarget < 0)
{
cout <<"Negative number detected, please enter a positive number: ";
cin >> nTarget;
}
for(int nAccum = 0, nNext, nCounter = 0; nCounter < nTarget; nCounter++)
{
cout <<"Enter the number to be added: ";
cin >> nNext;
nAccum = (nAccum + nNext)
}
cout <<"The total is " << nAccum << endl;
system("PAUSE");
return 0;
}
I'm sorry if the code is hard to read and sloppy I was just messing around. My problem is that it gives me an error saying that "name lookup if 'nAccum' changed for ISO 'for' scoping."
Does this mean that I cannot access that variable outside of that for loop? Is there a way I could change it so that it would allow me to?
And let's say that the original code did work and it did retrieve the value of nAccum, would it even hold the accumulated value or is its value completely erased once the for loop ends?
Sorry about these really newbie questions but I wasn't able to find an answer elsewhere, and thanks to whoever decides to answer.