V.Smithy V.Smithy - 1 month ago 9
C++ Question

Fixing this simple code

I'm a beginner at coding and I can't fix this code and I'm going crazy. It keeps telling me certain variables were not declared and i'm not sure how to fix it.

#include <iostream>

using namespace std;

int main()
{
int (a = 0), sum;{
cout << "This program should read all integer numbers ";
cout << "to sum until a negative number is entered\n";
exit(0);
}

while(a < 0) {
cout << "Enter an integer number: ";
cin >> a;
sum += a;
}

cout << "The sum is sum\n";
return 0;
}

Answer

You did not initialize sum, so it could start with any value.

You have extra layers of pointless { } around for no reason.

Your final cout statement does not actually print the varaible.
Change it to: cout << "The sum is " << sum << "\n";


#include <iostream>

using namespace std;

int main()
{
  int a = 0, sum = 0;
  cout << "This program should read all integer numbers ";
  cout << "to sum until a negative number is entered\n";

  do {
     cout << "Enter an integer number: ";
     cin >> a;
     if (a > 0)
     {
         sum += a;
         cout << "The sum is currently: " << sum << "; but this is not yet the final value.\n";
     }
  } while(a > 0) ;

  cout << "The sum is " << sum << "\n";
  return 0;
}
Comments