total the even numbers and product the odd - c++

I am trying to make code that gets from user, the number of inputs and value of each input and then calculate total sum of the even numbers and product of the odd numbers.
I get to put in the first number but then the for loop does not work.
#include <iostream>
#include <vector>
int main() {
int totalNum;
int total_even;
int product_odd;
std::vector<int> numbers;
std::cout << "How many numbers would you like to entre?:";
std::cin >> totalNum;
std::cout << "\n";
for (int i = 1; i <= totalNum; i++){
std::cout << "Please entre number " << i << "\n";
std::cin >> numbers[i];
if (numbers[i] % 2 == 0) {
total_even = total_even + numbers[i];
} else {
product_odd = product_odd * numbers[i];
}
}
std::cout << "Sum of even: " << total_even << "\n";
std::cout << "Product of odd: " << product_odd;
}

First off, there's no need for a vector since, once you've finished with the number, you never need to use it again. Getting rid of the vector will remove the erroneous assignment to a non-existing element (appending to a vector is done with push_back rather than assigning beyond the end).
Second, since you're either adding the number to, or multiplying the number by, some accumulator, the accumulators should be initialised. You should initiliase total_even to zero and product_odd to one, so that the operations work out (0 + a + b == a + b, 1 * a * b == a * b). As it stands at the moment, your initial values are arbitrary so your results will also be arbitrary.
By way of example, here's a possible solution (though you should edit your own program rather than use this verbatim: it's a near-certainty that educators will be checking classwork, assuming that's what this is, for plagiarism):
#include <iostream>
int main() {
int numCount, thisNum, sumEven = 0, productOdd = 1;
std::cout << "How many numbers would you like to enter? ";
std::cin >> numCount;
std::cout << "\n";
for (int i = 1; i <= numCount; i++) {
std::cout << "Please enter number #" << i << ": ";
std::cin >> thisNum;
if (thisNum % 2 == 0) {
sumEven += thisNum;
} else {
productOdd *= thisNum;
}
}
std::cout << "\nSum of even: " << sumEven << "\n";
std::cout << "Product of odd: " << productOdd << "\n";
}
A sample run:
How many numbers would you like to enter? 6
Please enter number #1: 1
Please enter number #2: 2
Please enter number #3: 3
Please enter number #4: 4
Please enter number #5: 5
Please enter number #6: 6
Sum of even: 12
Product of odd: 15

Related

Trying to validate user input for repeating values in 2D array

