What is a way to solve this with loops in c++? - c++

I've been coding all night so my head is in a state of shock. I'm trying to do the following, but I just don't get what our professor wants us to do. "Input an unsigned and call it number.. Then input number double values, then output the sum and product of the numbers. (If number is zero, then 0 doubles will be input; the sum of 0 numbers is 0, and the product of 0 numbers is 1)"
I could really appreciate if someone could help me with this. Thank you.
Edit:
This is what i have so far, The thing I'm currently confused with is on how to make the unsigned variable be the number of double inputs inside of the loop.
unsigned number, x;
double double_num, sum;
cout << "Input the number of value: \n";
cin >> number;
for (x = 0; x > number; x++) {
cin >> double_num;
}
return 0;

What're you having difficulty with?
Here's a start:
// Input an unsigned and
unsigned int g;
cout << "Please Enter an unsigned int value, g" << endl;
cin >> g;
In your loop, you have:
for (x = 0; x > number; x++) {
Which means:
x is set to Zero.
While x is bigger than some-number, keep going...
When do you think zero is bigger than a number such as 5??
How many times do you think that loop will run??
int main(void)
{
unsigned g;
double product(1);
double sum(0);
cout << "Input the number of value: \n";
cin >> g;
for (unsigned x = 0; x < g; x++) {
double n;
cout << "Input a number: " <<endl;
cin >> num;
product *= num;
sum += num;
}
cout << "The product is" << product << "\n";
cout << "The sum is" << sum << "\n" << endl;;
return 0;
}

You need something like the following:
#include<iostream>
#include<cstdlib>
int main()
{
unsigned int n;
std::cin >> n;
double g, p=1, s=0;
while (n-->0 && std::cin >> g) p*=g,s+=g;
return std::cin
? std::cout << s << std::endl << p << std::endl, EXIT_SUCCESS
: (std::cerr << "Failed to read all inputs" << std::endl, EXIT_FAILURE);
}
You should be sure that you understand each statement and be prepared to justify your choices; if not, you probably haven't learnt anything and will be unlikely to pass your course.

Related

How to calculate mean using calling function in C++?

The functions are getInputN(), calculateMean() & displayData().
So to be really clear, these are the requirements.
getInputN function: Should accept the number of the value, N as an integer as argument and ask the user to enter the value of N number. Then, return the sum of the value as a double.
calculateMean function: Should accept the number of the value, N and sum of the value as arguments. Then return the mean as a double.
displayData function: Should accept the mean as argument. Then, display them in the appropriate message on screen. No return value required for this function.
If I run the code, it will display Average = inf
p/s: I'm really sorry for the confusing question at first. I'm really new to this website and this is my very first question. It took me some times to figure out things to ask properly in this platform. I hope you guys understand and once again, sorry for the inconvenience. Thank you for the helps too :)
Here is my code:
#include <iostream>
using namespace std;
int getInputN(int n);
float calculateMean (int n, float sum);
float displayData(double mean);
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN(n);
calculateMean (n, sum);
displayData(mean);
return 0;
}
int getInputN(int n)
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
return n;
}
//function to calculate the mean
float calculateMean (int n, float sum)
{
mean = sum/n;
return mean;
}
//function to display the mean
float displayData (double mean)
{
cout << "Average = " << mean;
}
The argument int n in the function getInputN is shadowing (hiding) the global variable n. This prevents the global variable from being updated and sum is divided by zero (the default value of gloval variable without explicit initialization).
If you want to pass data using gloval variables, the arguments should be removed because one of that (n as descrived above) is harmful and other are redundant.
Also the function displayData is declared to return float but didn't execute any return statement. This invokes undefined behavior. I fixed this by changing its return type to void.
#include <iostream>
using namespace std;
int getInputN();
float calculateMean ();
void displayData();
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN();
calculateMean ();
displayData();
return 0;
}
int getInputN()
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
return n;
}
//function to calculate the mean
float calculateMean ()
{
mean = sum/n;
return mean;
}
//function to display the mean
void displayData ()
{
cout << "Average = " << mean;
}
This fix will make the code work, but there should be better design without usage of global variables. References is useful to have functions modify things given as arguments and std::vector is useful to return "arrays".
The variable n in int getInputN(int n) is used in the function instead of the global n declared. As such, using global n (which is uninitialized till that point initialized to 0) to calculate mean = sum/n will lead to a undefined behavior divide by 0 error, resulting in inf.
More info :
Uninitialized variable behaviour in C++
C++ global and local variables
Also, the function float displayData (double mean) doesn't return any value, causing another undefined behavior.
More info :
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
Modified code :
#include <iostream>
using namespace std;
void getInputN();
void calculateMean();
void displayData();
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN();
calculateMean();
displayData();
return 0;
}
void getInputN()
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
}
//function to calculate the mean
void calculateMean ()
{
mean = sum/n;
}
//function to display the mean
void displayData ()
{
cout << "Average = " << mean;
}
Result :
Enter the numbers of data: 3
1. Enter number: 1
2. Enter number: 3
3. Enter number: 6
Average = 3.33333
Furthermore, if you don't use the numbers for anything else, declaring a float num[50]; is quite pointless. Also, noted that using global variable and using namespace std; is not recommended.
#include <iostream>
const int maxn = 50;
const int minn = 1;
int main()
{
int n; std::cout << "Enter N : "; std::cin >> n;
while (n < minn || n > maxn) {std::cout << "Invalid. Re-enter N : "; std::cin >> n;}
double sum = 0; int tmp;
for (int i = 0; i < n; i++) { std::cout << "Enter number " << i+1 << " : "; std::cin >> tmp; sum += tmp;}
std::cout << "Average : " << sum/n;
}
Result :
Enter N : 3
Enter number 1 : 25
Enter number 2 : 97
Enter number 3 : 111
Average : 77.6667
Knowing how the functions are behaved, we can write implementations that work nicely and don't use any global variables at all.
#include <iostream>
double getInputN(int n);
double calculateMean(int n, double sum);
void displayData(double mean);
int main()
{
//User enter the number of value
int numEntries;
std::cout << "Enter the numbers of data: ";
std::cin >> numEntries;
//if user input more than 50 numbers
while (numEntries > 50 || numEntries <= 0)
{
std::cout << "Invalid! Enter the number in range of (1 to 50)." << std::endl;
std::cout << "Enter the number of data: ";
std::cin >> numEntries;
}
// Get user input
double sum = getInputN(numEntries);
double mean = calculateMean(numEntries, sum);
displayData(mean);
return 0;
}
double getInputN(int n)
{
double sum = 0.;
for (int i = 0; i < n; ++i)
{
double userInput;
std::cout << i + 1 << ". Enter number: ";
std::cin >> userInput;
sum += userInput;
}
return sum;
}
//function to calculate the mean
double calculateMean(int n, double sum)
{
double mean = sum / n;
return mean;
}
//function to display the mean
void displayData(double mean)
{
std::cout << "Average = " << mean;
}
Let's go into some more detail on each of the changes.
First, I've changed the signatures of all of your functions. getInputN is supposed to return a double, not an int. calculateMean is supposed to accept and return a double, not a float. And displayData isn't required to return anything, it doesn't make sense for it to return anything, and therefore I've made its return type void.
Second, note that I've moved the code for figuring out how many entries to enter from getInputN into main. The reason for this is that the sole argument to getInputN is "how many inputs should we get?", so we need to know its value before we call getInputN.
Third, note how I've used the return values from each function in the calling code. In main, when I write double sum = getInputN(numEntries);, that declares a variable sum and stores the return value of getInputN(numEntries) to sum. When you just write getInputN(n);, the return value from getInputN is discarded. By storing it in a variable in main, I can then pass its value to another function, like in the next line where I've written double mean = calculateMean(numEntries, sum);.
Fourth, note how the requirements of the question are such that I no longer use any kind of array whatsoever. getInputN doesn't bother tracking each individual entry, because all we care about is the final sum at the end.

