Why is my function not working properly - c++

My function that checks if numbers in the vector are even or odd doesn't work properly.
This function prints the numbers that i have typed in the vector and puts them in 2 categories EVENS/ODDS. But if i have a negative number there is a problem with the odds not printing it but evens work.
problematic code is here:
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1) // Here is the problem.
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}
Or more exactly this line: if (new_v1.at(i) % 2 == 1)
It prints the numbers that are odd but only the positive ones not the negative ones.
But if i change it to if (new_v1.at(i) % 2 != 0) then it works correctly.
Why does that happen and is there a problem with the equal operator?
If yes then why are the evens getting printed even if they are negatives while still using the equal operator?
Code here for reference.
clude <iostream>
#include <vector>
using namespace std;
void fillVector(vector <int>&);
void printVector(const vector <int>&);
void printEvensAndOddsVector(const vector <int>&); // Prints Evens and Odds.
int main()
{
vector <int> v1;
fillVector(v1);
printVector(v1);
printEvensAndOddsVector(v1);
cout << "\n\n\n";
system( "pause");
return 0;
}
// Function Definitions
void fillVector(vector <int>& new_v1)
{
int number;
cout << "Type in numbers and type -100 to stop: ";
cin >> number;
while (number != -100)
{
new_v1.push_back(number);
cin >> number;
}
}
void printVector(const vector <int>& new_v1)
{
cout << "\nVector: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
cout << new_v1.at(i) << " ";
}
cout << " \n";
}
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}

This line: if (new_v1.at(i) % 2 == 1). It prints the numbers that are odd but only the positive ones not the negative ones.
For negative n, n % 2 returns either 0 or -1 in C++. It never returns 1, so the condition cannot be true for negative inputs.
As you've discovered, comparing to zero would work.
See Modulo operator with negative values

Related

why isn't my vector pushbacking even and odd numbers

i tried to separate even and odd numbers using vectors from a array ==>
so i made a function that returns true is number is even and false for if number is odd
then i used an if else statement where if the function returns true then it pushbacks the value in a vector and if the function returns false then it pushbacks the value in another vector , finally i printed all the elements in the vector but the output does not show any element except it shows one in the odd vector.
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
int i=0 ;
if(sort(arr , i)){
even.push_back(arr[i]);
sort(arr , i+1);
}else{
odd.push_back(arr[i]);
sort(arr,i+1);
}
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
As #TonyDelroy said, you have to make for loop around call to sort(arr, i). Also first loop should go up to i <= n instead of i < n.
Your fixed working code below (see also std::partition_copy variant afterwards):
Try it online!
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
for (int i = 0; i < n; ++i)
if (sort(arr, i))
even.push_back(arr[i]);
else
odd.push_back(arr[i]);
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
As #chris said you can also use std::partition_copy to implement your algorithm:
Try it online!
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
int n = 0;
std::cin >> n;
std::vector<int> arr(n), odd, even;
for (int i = 1; i <= n; ++i)
arr[i - 1] = i;
std::partition_copy(arr.cbegin(), arr.cend(),
std::back_insert_iterator(odd), std::back_insert_iterator(even),
[](auto const & x){ return (x & 1) == 1; });
std::cout << "the even numbers are : " << std::endl;
for (auto element: even)
std::cout << element << " ";
std::cout << std::endl << "the odd numbers are : " << std::endl;
for (auto element: odd)
std::cout << element << " ";
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
You only push one element - the first.
Your partitioning code is equivalent to
if(sort(arr , 0)){
even.push_back(arr[0]);
sort(arr , 1);
}else{
odd.push_back(arr[0]);
sort(arr,1);
}
You need to loop over all the input numbers.
You can also simplify matters with a more generally useful evenness function that doesn't depend on an array:
bool is_even(int x) { return x % 2 == 0; }
and then there is no need to store all the inputs before processing them:
int main(){
vector <int> even , odd;
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (is_even(x)) {
even.push_back(x);
}
else {
odd.push_back(x);
}
}
cout << "the even numbers are : " << endl;
for (auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for (auto element:odd){
cout << element << " ";
}
}

