vendredi 1 juillet 2016

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 temp;
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 >> temp;
        arr[(maxterms - x)] = temp;
        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?

Aucun commentaire:

Enregistrer un commentaire