Integers not getting added up correctly but doubles are working fine

I know this isnt the right kind of question to be asking, but for the life of me I could not figure out what is causing this problem.
I need to write a problem that takes a set number of integers or doubles and returns their sum.
I have written the code to make this work, making sure to check each time I changed something.
#include<iostream>
using namespace std;
template <class T>
class totalClass
{
private:
T *p;
T Total;
T sum;
int size;
public:
T total(int x)
{
size = x;
p = new T[x];
for (int i = 0; i < size; i++)
p[i] = T();
if (size > 1)
{
for (int i = 0; i < size; ++i)
{
cin >> sum;
Total += sum;
}
}
return Total;
}
};
int main()
{
int size, result1;
double result2;
cout << "Enter: ";
cin >> size;
cout << "the number of ints you wish to enter: Enter: " << size << " integers:";
totalClass<int> test;
result1 = test.total(size);
cout << " Total = " << result1 << endl;
cout << "Enter: ";
cin >> size;
cout << "the number of doubles you wish to enter: Enter: " << size << " doubles:";
totalClass<double> test2;
result2 = test2.total(size);
cout << " Total = " << result2 << endl;
}
My doubles are getting added up correctly but my integer addition always seems to add up to some crazy number. Is there something wrong with my problem that I cannot see?
If you forget to initialize a variable and attempt to use it or do math with it, you might end up with "crazy numbers." Make sure all of your variables are Initialized.

