0

I am a total newcomer to the world of C++, and not much more experienced in any other languages, so please forgive me for the bad syntax and indentation etc etc...

Can someone please explain to me why this simple program will print the array values that I input, but won't add up the array values?

#include <iostream>

 using namespace std;

int main(){

  int alpha[8];
  int sum=0;

 for(int x=0; x<8; x++){
    cin>>alpha[x];
  }
 for(int x=0; x<8; x++){
    cout<<alpha[x];
  sum += alpha[x];
  return sum;

  }
  cout<<sum;

  return 0;
}

2 Answers 2

1

In your 2nd for statement, you have a return. The code reaches the return and exits your program.

You may want to move code to a function to keep the return or remove it.

BTW, you can find this out by using a debugger.

Sign up to request clarification or add additional context in comments.

1 Comment

Aye, tried debugging it, but it didn't offer much of an explanation as to why the program didnt work, it just said that there was an error in the active configuration of the program
1

Answer Thanks for the help, I have modified my code and made it into this:

#include <iostream>

using namespace std;

int main()
    {
    int alpha[8];
    int sum = 0;

    for (int x = 0; x<8; x++)
    {
        cin >> alpha[x];
    }
    for (int x = 0; x<8; x++)
    {
        cout << alpha[x];
    } 
    for (int x = 0; x<8; x++) 
    {
        sum = sum + alpha[x];
    }
    cout << sum;
    system("PAUSE");
    return 0;
}

having tried your suggestions, I couldn't make it work initially, so I fiddled with the formatting. The program seems to work now. I would assume that there was something wrong with either my formatting post-"return" removal, or there was something procedurally wrong with the Eclipse/MinGW setup I had. I seem to have more success with Visual Studio.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.