Why is the while loop for input validation either skipping the loop entirely or not accounting for wrong inputs?

The loop is not reacting properly when an input outside the parameters is put in. It should only accept 0-9, but I can put any number positive or negative in and it outputs it as is.
I've tried setting the int count to null and 0 on the 4th line, thinking null might allow the while loop which originally said 'while count < 0 or count > 9'. Even at null it skipped the whole loop entirely and didn't allow for any inputs. I set it this way thinking it would loop through as the count is set to 0, but it seems to skip the conditions inside. This is a small function inside a larger lottery program.
void human(int user[], int size) {
const int SIZEOF = 5;
cout << "Enter your 5 lottery number picks.\n";
int count = 0;
while (count == 0) {
if (count >= 0 and count <= 9)
for (count = 0; count < SIZEOF; count++)
{
cout << "Number " << (count + 1) << ": ";
cin >> user[count];
}
else
{
cout << "You must enter 0-9: ";
cin >> user[count];
}
}
}
//EDIT: Here is the code I used based on it being pointed out I was using the //counter
void human(int user[], int size) {
const int SIZEOF = 5;
cout << "Enter your 5 lottery number picks.\n";
for (int count = 0; count < SIZEOF; count++)
{
cout << "Number " << (count + 1) << ": ";
cin >> user[count];
while (user[count] < 0 || user[count] > 9)
{
cout << "You must enter a number between 0 and 9: ";
cin >> user[count];
}
}
}
problems:
your function is missing an output/return value
your outer loop makes no sense
you check count instead of input
you read into a (potentially) out of bounds array
solutions:
use std::vector instead of array
think about input and output of your function
fix input and loops
example:
#include <iostream>
#include <string>
#include <vector>
std::vector<int> lotteryInput(uint32_t count)
{
std::vector<int> numbersPicked;
std::cout << "Enter your " << count << "lottery number picks.\n";
while(numbersPicked.size() < count)
{
int pick;
std::cout << "Number " << numbersPicked.size()+1 << ": ";
std::cin >> pick;
if ((pick >= 0) && (pick <= 9))
{
numbersPicked.push_back(pick);
}
else
{
std::cout << "You must enter 0-9: \n";
}
}
return numbersPicked;
}
int main()
{
auto numbersChosen = lotteryInput(5);
std::cout << "picked numbers: ";
for(const auto& num : numbersChosen)
{
std::cout << num << ", ";
}
}

Converting String to vector of Integers