Exercise: for cycle and array

I have to write a program that allows to calculate the arithmetic average of an arbitrary numbers of values (chosen by the user)
It will outputs:
Number: 34
Number: 36
Number: 44
Number: //and I choose to stop input pressing
//Outputs:
It was inserted 3 numbers and the avarage is: 38
Of course i've forgot to post what i've done:
for (int x = 0; x < 50; x++){
cout << "Number: ";
cin >> number[x];
cout << "You have inserted the " << x << " element of the array;" << endl;
sum += number[x];
avarage = sum / number[x];
nEelementi = number[x];}
so I run the program, input some numbers, press something like ctrl+d or trying to add something to the code.. but it only goes from the first to the last element of the array with no values, becouse not entered, of course.. and then print absurd avarage and sum.
I know I don't need an array to do this but it's required from the exercise.. also the exercise only request to use for or while loop and arrays.
What I need is a way to stop the input and calculate the sum and avarage of only what I wrote.
edit1.
I've tried to dived by n writing for(x = 0; x < n, x++) because it made sense to me, but i think it "thinks" n, wrote like this, infinite, because the results is 0 (because the limit of a number divided by infinite is 0).. so i've started becoming mad.
Now i've started thinking that it would be easier to use while loop! and wrote
#include <iostream>
using namespace std;
int main() {
int num[50];
double sum = 0;
double average = 0;
int cont;
int end = 0;
while (cont < 50) {
cout << "num: ";
cin >> num[cont];
sum += num[cont];
cont++;
cout << "Want to continue 0 = sì, 1 = no";
cin >> end;
if (end == 1) {break;}
}
average = sum / cont;
cout << "You have insert " << cont << " elements" << endl;
cout << "LThe sum is: " << sum << endl;
cout << "The avarage is: " << average << endl;
return 0;
}
BUT still doesn't work. My professor says you should be able to stop input number by pressing ctrl+d so I'm not doing good.
Sorry for late answer but i have also to translate the code.. hope all translation is good:)
edit2.
#include <iostream>
int main() {
int sum = 0;
int num;
while ( std::cin ) {
std::cout << "Number: ";
std::cin >> num;
}
if ( std::cin >> num ) {
sum += num;
num++;
}
else {
std::cin.clear();
std::cout << "Input interrupted" << std::endl;
}
std::cout << "Sum is " << sum << std::endl;
std::cout << "You have entered " << num << " numbers" << std::endl;
return 0;
}
I love this new code, very simple and understandable to me, but I was not able to add sum operation, it only outputs 0! (leaving out average)
And also I was not able to determinate, and display, how many numbers I've entered. The last row of the code is just an example of what I want to do..
edit3.
Finally I made it.
#include <iostream>
using namespace std;
int main(){
double numero;
int index = 0;
double somma = 0.;
cout << "Inserire un numero: ";
while( cin )
{
if ( cin >> numero )
{
somma = somma + numero;
index++;
cout << "Inserire un numero: ";
}
else
{
cout << "Input interrotto" << endl;
}
}
cout << "Sono stati inseriti " << index << " numeri e la lora media è:
<< somma / index << endl;
return 0;
}
Thanks so much!
P.S. To the end, I don't need to use an array, it's just simple
There are a few problems here. One is that if the stream errors due to being closed or bad input, you don't recover and you just charge through your loop.
So first, make the loop terminate early if necessary. I'm also going to convert it to a while loop in preparation for the next part.
int x = 0;
while( std::cin && x < 50 )
{
std::cin >> number[x++];
}
Now it terminates early if the stream errors. But what if the user typed in "hello"? You could ignore it and continue like this:
if( std::cin >> number[x] )
{
x++;
}
else
{
std::cin.clear();
}
Notice that I didn't compute the sum or anything inside the loop. There's no need, since you are already putting them in an array. You can just do it after the loop. Here, I'm using std::accumulate
double sum = std::accumulate( number, number + x, 0.0 );
double average = 0.0;
if( x > 0 ) average = sum / x;
Now, you have also said you want an arbitrary number of values. Your original code allowed up to 50. Instead of storing them, you can instead just compute on the fly and discard the values.
double sum = 0.0;
int count = 0;
while( std::cin )
{
double value;
if( std::cin >> value )
{
sum += value;
count++;
}
else
{
std::cin.clear();
}
}
double average = 0.0;
if( count > 0 ) average = sum / count;
If you still want to store the values along the way, you can use a vector.
std::vector<double> numbers;
//...
numbers.push_back( value );
And if you want the user to choose the number of values:
std::cout << "Enter number of values: " << std::flush;
std::size_t max_count = 0;
std::cin >> max_count;
std::vector<double> numbers;
numbers.reserve( max_count );
while( std::cin && numbers.size() < max_count )
{
// ...
}

