I am trying to write a program in c++ that allows you to enter 10 numbers and receive the sum of those numbers using a for loop. However, I am encountering a problem where I am not getting the added integers and instead getting the sum of the last 2 numbers.
#include <iostream>
using namespace std;
int main ()
{
int i;
int number;
for(i; i < 10; i++)
{
cout << "enter a number" << endl;
cin >> number;
if( i < 10)
number+= number;
}
cout << number;
return 0;
}
1) You never initialize i, you should do so in the for loop.
for(int i=0; i < 10; ++i)
You also don't need:
if( i < 10 )
because based on your for loop conditions, this can never be false.
2) You also need to initialize number.
int number = 0;
3) You shouldn't cin directly to number or you will replace the total every single time. You could do this in your for loop for example.
int temp = 0;
cin >> temp;
number += temp;
Summary
If you correct the above three issues, the modified code would look like this:
int main ()
{
int number = 0;
for(int i=0; i < 10; ++i)
{
cout << "enter a number" << endl;
int temp = 0;
cin >> temp;
number += temp;
}
cout << number;
return 0;
}
When you write cin >> number; you are replacing your sum so far. You need to take user input into a separate variable and then add it. Something like:
for(i = 0; i < 10; i++)
{
cout << "enter a number" << endl;
int input;
cin >> input;
number += input;
}
A couple of things. You need to initialize i before you use it in a for loop
for(int i=0; i<10; i++)
Also, you are using the same variable to get the number from cin as you are using to store the sum. You should use two separate variables.
Here's a list of things to change and a working program with a few modifications below
1.You must initialize variables before you can use them in any meaningful way.
Initialize means assigning an initial value but it also requires you declare variables and that they are properly defined (e.g. loop variable is i NOT defined to be an int)
Therefore, you have to initialize the for loop variable i. You also have to initialize number by changing it to 0
2. Use a different number for your input and for your sum because you will just overwrite any old values as you read them. Note that you do not need to assign a value to this number because you are reading from the input stream into it
int sum=0,n;//n is input
for(int i=0; i < 10; i++)
{
cout << "enter a number" << endl;
cin >> n;
sum+= n;
}
cout << sum;
Related
I have to write a programme in c++ where user enters a number N, then on a second line he enters as many numbers as N, no more. The ouput shoud be the sum of all positive numbers among the entered numbers.
I have to use for loop. Also we have not covered much so far, only if statements.
The code I have tried gives the sum of positive numbers only, but I can't make the programme use N inputs and stop. It either calculates only one or continues as long as user enters numbers.
#include <iostream>
using namespace std;
int main ()
{
int n, sum=0;
cin>> n;
cout<<endl;
cout<<"Enter numbers"<<endl;
for (int i=1; i<=n; i++)
{
cin>>i;
if(i>0)
{sum=sum+i;
}
cout<<sum<<endl;
}
return 0;
}
The problem is that you're using the same variable (i) for looping and input.
for (int i=1; i<=n; i++)
{
cin>>i;
Whatever gets entered in that cin>>i ruins the logic of your program. Add one separate input variable and keep your i for the loop.
Example:
#include <iostream>
int main() {
int n, sum = 0;
std::cout << "How many numbers do you want to enter? \n";
std::cin >> n;
std::cout << std::endl;
std::cout << "Enter numbers: \n";
for(int i = 1; i <= n; i++) {
std::cout << i << ": ";
int input;
if(std::cin >> input) {
if(input > 0) {
sum = sum + input;
}
std::cout << sum << std::endl;
} else
break; // user failed to enter a number
}
}
I've got a small task I need to complete and I'm rather confused. This task has 3 parts to it which are:
Write a program that dynamically allocates a float array of a size specified by a user (currently working on - if anyone could check my code for this it would be appreciated.
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
Program should print what was saved into the array, the sum, and the average value in the array, and exit.
As you could tell I'm new to C++ and coding in general so please spell it out for me wherever possible. It is mandatory that I am using pointers so I'm afraid I can't change that.
#include <iostream>
using namespace std;
int main()
{
int length;
cout << “Please enter the length of the array: “;
cin >> length;
float * dArray = new float [length];
for (int i = 0; i < length; i++)
{
cin >> dArray[i] = i;
for (int i = 0; i < length; i++)
{
cout << dArray[i] << “ “;
}
cout << ‘/n’;
int sum = 0;
for (int i=0; i < length; i++)
{
sum +=dArray[i];
avg =sum/length;
cout << “Sum is “ << sum << “/nAverage is “ << average;
delete [] dArray;
}
return 0;
}
Please explain the 2nd part.
Thanks in advance.
Regarding
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
It means that you have to let the user input the values to that array. What you are doing is giving them values yourself.
What you need to do is change
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
to
for (int i = 0; i < length; i++)
{
cin>>dArray[i];
}
Also Note that length should be an int and not a float.
After completion, this would probably be the code you need ( although I would advice you to do the part of finding the sum and average by yourself and use this code I have posted as reference to check for any mistake, as finding the sum and average for this is really easy )
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
float sum = 0 , avg; // variables to store sum and average
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for (int i = 0; i < length; i++)
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
delete[] dArray;
return 0;
}
EDIT
After getting your comment, I decided to post this new code. ( I am assuming what you meant is that the program should repeat as long as the user wants )
I have done it by using a do while loop.
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
char a; // a variable to store the user choice
do
{
float sum = 0 , avg; // variables to store sum and average
cout << "\nPlease enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for ( int i = 0; i < length; i++ )
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++ ) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
cout << "\n\nDo you want to try again ( y/n ) ?\n";
cin >> a;
delete[] dArray;
}while( a =='Y' || a == 'y' ); // The do while loop repeats as long as the character entered is Y or y
return 0;
}
Well, hope this is what you were looking for, if not, please do notify me with a comment... :)
Just so you know, the new code you have posted doesn't even compile. Here are some of the problems.
cin >> dArray[i] = i;
You don't need to use = i here. Just cin >> dArray[i] ; is enough.
The next problem is
cout << ‘/n’;
First of all, its \n and not /n. You also need to enclose it in double quotes and not single quotes. That is cout << "\n";
Next one, you have not defined the variable avg . Also note that you have also used an undefined variable average, which I assume you meant avg.
Now here's one of the main problems , You have not closed the curly brackets you opened. You open the brackets for for loops, but forget to close it. I'm leaving that part to you as you need to learn that part yourself by trying.
Now Here's one problem I don't understand, you have used “ “, which is somehow not the same as " ". I don't know if it's something wrong with my computer, or if it's a totally different symbol. My compiler couldn't recognize it. If its not causing any trouble on your end, then don't mind it.
Well, this sums up the problems I noticed in your code ( the problems that I noticed ).
Your issues are too simple for us to just give you the answers, but I've commented your code with suggestions on how to solve your problem:
#include <iostream>
using namespace std;
int main()
{
float length; //it doesn't make sense for something to be of a float length
//should be size_t instead
cout << "Please enter the length of the array: ";
cin >> length;
float *dArray = new float[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i; //this line is incorrect
//how should we read the data into this array?
//we've used cin before
}
for (int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
cout << '\n';
//now we've output the array, just need to output the sum and average value
int sum = 0;
for (int i=0; i < length; i++)
{
sum += //what should go here?
}
int average = //how should we calculate the average?
cout << "Sum is " << sum << "\nAverage is " << average;
delete[] dArray;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int howmany;
int i=0;
cout <<"How many integers you want to add,just enter the number.\n";
cin >> howmany;
while (i < howmany)
{
int sum = 0;
sum = sum +i;
i++;
cout << sum << endl;
}
system ("pause");
return 0;
}
what is the mistake? It gives me list of numbers rather than their sum.I have tried to change order of statements in loop body but still problem not solved.
Initialise sum=0 outside the loop. Because in your code every time you loop, the varaible sum is set to 0.
Change like this
int sum = 0;
while (i < howmany)
{
sum = sum +i;
i++;
cout << sum << endl;
}
Declare the sum variable out side the loop.
Or
you can declare a static variable inside loop (static variable will
be initialized once)
int main()
{
int howmany;
int i=0;
cout <<"How many integers you want to add,just enter the number.\n";
cin >> howmany;
int sum = 0; //Declare here
while (i < howmany)
{
sum = sum +i;
i++;
}
//Display the result after the while loop.
cout << sum << endl;
system ("pause");
return 0;
}
OK so basically i want this code to get the user to input a value each time into the array and they get to specify the amount of rows and columns. I think i that the problem is that each time the user enters the value it goes into the correct column but also into both rows so by the end it only prints out the last lot of numbers the user had entered in all of the rows.
Sorry if that was hard to understand as this is my first post to this site and as you can probably tell i am only learning c++. So if you could help it would be greatly appreciated.
#include <iostream>
using namespace std;
int main()
{
int row;
int column;
int value[row][column];
cout << "How Many Rows?\n";
cin >> row;
cout << "How Many Columns\n";
cin >> column;
for(int x = 0; x<row; x++) {
for(int y = 0; y<column; y++) {
cout << "Enter Value Now\n";
cin >> value[x][y];
}
cout << endl;
}
cout << endl;
for(int a = 0; a < row; a++) {
for(int b = 0; b < column; b++) {
cout << value[a][b] << " ";
}
cout << endl;
}
}
int value[row][column];
declares an array whose dimensions are based on 2 uninitialised values.
If you don't have to use a C-style array, you could use
std::vector<std::vector<int>> value;
and choose its dimensions based on user input.
Alternatively, you could continue to use a C-style array if you allocate it like
int** value;
// input row/column
value = new int*[row];
for (int i=0; i<row; i++) {
value[i] = new int[column];
}
If you use the latter approach, make sure to also delete all dynamically allocated memory later.
I am supposed to write a program that asks the user for a positive integer value. The program should use a loop to get the sum of
all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of
1, 2, 3, 4, ... 50.
But for some reason it is not working, i am having trouble with my for loops but this is what i have down so far.
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
int i = 0;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
return 0;
}
I am just at a loss right now why it isn't working properly.
The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.
try this:
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
cout << "Please input an integer upto 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i=startingNumber; i <= positiveInteger; i++)
{
result += i;
cout << result;
}
cout << result;
return 0;
}
I have the following formula that works without loops. I discovered it while trying to find a formula for factorials:
#include <iostream>
using namespace std;
int main() {
unsigned int positiveInteger;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
cout << (positiveInteger * (positiveInteger + 1)) / 2;
return 0;
}
You can try:
int sum = startingNumber;
for (int i=0; i < positiveInteger; i++) {
sum += i;
}
cout << sum;
But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2, so you do not need a loop at all, just use the formula n*(n+1)/2.
mystycs, you are using the variable i to control your loop, however you are editing the value of i within the loop:
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
Try this instead:
int sum = 0;
for (int i=0; i < positiveInteger; i++)
{
sum = sum + i;
cout << sum << " " << i;
}
int result = 0;
for (int i=0; i < positiveInteger; i++)
{
result = startingNumber + 1;
cout << result;
}
First, you have two variables of the same name i. This calls for confusion.
Second, you should declare a variable called sum, which is initially zero. Then, in a loop, you should add to it the numbers from 1 upto and including positiveInteger. After that, you should output the sum.
You are just updating the value of i in the loop. The value of i should also be added each time.
It is never a good idea to update the value of i inside the for loop. The for loop index should only be used as a counter. In your case, changing the value of i inside the loop will cause all sorts of confusion.
Create variable total that holds the sum of the numbers up to i.
So
for (int i = 0; i < positiveInteger; i++)
total += i;