Laila Laila - 1 month ago 6
C++ Question

How to find sum of several integers input by user using do/while, While statement or For statement

Please help out here. I want to create a program whereby a user inputs several numbers (let's say 6 numbers from his/ her head). The program should then go ahead and calculate the sum of all these numbers. I however have to use a loop statement, either For statement, While statement or do/while statement. This is what I have so far:

#include <iostream>

using namespace std;

int main()
{
int count = 1;
int sum = 0;
int number;
int numberitems;

cout << "Enter number of items: \n";
cin >> numberitems;

cout << "Enter number: \n";
cin >> number;

do {

sum = sum + number;

count++;
} while (count <= 6);
}


AND HERE IS THE OTHER CODE USING WHILE STATEMENT

#include <iostream>

using namespace std;

int main()
{
int count = 1;
int sum = 0;
int number;

cout << "Enter number: \n";
cin >> number;

while (count <= 6) {
sum = sum += number;

count++;
}
cout << sum << endl;
}


I know this is beginner stuff, well am a beginner so help out a sister politely.
THANKS

Answer

The FOR loop worked well, I modified it a tiny bit:

#include<iostream>
using namespace std;
int main ()
{

    int sum = 0;
    int number;
    int numberitems;


    cout << "Enter number of items: \n";
    cin >> numberitems;

    for(int i=0;i<numberitems;i++)
    {
        cout << "Enter number: \n";
        cin >> number; 

        sum=sum+number;

    }
    cout<<"sum is: "<< sum<<endl;
}

HOWEVER, the WHILE loop has got some errors on line 11 (Count was not declared in this scope). What could be the issue? Also, if you would have a solution using DO,WHILE loop it would be wonderful. Thanks