How to record multiple values based upon a user-entered number?

My lab professor wants us to make a program that "Use a for loop to write a program that calculates the product of x integers entered by the user; where x is entered by the user as well. Repeat the question using while or do-while."
After further clarification, I realized he meant something like the user enters a number, say 5. The program will then prompt the user to enter 5 numbers. The program then displays the product of those 5 entered numbers. I get how it works now, but i don't understand how I can store all those numbers and bring them out for multiplication later.
This is all I have so far:
#include <iostream>
using namespace std;
int main() {
int numofNumbers = 0;
cout << "Enter the number of numbers you want multipled: ";
cin >> numofNumbers;
for (numofNumbers; numofNumbers > 0; numofNumbers = numofNumbers - 1) {
cout << "Enter a number"; //how can I record these values then multiply them?
cout << endl;
}
system("pause");
return 0;
}
Complete code using WHILE loop
#include <iostream>
using namespace std;
int main()
{
int n, count = 0;
int input, result = 1;
cout<<"Enter number: ";
cin>>n; // n numbers
while (count < n)
{
cout<<"Enter number "<<count + 1<<": ";
cin>>input; // taking input
result *= input; // multiplying
count++;
}
cout<<"Total result is: "<<result;
return 0;
}
You're assuming that you need to store all the user-provided numbers in order to multiply them - this is not true. I suggest spending more time thinking on a way to solve your assignment without storing all the passed numbers.
In order to answer your question: the most common way of storing items in C++ is using std::vector. In order to understand what it is doing, you should have some knowledge about arrays and carefully read the documentation.
So you managed to calculate the factor of those numbers, now you want to store them to use it later.
You can use a the vector container from the STL to store your numbers. Bellow is an example :
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers;
int numofNumbers = 0;
int number;
cout << "Enter the number of numbers you want multipled: ";
cin >> numofNumbers;
for (numofNumbers; numofNumbers > 0; numofNumbers = numofNumbers - 1) {
cout << "Enter a number";
cin >> number;
numbers.push_back(number); // store the numbers
cout << endl;
}
// do what you want with stored numbers in the vector....
// ....
//
for (auto it: numbers){
cout << it << std::endl;
}
return 0;
}
If storing N number isn't a requirement, you can multiply values on place:
int numofNumbers = 0;
int result = 1
cout << "Enter the number of numbers you want multipled: ";
cin >> numofNumbers;
for (; numofNumbers > 0; numofNumbers = numofNumbers - 1) {
cout << "Enter a number";
int num = 1;
cin >> num;
result *= num;
}
if (numofNumbers > 0) {
cout << "Multiplication result is: " << result;
}
You don't need to store numbers. Just multiply as a number is entered.
#include <iostream>
using namespace std;
int main() {
unsigned int numofNumbers = 0;
int product = 0;
int number = 0;
int tempNumofNumbers = 0;
cout << "Enter the number of numbers you want multipled: ";
cin >> numofNumbers;
tempNumofNumbers = numofNumbers;
while(tempNumofNumbers) {
cout << "Enter a number";
cin >> number;
if(tempNumofNumbers == numofNumbers)
{
product = number;
}
else
{
product *= number;
}
tempNumofNumbers--;
}
cout << "product" << product;
system("pause");
return 0;
}
For recording input, you could use:
#include <iostream>
int main() {
int numofNumbers = 0;
std::cout << "Enter the number of numbers you want multipled: ";
std::cin >> numofNumbers;
double total = 1;
for (int counter = numofNumbers; counter > 0; counter--)
std::cout << "Enter a number: " << std::endl;
std::cin >> input_number;
total = total * input_number; //multiple the numbers
}
if (numofNumbers > 0) {
std::cout << "total is: " << total << std::endl;
}
system("pause");
return 0;
}

