The 'for' not running well - c++

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");
}

Related

Summing values from user input while looping (C++)

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;
}
}

c++ Adding 100 numbers to each other

I know most of people may find this too easy but i am still very new to programming so i need a program that allows the user to enter 100 numbers and the program finds their sum , i have tried this:
#include <iostream>
using namespace std;
int main ()
{
float x;
int counter=0 , sum=0;
cout<<"enter a number\n";
cin>>x;
do {
sum+=x;
cout<<"sum="<<sum<<endl;
counter++;
}
while ( counter<=100 );
}
i found this making 'x' has the value that i entered first time but i need to enter different value every time it repeats (entering 100 different values) what should i add?
Simply move the input prompt and cin into the loop
do
{
cout << "enter a number\n";
cin >> x
sum += x;
cout << "sum=" << sum << endl;
counter++;
}
while (counter < 100);
Take note that it should be counter < 100 instead of counter <= 100 if you want it to be exactly 100 times.
You just have put the cin into the loop so that in every iteration it asks for an input.
Also note that the variable sum is an integer, while the variable x is a float.
So you probably should make sum a float or make x an integer to avoid getting unexpected results .
#include <iostream>
using namespace std;
int main () {
float x,sum=0;
int counter=0 ;
do {
cout<<"enter a number\n";
cin>>x;
sum+=x;
cout<<"sum="<<sum<<endl;
counter++;
} while ( counter<=100 );
}
You can use a For loop also for simplicity. Make sure to use long int data type for storing sum because the sum of 100 integers may lead to integer overflow.
#include <iostream>
using namespace std;
int main() {
int x, num;
long int sum=0;
cout<<"Enter the number you want to find the sum:";
cin>>num; // Like 100
for(int counter=1;counter<=num;counter++)
{
cout<<"Enter a number:";
cin>>x;
sum+=x;
}
cout<<"Sum of "<<num<<" numbers is:"<<sum;
return 0;
}
You could also do it in a for loop:
float input, sum;
for(int i = 0;i < 100; i++){
cout << "Enter a number << endl;
cin >> input;
sum += input;
cout << "sum is: << sum << endl;
}
Look out at the condition of your while. You are saying this -> counter<=100, and counter is initialized to 0. So, you will enter from 0 to 100(included) = 101 times. If you only want to enter 100 times, the condition should be
do
{
cout << "enter a number\n";
cin >> x
sum += x;
cout << "sum=" << sum << endl;
counter++;
}
while (counter < 100);
or initialize counter to 1, and then you can use the same while as you had.

c++ - Putting values (and solving for its sum) in an array

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];

C + + Can I use arrays here to shorten my code?

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;
}

I modified the following C++ program, but did i get it correct?

In the analysis of the following program my book says, "In this sample, the input parameter containing the number sent by the user has been modified. If you need both values, the original and the square, you can have the function accept two parameters: one that contains the input and the other that supplies the square."
#include <iostream>
using namespace std;
void ReturnSquare(int& Number)
{
Number *= Number;
}
int main()
{
cout<< "enter a number you wish to square: ";
int Number = 0;
cin>> Number;
ReturnSquare(Number);
cout<< "square is: " << Number <<endl;
cout<< "press enter to continue..." <<endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
I made a quite extensive modification to this program, which compiles and runs properly, but did I demonstrate what the book was asking me to correctly? Please help me I am only beginning. Modification follows:
#include <iostream>
using namespace std;
void ReturnSquare(int& Number, int Number2)
{
cout<< "do you wish to add number ?...(y/n) ";
char CalcCircum = 'n';
cin>> CalcCircum;
if (CalcCircum == 'n' || 'y')
Number *= Number;
if (CalcCircum =='y')
cout<< "addition of number is..." << Number2 + Number2 <<endl;
}
int main()
{
cout<< "enter a number you wish to square: ";
int Number = 0;
cin>> Number;
ReturnSquare(Number, Number);
cout<< "square is: " << Number <<endl;
cout<< "press enter to continue..." <<endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
Please tell me Where my admittedly little experienced thinking has, as I suspect, gone wrong. Thank you all, sincerely newmanadam
The exercise asks for a very unconventional manner to return a value.
void calc(int argument, int& returnValue){
returnValue = argument * argument; }
You have to call it in an odd way:
int returnValue;
int square = 17;
calc(square, returnValue);
std::cout << returnValue;
You might see 289 on your console.
You made it a lot more complicated that it needs to be. Change the function to:
void ReturnSquare(int in, int& out)
{
out = in*in;
}
and then change main to:
int main()
{
cout<< "enter a number you wish to square: ";
int messaround = 0;
cin>> messaround;
int sq;
ReturnSquare(messaround, sq);
cout<< "original number is: " << messaround <<endl;
cout<< "square is: " << sq <<endl;
cout<< "press enter to continue..." <<endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
This very slight variation of my modified problem program also works, and is perhaps slightly more readable. Variation follows:
#include <iostream>
using namespace std;
void ReturnSquare(int& Number, int Number2)
{
cout<< "do you wish to add number ?...(y/n) ";
char CalcCircum = 'n';
cin>> CalcCircum;
Number *= Number;
if (CalcCircum =='y')
cout<< "addition of number is..." << Number2 + Number2 <<endl;
}
int main()
{
cout<< "enter a number you wish to square: ";
int messaround = 0;
cin>> messaround;
ReturnSquare(messaround, messaround);
cout<< "square is: " << messaround <<endl;
cout<< "press enter to continue..." <<endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
Thank you all very much. Much respect from a newbie programmer (but hopefully not by this time next year). Peace to all fellow coders, sincerely, newmanadam