FizzBuzz program. The user enters numbers separated by a comma. The program reads input and lets the computer know if divisible by 3, 5 or both. When the user enters 15,5,30, the program will only output the first number, 15 and stops there. What am I doing wrong?
void processVector(vector<int> intVector)
{
bool loop;
for (int i = 0; i < intVector.size(); i++)
{
loop = true;
}
}
int main()
{
cout << "Welcome to the FizzBuzz program!" << endl;
cout << "This program will check if the number you enter is divisable by
3, 5, or both." << endl;
cout << "Please enter an array of numbers separated by a comma like so,
5,10,15" << endl;
cin >> userArray;
vector<int> loadVector(string inputString);
istringstream iss(userArray);
vector <int> v;
int i;
while (iss >> i);
{
v.push_back(i);
if (iss.peek() == ',')
iss.ignore();
if (i % 15 == 0)
{
cout << "Number " << i << " - FizzBuzz!" << endl;
}
else if (i % 3 == 0)
{
cout << "Number " << i << " Fizz!" << endl;
}
else if (i % 5 == 0)
{
cout << "Number " << i << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
system("pause");
}
Here is how I would approach the problem:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::cout << "!!!Hello World!!!" << std::endl; // prints !!!Hello World!!!
std::cout << "Please enter your numbers seperated by a comma (5, 3, 5, 98, 278, 42): ";
std::string userString;
std::getline(std::cin, userString);
std::vector<int> numberV;
size_t j = 0; // beginning of number
for(size_t i = 0; i < userString.size(); i++){
if((userString[i] == ',') || (i == userString.size() -1)){ // could also use strncmp
numberV.push_back(std::stoi(userString.substr(j, i))); // stoi stands for string to int, and .substr(start, end) creates a new string at the start location and ending at the end location
j = i + 1;
}
}
for(size_t n = 0; n < numberV.size(); n++){
std::cout << numberV[n] << std::endl;
}
return(0);
}
This should give you a method to solve the problem (without handling the fizzbuzz part of your program) that I personally find simpler.
The basic form for using functions is:
<return type> <function_name(<inputs)>{
stuff
};
So, a basic function that takes a string and returns a vector (what you are wanting) would be:
std::vector myStringToVector(std::string inputString){
std::vector V;
// your code (see the prior example for one method of doing this)
return(V);
};
It also looks like they want a separate function for outputting your vector values, this could look something like:
void myVectorPrint(std::vector inputVector){
// your code (see prior example for a method of printing out a vector)
};
Thank you #Aaron for the help. Here is the finished code and it works great!
I had to take a little more time researching a few things and trying to understand which order and what to put where in terms of the functions and how to call them. I appreciate all the help as I said I am a noob.
#include "stdafx.h"
#include <iostream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;
vector<int> loadVector(string inputString)
{
stringstream ss(inputString);
vector <int> numberV;
int n;
size_t j = 0; // beginning of number
for (size_t n = 0; n < inputString.size(); n++)
{
if ((inputString[n] == ',') || (n == inputString.size() - 1))
{
numberV.push_back(std::stoi(inputString.substr(j, n)));
j = n + 1;
}
}
return numberV;
}
void processVector(vector<int> intVector)
{
for (int i = 0; i < intVector.size(); i++)
{
int n = intVector.at(i);
if (n % 15 == 0)
{
cout << "Number " << n << " - FizzBuzz!" << endl;
}
else if (n % 3 == 0)
{
cout << "Number " << n << " Fizz!" << endl;
}
else if (n % 5 == 0)
{
cout << "Number " << n << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
}
int main()
{
cout << "Welcome to the FizzBuzz program." << endl
<< "Please enter an array of numbers separated by comma's (5, 10, 15)"
<< endl;
string inputString;
getline(cin, inputString);
try
{
vector<int> intVector = loadVector(inputString);
processVector(intVector);
}
catch (const exception& e)
{
cout << "Exception caught: '" << e.what() << "'!;" << endl;
}
system("pause");
return 0;
}

C++ : Count even / odd numbers in a range

My program has to count how many numbers in a range are even and how many of them are odd but I can't seem to figure it out.It kinda works
but when I put numbers in it spouts out nonsense. I'm an extreme nooob when it comes to programing, I think that the problem has to be at line 21 for (i=n; i<=m; i++) { ?
But I'm not sure. I have a programing book but it does not help much,maybe someone can help?
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i;
}
else {
b=b+i;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
Assuming you mean even and odd numbers your problem lies in this code:
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i; // increase number of even numbers by i
}
else {
b=b+i; // increase number of odd numbers by i
}
}
What you might want do to do is add 1 (instead of whatever i is):
for (i = n; i <= m; ++i) {
if (i % 2 == 0)
++a; // increase number of even numbers by one
else
++b; // increase number of odd numbers by one
}
Also I'd suggest using better variable names, for example even and odd instead of a and b and so on. It makes code easier to understand for everybody, even for you.
Just a little more tips. Assigning variables as soon as you declare them is good practice:
int m = 0;
You can declare variable inside of for loop, and in your case there is no need to declare it out of it:
for (int i = n; i <= m; ++i) { ... }
Example how it can change look and clarity of your code:
#include <iostream>
using namespace std;
int main() {
int from = 0,
to = 0,
even = 0,
odd = 0;
cout << "Enter a number that begins interval: ";
cin >> from;
cout << "Enter a number that ends interval: ";
cin >> to;
for (int i = from; i <= to; ++i) {
if (i % 2 == 0)
++even;
else
++odd;
}
cout << " even numbers: " << even << endl;
cout << " odd numbers: " << odd << endl;
return 0; // don't forget this! main is function returning int so it should return something
}
Ok, so as per the new clarification the following should work
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a++;
}else {
b++;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
So the following changes were done:
The for loop was closed
a = a + i or b = b + i was wrong as you are adding the counter value to the count which should be a++ or b++. Changed that also
The last two lines where you are showing your result was out of the main method, brought them inside the main method
Hope you find this useful.
You don't need to use loop to count even and odd numbers in a range.
#include <iostream>
int main ()
{
int n,m,even,count;
std::cin >> n >> m;
count=m-n+1;
even=(count>>1)+(count&1 && !(n&1));
std::cout << "Even numbers: " << even << std::endl;
std::cout << "Odd numbers: " << count-even << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
int n, i;
cin >> n;
cout << " even : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 == 0)
cout << i << " ";
}
cout << " odd : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 != 0)
cout << i << " ";
}
return 0;
}
//input n = 5
// output is even : 2 4 6 8 10
// odd : 1 3 5 7 9
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a = 0;
b = 0;
for (i = n; i < = m; i++) {
if (i%2 == 0){
a = a + 1;
} else {
b = b + 1;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
Not sure why you are looping through all the elements (half of them are going to be even and the other half odd). The only case where you have to consider when the interval length is not divisible by two.
using namespace std;
int main()
{
int n;
int m;
int x;
int odds;
int evens;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
cout << n << " " << m << endl;
x = m - n + 1;
odds = x / 2;
evens = odds;
if (x % 2 != 0) {
if (n % 2 == 0) {
evens++;
} else {
odds++;
}
}
cout << " even numbers: " << evens << endl;
cout << " odd numbers: " << odds << endl;
}
This is a more readable version of #Lassie's answer

Greedy Algorithm for coin change c++

So, I'm creating a coin change algorithm that take a Value N and any number of denomination and if it doesn't have a 1, i have to include 1 automatically. I already did this, but there is a flaw now i have 2 matrix and i need to use 1 of them. Is it possible to rewrite S[i] matrix and still increase the size of array.... Also how can i find the max denomination and the second highest and sooo on till the smallest? Should i just sort it out in an highest to lowest to make it easier or is there a simpler way to look for them one after another?
int main()
{
int N,coin;
bool hasOne;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter number of different coins: " << endl;
cin >> coin;
int *S = new int[coin];
cout << "Enter the denominations to use with a space after it" << endl;
cout << "(1 will be added if necessary): " << endl;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] == 1)
{
hasOne = true;
}
cout << S[i] << " ";
}
cout << endl;
if(!hasOne)
{
int *newS = new int[coin];
for(int i = 0; i < coin; i++)
{
newS[i] = S[i];
newS[coin-1] = 1;
cout << newS[i] << " ";
}
cout << endl;
cout << "1 has been included" << endl;
}
//system("PAUSE");
return 0;
}
You could implement it with std::vector, then you only need to use push_back.
std::sort can be used to sort the denominations into descending order, then it's just a matter of checking whether the last is 1 and adding it if it was missing. (There is a lot of error checking missing in this code, for instance, you should probably check that no denomination is >= 0, since you are using signed integers).
#include <iostream> // for std::cout/std::cin
#include <vector> // for std::vector
#include <algorithm> // for std::sort
int main()
{
std::cout << "Enter the value N to produce:\n";
int N;
std::cin >> N;
std::cout << "Enter the number of different denominations:\n";
size_t denomCount;
std::cin >> denomCount;
std::vector<int> denominations(denomCount);
for (size_t i = 0; i < denomCount; ++i) {
std::cout << "Enter denomination #" << (i + 1) << ":\n";
std::cin >> denominations[i];
}
// sort into descending order.
std::sort(denominations.begin(), denominations.end(),
[](int lhs, int rhs) { return lhs > rhs; });
// if the lowest denom isn't 1... add 1.
if (denominations.back() != 1)
denominations.push_back(1);
for (int coin: denominations) {
int numCoins = N / coin;
N %= coin;
if (numCoins > 0)
std::cout << numCoins << " x " << coin << '\n';
}
return 0;
}
Live demo: http://ideone.com/h2SIHs