Primary expression before Double which is in my Array?

IT keep asking me for a primary expression before Double which is in my int Array and i dont know what to do. i have midterms tomorrow ugh this hurts my brain. All other input would be helpful thanks :)
#include <iostream>
#include <iomanip>
using namespace std;
void get_input(double array[50], int& sizearray1)
{
cout << "How many doubles do you wish to add?" << endl;
cin >> sizearray1;
while(sizearray1 < 1 || sizearray1 > 50) {
cout << "Error: That is an invalid number! You must enter a value between 1 and 50.\nHow many doubles do you wish to add?" << endl;
cin >> sizearray1;
}
for(int n=1;n<sizearray1;n++){
cout << "Enter Double " << n << endl;
cin >> array[n];
}
}
double calcSum(double array[50],int sizearray1)
{
int sum
cout << "The sum is ";
for(n=1,n<sizearray1,n++){
sum += array[n]
}
cout << sum << endl;
}
void printArray(double c[],int sizearray1)
{
cout << "The array contains:\n";
for(int n=1;n<sizearray1;n++){
cout << setprecision(2) << showpoint << fixed << c[n] << " ";
}
calcSum(double array[50],int sizearray1);
}
int main()
{
double array1[50];
int sizearray1 = 0;
get_input(double array[50],int sizearray1);
printArray(double array[50],int sizearray1);
Firstly I'm going to start off with some errors, as THIS code can't compile. No way.
You're missing a semicolon at int sum line 21. Your for loop at line 23 has commas instead of semicolons. You're using a undefined variable n = 1 in the same loop, you have to declare it before doing so for(n=1,n<sizearray1,n++). Again in the same for loop at line 24 you forgot another semicolon sum += array[n].
Back to your question:
You can't give a function a type parameter, you would actually try to declare a variable there. Also please don't declare a function like this double calcSum (double array[50], int sizearray1) as this is really not what you want... use this instead double calcSum (double array[/*Nothing here*/], int sizearray1).
Please check your whole code and fix all errors. This is a fix of me. Of course it doesn't work, your code is a bit to messy, check all the functions and give them the right parameters.
#include <iostream>
#include <iomanip>
using namespace std;
void get_input (double array[], int& sizearray1)
{
cout << "How many doubles do you wish to add?" << endl;
cin >> sizearray1;
while (sizearray1 < 1 || sizearray1 > 50)
{
cout << "Error: That is an invalid number! You must enter a value between 1 and 50.\nHow many doubles do you wish to add?" << endl;
cin >> sizearray1;
}
for (int n = 1; n < sizearray1; n++)
{
cout << "Enter Double " << n << endl;
cin >> array[n];
}
}
double calcSum (double array[], int sizearray1)
{
int sum;
cout << "The sum is ";
for (int n = 1; n < sizearray1; n++)
{
sum += array[n];
}
cout << sum << endl;
}
void printArray (double c[], int sizearray1)
{
cout << "The array contains:\n";
for (int n = 1; n < sizearray1; n++)
{
cout << setprecision(2) << showpoint << fixed << c[n] << " ";
}
calcSum (array[50], sizearray1); //This still can't work, the variable "array" has not been declared
}
int main()
{
double array1[50];
int sizearray1 = 0;
get_input (array[50], sizearray1); //Again "array" has not been declared
printArray (array[50], sizearray1); //Again "array" has not been declared
return EXIT_SUCCESS;
}
When calling a function don`t include the type like :
calcSum(double array[50],int sizearray1);
But simply use the variable names :
calcSum(array[50],sizearray1);
same with your get_input() and printArray() functions.
And in your printArray() function, I think you are recieving the passed array into the variable c. So it should be :
calcSum(c[50],sizearray1);
And I think you are trying to pass the whole array, then you just have to use the arrayname:
calcSum(c,sizearray1);
c[50] will only pass the element at 50th position in the array.