-1

I am experimenting with an online compiler, but I keep getting errors when I try to run the below program, stating that the variables were not declared in scope. I am declaring them in main() and then using them in a loop, and I don't understand why this error is occurring. I would greatly appreciate any help in understanding the issue and how to fix it.

#include <iostream>
using namespace std;

int main() {
 
    sum = 0;
    value = 0;
    
    while(value > -1){
        sum += value;
        cout << "Enter a value" << endl;
        cin >> value;
    }

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    I suggest you read [some good books on C++](https://stackoverflow.com/q/388242/8484779) if you're new to this programming language. – DeBARtha Jun 05 '21 at 03:57

2 Answers2

3

You simply have to declare the variable the right way in C++, which is:

<variable_type> <variable_name> = <variable_value>;

Also, #include using namespace std; is a typo, it should be

#include <iostream>
using namespace std;

Your code :

#include <iostream>
using namespace std;

int main()
{
    int sum = 0;
    int value = 0;

    while(value > -1)
    {
        sum += value;
        cout << "Enter a value" << endl;
        cin >> value;
    }
    cout << sum;
    return 0;
}

Output:

Enter a value
5
Enter a value
7
Enter a value
-1
12

Also, see why using namespace std; is considered bad practice.

1

C++ is a strongly-typed language, and requires every variable to be declared with its type before its first use

You are never declaring the variables value and sum in your entire program before using it.

Fix

#include <iostream>
using namespace std;

int main() {
 
    int sum = 0;
    int value = 0;
    
    while(value > -1){
        sum += value;
        cout << "Enter a value" << endl;
        cin >> value;
    }

    return 0;
}
Arsenic
  • 727
  • 1
  • 8
  • 22