简体   繁体   中英

Writing To & Reading From an Array using For Loops and User Input

#include <iostream>
using namespace std;


int arr[100] = {};
int terms;
int maxterms;
int sum = 0;

int main() {
    cout << "How many terms would you like to add?" << endl;

    cin >> terms;

    terms = maxterms;

    for (int x = terms; x >= 0; x--) {
        cout << "Number " << (((maxterms)-x) + 1) << ": ";
        cin >> arr[(maxterms - x)];
        cout << endl;
    }

    for (int x = 0; x < maxterms; x++) {
        sum += arr[x];
    }

    cout << "Your sum is: " << sum;

    return 0;
}

This simple program always prints sum as zero, and only prompts for user input once. How can this code be improved so that it writes to consecutive indexes of the array, then returns the sum of them?

maxterms is initialised to 0 since it is a global variable. You are equation terms = maxterms where in you are overwriting user's input to 0.

So for (int x = 0; x < maxterms; x++) doesn't run at all. Hence the sum is 0 all the time. The same holds for the the loop where number of times user input is prompted.

Also, the loop where you are prompting the user for input is running for terms+1 times.

As @SilentMonk noted, x = maxterms, and so the loop exits.

You can redesign the loop like so:

for (int x = maxterms; x >= 0; x--)
{
    sum += arr[x];
}

Here x starts with its value equal to maxterms , and decreases until its value is 0, and the value of arr[x] is added to sum every iteration.

I just checked your code and i found this point by looking at this line,

terms = maxterms;

this will overwrite the input of user with some random value as you are not initialising maxterms.

i think you wanted to copy user input to maxterms so do like this:

maxterms = terms;

change this and try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM