I am trying to write a program in which a user will be prompted to enter an integer 3 times. After each integer, a sum will be displayed after the input. Then, with the second and third integers, the numbers should be added onto the initial sum within a loop. Here is what I have done:
#include <iostream>
using namespace std;
int main () {
double number=0, total=0;
for (double n=0; n<3; n++){
cout << "Enter an integer: ";
cin >> number;
cout << "Sum is: " << number <<endl;
total+=number; }
}
This is the output so far:
Enter an integer: 2
Sum is: 2
Enter an integer: 3
Sum is: 3
Enter an integer: 4
Sum is: 4
The goal is for the integers to continue to add to the sum until the loop is done. This is the output that I am trying to achieve:
Enter an integer: 2
Sum is: 2
Enter an integer: 3
Sum is: 5
Enter an integer: 4
Sum is: 9
Any help would be appreciated, as I am confused on how to solve this part, and it is the only part I need to figure out in order to complete it. Thanks for taking the time to read this!
cout << "Sum is: " << number << endl;
In this line you are printing the current number, not the total. You need to use total instead.
Also move total += number; before the previous line. Else you will be one step behind when displaying.
Thus your code should look like this:
#include <iostream>
using namespace std;
int main () {
double number=0, total=0;
for (double n=0; n<3; n++){
cout << "Enter an integer: ";
cin >> number;
total+=number;
cout << "Sum is: " << total << endl;
}
}
Related
I am very new to C++, and I am trying to make a simple number reading program, and it is functional. However, I keep getting a '1' input in between my other output lines. How can I remove these 1s?
Here is my code:
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
printf("\nThe following program should enter integer numbers until a negative number.\n");
printf("The output is the smallest number input as well as the number of numbers.\n\n");
printf("Please enter a number -----> ");
int n = 0;
int num;
cin >> num;
int smallest = num;
while (num >= 0)
{
n++;
if (num < smallest)
{
int smallest = num;
}
cout << "Please enter another number -----> " << (cin >> num) << endl;
}
while (num < 0)
{
cout << "Negative number entered. Calculating Results...\n\n";
cout << "Of " << n << " numbers read, the smallest number is " << smallest << ".\n";
return 0;
}
}
And the output looks like this (I randomly input some test numbers):
The following program should enter integer numbers until a negative number.
The output is the smallest number input as well as the number of numbers.
Please enter a number -----> 3
Please enter another number -----> 4
1
Please enter another number -----> 8
1
Please enter another number -----> -1
1
Negative number entered. Calculating Results...
Of 3 numbers read, the smallest number is 3.
'''
How do I remove these 1s, and why are they happening?
(cin >> num)
This expression does two things:
The cin input stream waits for user input and puts that value into num.
The operator overload for >> on an istream returns a istream&, a reference to the cin instance.
(This is why you can repeat the >> operator on one line to get multiple values.)
That expression is in a place where the cout << operator is expecting an argument, so the conversion from istream& to some sort of printable character is resulting in a 1 being added to the cout stream.
The reason the 1 is on a new line is because the terminal/console you're using requires you to use the Enter key (which adds a new line) to enter a value.
I tried this in my c++ console, and had to make a change in line 25. Instead of -
cout << "Please enter another number -----> " << (cin >> num) << endl;
I used this -
cout << "Please enter another number -----> ";
cin >> num;
And there were no explicit error messages. Also, no 1s.
I am a bit concerned about the actual code though. The logic is not correct.
How was you able to compile this code?
Doc.cpp:26:60: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘std::basic_istream::__istream_type {aka std::basic_istream}’)
cout << "Please enter another number -----> " << (cin >> num) << endl;
I have to change this line:
cout << "Please enter another number -----> " << (cin >> num) << endl;
into this:
cout << "Please enter another number -----> ";
cin >> num;
cout << endl;
in order to make the code compilable, at least for me.
Also, the last while loop is unnecessary, since if num is not bigger or equal to zero, it could only be a negative number.
I am writing code for an assignment that wants me to make a program that asks the user for the amount of integers they'd like to input then it accepts each input while testing if the value is the max value or the minimum.
The program runs fine but for some reason will stop and show me the min and max number when I have entered in 1 integer less than the original input.
Examples of the problem I am having:
If I input 5 for the first value, it asks me to enter 5 integers.
After entering 4 numbers, 1 2 3 and 4.
It tells me the max is 4 and min is 1.
It prevents me from entering in the 5th integer.
Additionally,
If I input 5 for the first value, it asks me to enter 5 integers.
If I enter a negative number, like -1, the input allowed to me is further
shortened.
If I enter -1, 2, 3 then the output is min: 2 and max: 3
I have two main questions:
What adjustments do I need to make to my code so that I can properly
enter in the number of integers initially asked for?
What adjustments need to be made in order for me to be able to enter
negative integers so they are outputted correctly?
The code:
#include <iostream>
using namespace std;
int main()
{
int input;
int tmp;
int counter = 1;
int max_num = 0;
int min_num;
// prompt user for integer amount
cout << "How many integers would you like to enter? " << endl;
cin >> input;
cout << "Please enter " << input << " integers." << endl;
tmp = input;
// loop for requested amount with a test for each input
while (counter <= tmp) {
cin >> input;
// if smaller than previous number it is the minimum
if (input < min_num || min_num == -1) {
min_num = input;
counter++;
}
// if larger than previous number it becomes max number else
if (input > max_num) {
max_num = input;
counter++;
} else { // continue loop if number isn't bigger than max or smaller than min
counter++;
}
}
// display the max and min
cout << "min: " << min_num << endl;
cout << "max: " << max_num << endl;
return 0;
}
I have this code and its job is to ask the user if how many elements they would like to enter in the array - the user then enters their desired elements - the elements are integers -then the program solves for the sum of the entered numbers.
Here's the code:
#include <iostream>
using namespace std;
int main()
{
int arr[20], i, n, sum=0;
cout<<"How many elements you want to enter?: ";
cin>>n;
cout<<"Enter any "<<n<<" elements in Array: ";
for(i=0;i<n;i++)
cout<<"How many elements you want to enter?: ";
cin>>n;
cout<<"Enter any "<<n<<" elements in Array: ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Sum of all Elements are: ";
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
for(i=0;i<n;i++)
{
cout<<sum;
getch();
}
I doesn't seem to work and the program doesn't run, so I can't put the actual output.
Expected output would be the sum of all the elements (integers) that the user entered.
Does it have to be an array? you can do it in a simpler way like this:
cout << "Enter number of elements\n";
cin >> n
cout << "Please enter the elements \n"
int temp = 0;
int sum = 0;
for(int i = 0; i<n ; i++){
cin >> temp;
sum+=temp;
}
cout << "Sum is: " << sum << endl;
One thin you need to note, you did not restrict the user to the max array size .. say he/she said 21 then you'll have an overflow which produces error.
Since you're using C++, I would suggest you go with vectors, or use the simple way I stated above.
Basic advice: design as you go, and at each stage, use a print-out to tell you what values are entered.
cin >> n;
cout << "Please enter " << n << " values to sum: " << endl;
for(i=0;i<n;i++)
{
cin >> arr[i];
cout << "value #" << i << ": " << arr[i] << " entered." << endl;
}
You basically want to move on to the next stage of processing only when you're sure that your program works for entering the initial data. Take each stage of processing one at a time, and output what the current stage is. This makes it much easier to work out which stage of processing is causing an error. You can cut back on the print commands later on once it's working as intended, but I'd recommend leave then in there but commented out. Sometimes incorrect inputs cause errors again, and it's handy to re-enable the debug prints to tell you what's going on.
Here is the program for your problem description.It takes input from the user to how much elements you want to enter into the array then it take elements and saved in an array then calculates the sum of array elements.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int arr[20],i,n,sum=0;
cout<<"How many elements you want to enter: ";
cin>>n;
cout<<"Enter any "<<n<<" elements in Array: ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Sum of all Elements are: " << endl;
for(i=0;i<n;i++)
{
sum=sum+arr[i];
cout << "sum of a[" << i << "] = " << sum << endl;
}
cout<< "the sum of all the elements (integers) that the user entered = " << sum;
getch();
return 0;
}
Now this program gives the information sum of a[i] elements is and so on to the end of the loop.
It is helpful to show the output or error message.
Try to convert cin into an integer or float for:
cin>>arr[i];
This is my first post on here so please don't kill me for my noobishness.
I recently made a program for fun to put in a ton of numbers and have it put out the mean, not very useful but I thought I would see if I could. I would love it if someone could explain to me how I could improve my code using arrays instead of lots of variables, but still achieve the same thing, maybe even more efficiently.
My code looks like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int q1;
int q2;
int q3;
int q4;
int q5;
int q6;
int q7;
int q8;
int q9;
int q10;
int q11;
int q12;
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
cin >> q1;
cin >> q2;
cin >> q3;
cin >> q4;
cin >> q5;
cin >> q6;
cin >> q7;
cin >> q8;
cin >> q9;
cin >> q10;
cin >> q11;
cin >> q12;
f = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12;
cout << f / a << '\n';
system("pause");
}
Any advice is very appreciated! This was made in Visual Studio just in case you needed to know.
Of course arrays can make your life easier!
Here's how you could have accomplished the same task as above, with arrays:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "You can only enter up to 12 numbers;
// Declare an array to hold 12 int's
int nums[12];
// i will count how many numbers have been entered
// sum will hold the total of all numbers
int i, sum = 0;
for(i = 0; i < 12; i++) {
cout << "Enter the next number: ";
cin >> nums[i];
sum += nums[i];
}
cout << "The mean is: " << (sum / totalNums) << '\n';
//Try to avoid using system!
system("pause");
}
But, why use an array?
There's no need to keep any of the numbers after you add them to the total, so why use an array?
You can accomplish the same task without an array and with only one variable for the numbers!
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "Enter the amount of numbers that will be entered: ";
cin >> totalNums;
// i will count how many numbers have been entered
// sum will hold the total of all numbers
// currentNum will hold the last number entered
int i, sum = 0, currentNum = 0;
for(i = 0; i < totalNums; i++) {
cout << "Enter the next number: ";
cin >> currentNum;
sum += currentNum;
}
cout << "The mean is: " << 1.0 * sum / totalNums << '\n';
//Try to avoid using system!
system("pause");
}
Arrays can be considered as series of variables each of which has ids.
integers between 0 and (number of elements) - 1 (both inclusive) are available ids.
Using that with loop, your code can be like this (sorry, I hate stdafx.h):
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int q[12];
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
for (int i = 0; i < 12; i++) {
cin >> q[i];
}
f = 0;
for (int i = 0; i < 12; i++) {
f += q[i];
}
cout << f / a << '\n';
system("pause");
}
You may use the numbers read in the future, but currently the numbers aren't used except for calculating the sum, so you can omit the array and do addition while reading. Also I deleted the variable t, which is unused and stopped using using namespace std;, which is not considered as good.
#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
int main() {
int q;
int f;
//Used for the total of all values
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
f = 0;
for (int i = 0; i < 12; i++) {
cin >> q;
f += q;
}
cout << f / a << '\n';
system("pause");
}
You marked this question as C++.
I recommend you do not use "using", and you should prefer vector over array.
Consider the following approach:
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
std::cout << "We will be finding a mean." << std::endl
<< "Enter numbers, and press ^d when complete.\n"
<< std::endl;
// Declare a vector to hold user entered int's
std::vector<int> intVec;
// the vector automatically keeps track of element count
do {
std::cout << "number: "; // prompt
int t = 0;
std::cin >> t; // use std::cin,
if(std::cin.eof()) break; // ^d generates eof()
intVec.push_back(t);
}while(1);
// there are several way to sum a vec,
// this works fine:
int sum = 0;
for (auto i : intVec) sum += i;
std::cout << "\n sum : " << sum
<< "\ncount : " << intVec.size()
<< "\n mean : " << (sum / intVec.size()) << std::endl;
return(0);
}
You can enter single item per line (neatness counts).
You can enter multiple integers separated by white space, but the above will give back a prompt for the integers already entered.
^d - generates an end of file input.
... press and hold 'Control' key and letter 'd' at same time
Note - does not handle error input - try entering a 'number' as 'num' string.
The accepted answer is definitely the most efficient way to transform your code using arrays, but one thing I would add is that in C++ dividing an integer by another integer can only ever result in an integer, and because you're trying to get the mean, it seems like you'd want to have the result in decimals, so you need to do one of two things:
Declare sum as a float for the purposes of diving it by totalNums to get the mean.
Cast one of the integers to either a float or a double so that the decimals won't get truncated, so the last cout statement would look like this:
cout << "The mean is: " << (double)sum/totalNums << endl;
In C++ the default for precision is 6, but you can change the number of decimal points that are displayed by adding #include <iomanip> and using the setprecision( ) function in the iomanip, which you can just add in the same output line:
cout << setprecision(x) << "The mean is: " << (double)sum/totalNums << endl;
where x is whatever precision you want.
If you want to try using dynamic memory
This is definitely not necessary for what you're doing, but it's interesting stuff and good practice!
One more thing is that if you want to be able to have the user enter integers indefinitely, you can dymanically allocate memory during runtime by declaring a array of pointers to integers (so it's an array of address locations instead of an array of integers) and some sentinal value so they can decide when to stop. That code would look like:
#include <iostream>
#include <iomanip>
using namespace std;
main( ) {
const int ARRAY_SIZE = 200;
const int SENTINAL = -999;
int totalNums = 0;
int sum = 0;
//declare an array of pointers to integers so
//the user can enter a large number of integers
//without using as much memory, because the memory
//allocated is an array of pointers, and the int
//aren't allocated until they are needed
int *arr[ARRAY_SIZE];
cout << "We will be finding a mean." << endl;
cout << "Enter integers (up to 200) or enter -999 to stop" << endl;
//add a conditional into the for loop so that if the
//user enters the sentinal value they will break out
//of the loop
for (int c = 0; c < ARRAY_SIZE; c++) {
//every time you iterate through the loop, create a new
//integer by using the new keyword using totalNums as
//the index
arr[totalNums] = new int;
cout << "Enter integer: ";
//input into the array of pointers by dereferencing it
//(so it refers to what the pointer is pointer to instead
//of the pointer)
cin >> *arr[totalNums];
if (*arr[totalNums] == SENTINAL)
break;
else {
sum += *arr[totalNums];
totalNums++;
}
}
cout << setprecision(3) << "The mean is: " << (float)sum / totalNums << endl;
}
When I'm trying to run the program and execute it the for loop doesn't repeat of an adequate form, when I'm trying to execute it appears me this:
Enter a number:
5.6
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
I tried to search some information about this problem, but I don't found anything. I know that is a foolish question but I don't know where else to turn. A help is appreciated.
I left you my code:
#include <iostream>
using namespace std;
int main (void){
int num, sum;
float average;
for(int i=0; i<10; i++){
cout << " Enter a number: " <<endl;
cin >>i;
sum += num;
}
average = num / 10;
cout << " The total average is:\n " << media <<endl;
}
cin fails its formatted input operation. It was expecting an integer, but you entered into it a floating point number. Hence, it failed. change the input to a float or double.
A couple of more problems with your code:
You can write int main(), rather int main(void). The void isn't quite useful here
Always initialize your variables before use
Sometimes, check for cin failures and report errors if need be
Corrected code...
#include <iostream>
using namespace std;
int main (){
int num = 0, sum = 0;
float average = 0;
for(int i=0; i<10; i++){
cout << " Enter a number: " <<endl;
if(!(cin >> num)){ //you can also use a while loop to force requirement of proper input
cin.clear();
cin.ignore(100000, '\n');
// you can print an error message here
}
else
sum += num;
}
average = static_cast<float>(sum) / 10;
cout << " The total average is:\n " << average <<endl;
}
See Why would we call cin.clear() and cin.ignore() after reading input?
You have three things that ain't correct:
First of all, you have to initialize sum before using, like so int sum = 0;.
Second of all, the entered number has to be saved in a variable. You can't use i as that variable 'cause it's you loop iterator, therefore you can use num.
Last of all, media has no meaning in your program. and i know you meant to use average.
After correcting all of these, your program should look like this one:
#include <iostream>
using namespace std;
int main (void){
int num, sum=0;
float average;
for(int i=0; i<10; i++){
cout << " Enter a number: ";
cin >>num;
sum += num;
}
average = num / 10;
cout << " The total average is:\n " << average <<endl;
system("pause");
}