So I'm working on a Lo Shu Magic Square for my first programming class and I'm stuck. I'm sure everyone here will know what that is but just in case, it's a 2D array that takes 9 numbers from user input, but they have to be between that range (1-9) and also non repeating (where I'm stuck).
I can validate for numbers within the 1-9 range, but I'm having trouble also validating for the second condition of non-repeating numbers
Here's my code for the function that takes user input:
(Oh yea, the 2D array is 3x3 so ROWS = 3 and COLS = 3 and they're being passed to this function)
// Get numbers
void getNumbers(int magicSquare[][COLS], int ROWS)
{
cout << "\nEnter Nine Numbers (1-9)" << endl;
int num;
int n = 0;
for (int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
cout << "\tNumber " << (n + 1) << ": ";
cin >> num;
magicSquare[r][c] = num;
n++;
// Input validation
// Validate against numbers outside the range
while (num < 1 || num > 9)
{
cout << "\tError ... Invalid number. Try again" << endl
<< endl;
cout << "\tNumber " << (n) << ": ";
cin >> num;
magicSquare[r][c] = num;
}
// Validate against repeating numbers
while (...) //OMEGA STUCK
{
cout << "\tError ... " << num << " is already in the
Lo Shu Square. Try again" << endl <<endl;
cout << "\tNumber " << (n) << ": ";
cin >> num;
magicSquare[r][c] = num;
}
}
}
cout << endl;
}
I have tried several approaches, from using while loops, to trying temp arrays, and I'm currently attempting to create a new bool function and pass the array and input to it but with little success.
// Validate against repeating numbers
while (repeatNumbers(magicSquare, num)) // Calling boolean function (defined below)
{
cout << "\tError ... " << num << " is already in the Lo Shu Square.
Try again" << endl << endl;
cout << "\tNumber " << (n) << ": ";
cin >> num;
magicSquare[r][c] = num;
}
...
// Validate against repeating numbers function
bool repeatNumbers(int magicSquare[][COLS], int num)
{
bool status;
if (num == magicSquare[COLS][COLS]) //Here I get an error:
{ //"Reading invalid data from
status = true; //'magicSquare[COLS]'.
}
else
{
status = false;
}
return status;
}
Is there a way to ensure that reading a partially filled-in array is well-behaved, what's the best approach? I can't arrive at the correct way, and I just KNOW I'm missing something that is quite logical which my tired brain can't think of at this point.
Any ideas on how to test for both conditions?

Show the sum in c++ and after that add more sum cpp

Consider a program that asks the user for an integer value greater than 10, say 15. The program should then calculate the sum of all positive values up to 15 and now I need to "show the
current sum after adding each number".
For the first part I made everything like this:
#include <iostream>
using namespace std;
int main()
{
int num = 0;
int sum = 0;
cout << " Please enter how many number you'd like to sum up\n";
cin >> num;
while (num <= 10)
{
cout << "Please enter an integer which is more than 10";
cin >> num;
}
for ( int i = 1; i <= num; i++)
{
sum += i;
}
cout << "The total sum is : " << sum;
But now I dont know what should i do?
It should look like this in the end.
You can do this by outputting the values used in the calculation, along with the 'running' total, inside your summation loop:
for (int i = 1; i <= num; i++)
{
cout << sum << " + " << i << " = " << sum + i << "\n";
sum += i;
}
Feel free to ask for further clarification and/or explanation.

Finding the minumum value out of user inputs in C++

My problem is finding the minimum value out of user defined number of inputs. Everything so far works just fine, except that. Every time I try and rearrange some code or try a new method, I keep getting the same output on the screen:
Sum of numbers entered is: 145.4
Average of numbers entered is: 24.2333
The Highest number entered was: 45
The Lowest number entered was: 6.95283e-310
I get this every single time, regardless of what is entered, or what different suggestion I try:
The Lowest number entered was: 6.95283e-310
I am aware of the use and implementation of Arrays. However, the assignment I'm doing hasn't even covered arrays yet. That is some number of chapters later. Please don't suggest arrays...
I've looked here:
Finding Maximum and Minimum values in c++ by user input
Didn't work
http://www.cplusplus.com/forum/beginner/38799/
Didn't work
changing the values of max/min didn't work either
#include <iostream>
using namespace std;
int main()
{
double number, numberitems, sum = 0, average, max, min;
cout << "Enter number of items: \n";
cin >> numberitems;
//Make sure user can not enter negatives
if ( numberitems < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number > max) {
max = number;
}
//minimum value entered
if (number < min) {
min = number;
}
//Make sure user can not enter negatives
if ( number < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Sum of all the numbers
sum = sum + number;
//Average of all the numbers
average = sum / numberitems;
}
std::cout << endl;
std::cout << endl;
std::cout << "Sum of numbers entered is: " << sum << '\n';
std::cout << "Average of numbers entered is: " << average <<'\n';
std::cout << "The Highest number entered was: " << max <<'\n';
std::cout << "The Lowest number entered was: " << min <<'\n';
return 0;
}
Made a temporary fix :3
double min = 99999999999999999999999999999999999999999999999;
I'm very new to this.
Updated
After reading more comments I saw I was missing <cfloat>. Using #include <cfloat> NOW everyone's suggestions above work. However, <cfloat> was not covered in class, at all. So I'm not sure if that is usable here?
#include <iostream>
#include <cfloat>
using namespace std;
int main()
{
int numberitems;
double number, sum = 0, average;
double max = 0;
double min = DBL_MAX;
cout << "Enter number of items: \n";
cin >> numberitems;
//Make sure user can not enter negatives
if ( numberitems < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number >= max) {
max = number;
}
//minimum value entered
if (number <= min) {
min = number;
}
//Make sure user can not enter negatives
if ( number < 0 ) {
std::cout << "I said not to enter a negative number...'\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Sum of all the numbers
sum = sum + number;
//Average of all the numbers
average = sum / numberitems;
}
//Print the results
// some cosmetic...
std::cout << endl;
std::cout << endl;
std::cout << "\n=================REPORT====================\n";
std::cout << '\n';
std::cout << "\tYour Totals\tValues\n";
std::cout << "\t-----------\t------\n";
std::cout << "\t Sum: " << sum << '\n';
std::cout << "\t Average: " << average <<'\n';
std::cout << "\t Highest: " << max <<'\n';
std::cout << "\t Lowest: " << min <<'\n';
return 0;
}
Again, <cfloat> works fine, but I'm not sure if I'm allowed to use it. What other ways around this are there?
The question already got good answers - shortly: min and max are uninitialized.
However
Above is very specific.
Of course it helps in this specific case but I feel a broader advise that would work here and in many other cases is needed.
Add printouts
Adding debug printouts to your code ("debugging without a debugger") is always helpful in such cases.
For example adding the following in your example may help:
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number > max) {
// debug - (remove before submission)
std::cout << "number is the new max! number = " << number
<< ", max = " << max << std::endl;
// end of debug
max = number;
}
//minimum value entered
if (number < min) {
// (debug - remove before submission)
std::cout << "number is the new min! number = " << number
<< ", min = " << min << std::endl;
// end of debug
min = number;
}
When calculating minimum and maximum, you should initialize your variables to a default value. For minimum, it's the maximal possible value; for maximum - the minimal possible one.
double max, min; // BUG - not initialized
#include <float.h> // or <cfloat>
...
double max = 0; // CORRECT - initialized
double min = DBL_MAX; // CORRECT - initialized
For maximum, the initialization is usually -DBL_MAX (note: not DBL_MIN), but 0 is good enough in this case, when no negative values exist.
You need to set an initial value for min and max. For min, I'd suggest using an initial value of DBL_MAX, which is defined in the header cfloat.

Wrong results for fibonacci-test (C++)

I started to learn C++ and my homework is to write a code where you can enter 5 numbers and the program will tell you for each number whether it is a Fibonacci number or not.
I also tried using a do/while-loop in the isFibonacci function instead of the for-loop, but that did not fix the problem.
#include <iostream>
#include <cstdio>
using namespace std;
//function to test whether a number is a Fibonacci number or not
bool isFibonacci (int i)
{
//special cases with 0 and 1:
if ( i == 0 || i ==1) {
return true;
}
//for all other numbers:
int Fib1;
int Fib2;
int Fib3;
for (Fib3=0; Fib3>=i; Fib3++) {
Fib3 = Fib1 + Fib2;
Fib1 = Fib2;
Fib2 = Fib3;
if (Fib3==i){
return true;
}
else {
return false;
}
}
}
int main ()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
cout << "Please enter 5 numbers;" << endl;
cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i=0; i<5; i++) {
result=isFibonacci (numbers[i]);
if (result == true) {
cout << "Your number " << numbers[i] << " is a Fibonacci number!" << endl;
}
else {
cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << endl;
}
}
return 0;
}
The first Fibonacci numbers are (0),1,1,2,3,5,8,12.
So when I enter 5 numbers, for example 1,2,3,4,5 I should get a "yes" for 1,2,3 and 5, but a "no" for 4.
However, my program claims that except for 1, none of these numbers are Fibonacci numbers.
Basically your approach was a good idea. But you made some implementation errors in your check function. Like not initialized variables and wrong calculations. And look at you for loop.
Additionally. There will be a problem with big numbers.
Many very smart people, explored the Fibonacci numbers. There are whole books available. Also a Wikipedia article. See here.
Or look into that book:
The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
Or also here on stackoverflow
Therefore I will not reinvent the wheel. Here is your revised software:
#include <iostream>
#include <cmath>
#include <numeric>
// Positive integer ? is a Fibonacci number
// If and only if one of 5?2 + 4 and 5?2 - 4 is a perfect square
// from The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
// Function to test whether a number is a Fibonacci number or not
bool isFibonacci(int w)
{
{
double x1 = 5 * std::pow(w, 2) + 4;
double x2 = 5 * std::pow(w, 2) - 4;
long x1_sqrt = static_cast<long>(std::sqrt(x1));
long x2_sqrt = static_cast<long>(std::sqrt(x2));
return (x1_sqrt * x1_sqrt == x1) || (x2_sqrt * x2_sqrt == x2);
}
}
int main()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
std::cout << "Please enter 5 numbers;" << std::endl;
std::cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i = 0; i < 5; i++) {
result = isFibonacci(numbers[i]);
if (result == true) {
std::cout << "Your number " << numbers[i] << " is a Fibonacci number!" << std::endl;
}
else {
std::cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << std::endl;
}
}
return 0;
}

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 )
{
// ...
}