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 << " ";
}
}
Related
C++ This is my code in C++ for finding the largest number in array. When I was running in my IDE then there was no compilation error but it was not giving me output. I think the problem is in the declaration of array at line 8. I replaced the array declaration from line 8 to line 11 then it is working fine in my IDE. So I didn't get it that why the declaration of array was not working at line 8?
#include <bits/stdc++.h>
using namespace std;
int largest_in_array(int a[], int n);
int main() // main function
{
int n; // User will enter the size of array
int arr[n]; // Line 8
cout << "Enter the size of array: " << endl;
cin >> n;
// Line 11
cout << "\nEnter the elements of array: " << endl;
for (int i = 0; i < n; i++) // This loop will run for each element of array that user wants to enter
{
cout << "Enter the " << (i + 1) << " element:";
cin >> arr[i];
cout << endl;
}
cout << "Elements are: [";
for (int i = 0; i < n; i++) // Prints the elements of array
{
// cout << "Enter the " << (i + 1) << " element:";
cout << arr[i] << " ";
// cout << endl;
}
cout << "]";
int res = largest_in_array(arr, n); //Function call
cout << "\nLargest element in array is: " << arr[res] << endl;
return 0;
}
int largest_in_array(int a[], int n) // function that will return the index of largest element in array
{
int max = 0;
for (int i = 1; i < n; i++)
{
if (a[max] < a[i])
{
max = i;
}
}
return max;
}
You declare int arr[n]; before the user has entered a value into n. n has an indeterminate value when you read it and create arr.
You don't check that the user enters a positive value into n. Zero and negative sized arrays are not valid.
Other points:
bits/stdc++.h is not a standard header which makes your program not portable. Use the proper header files, like iostream etc.
arr[n] is a Variable Length Array (VLA) which is not part of standard C++. Make it a std::vector<int> arr(n); instead.
The use of std::endl is unnessesary. There is no need to flush the output streams here. Use \n instead.
Example:
#include <iostream>
#include <limits>
#include <vector>
int largest_in_array(const std::vector<int>& a) {
int max = 0;
for(int i = 1; i < a.size(); i++) {
if(a[max] < a[i]) {
max = i;
}
}
return max;
}
int main() // main function
{
int n; // User will enter the size of array
std::cout << "Enter the size of array:\n";
// check that input succeeds and that the value is valid
if(!(std::cin >> n) || n < 1) return 1;
std::vector<int> arr(n);
std::cout << "\nEnter the elements of array:\n";
for(int i = 0; i < n; i++)
{
std::cout << "Enter the " << (i + 1) << " element:";
if(!(std::cin >> arr[i])) {
std::cout << "invalid input, bye bye\n";
return 1;
}
}
std::cout << "Elements are: [";
for(int i = 0; i < n; i++)
{
std::cout << arr[i] << " ";
}
std::cout << "]";
int res = largest_in_array(arr); // Function call
std::cout << "\nLargest element in array is: " << arr[res] << '\n';
}
That said, you could however use the standard algorithm std::max_element instead of writing your own. It returns an iterator to the maximum element.
You could also make use of range-based for loop when you don't need to know the index in the array, as in your second loop.
Example:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
int main() {
int n; // User will enter the size of array
std::cout << "Enter the size of array:\n";
if(!(std::cin >> n) || n < 1) return 1;
std::vector<int> arr(n);
std::cout << "\nEnter the elements of array:\n";
for(int i = 0; i < n; i++) // This loop will run for each element of
// array that user wants to enter
{
std::cout << "Enter the " << (i + 1) << " element:";
if(!(std::cin >> arr[i])) {
std::cout << "invalid input, bye bye\n";
return 1;
}
}
std::cout << "Elements are: [";
for(auto value : arr) { // a range-based for loop
std::cout << value << ' ';
}
std::cout << "]\n";
auto res = std::max_element(arr.begin(), arr.end());
std::cout << "Largest element in array is: " << *res << '\n';
std::size_t index = std::distance(arr.begin(), res);
std::cout << "which has index " << index << '\n';
}
When you have int n on line 8 it is initialized when you use it to create the array. When n is initialized explicitly, it's value is undefined behavior. You may be creating an array larger than the n you inputted on line 10, resulting in the array having extra random junk, it may be smaller meaning your program read memory it really shouldn't, etc.
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
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
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
I have created a function to count the duplicate items in array .
And everything is fine . but I want to output the unique items only , and this is my problem .
My function:
void RepeatedCounter(int n){
int i, j, temp, count= 0;
int *Numbers = new int[n];
for(i=0;i<n;i++){
cout << "Enter the number (" << i+1 << "): ";
cin >> *(Numbers+i);
}
cout << "---------------------\n";
for(i=0;i<n;i++){
temp = *(Numbers+i);
for(j=0;j<n;j++){
if(temp == *(Numbers+j)){
++count;
}
}
if(*(Numbers+i+1) != temp)
cout << *(Numbers+i) << "= " << count << endl;
count= 0;
}
delete []Numbers;
}
Main function:
int Num_Of_Digits= 0;
cout << "How many numbers: ";
cin >> Num_Of_Digits;
RepeatedCounter(Num_Of_Digits);
Example:
Inputs
1
5
3
5
1
Wrong result (current output)
1= 2
5= 2
3= 1
5= 2
1= 2
What I want
1= 2
5= 2
3= 1
First of: read the user data into a proper dynamic container like a vector:
std::vector<int> v;
v.reserve(100);
while (true)
{
int n;
std::cout << "Enter the number: ";
if (!(std::cin >> n)) { break; }
v.push_back(n);
}
Second, make a histogram using a map:
std::map<int, unsigned int> histogram;
for (int i : v) { ++histogram[i]; }
Now output the count:
for (auto const & p : histogram)
{
std::cout << "The number " << p->first
<< " appears " << p->second << " times.\n";
}
This has been done for you.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
int repeated_counter(int n){
std::vector<int> vec;
std::vector<int> uniques;
int t;
for(int i=0; i!=n; ++i)
{
std::cin >> t;
vec.push_back(t);
}
std::sort(vec.begin(), vec.end());
std::unique_copy(vec.begin(), vec.end(),
std::back_inserter(uniques));
for(std::vector<int>::iterator it=uniques.begin();
it!=uniques.end();
++it)
{
std::cout << *it << "="
<< std::count(vec.begin(), vec.end(), *it) << "\n";
}
return 0;
}
please refrain from newing memory like you have done it is worse in every way to using a vector.
http://www.sgi.com/tech/stl/unique_copy.html
http://en.cppreference.com/w/cpp/container/vector
Try this,
for(i=0;i<n;i++){
count= 0;
temp = *(Numbers+i);
bool found = false;
for(j=0;j<n;j++){
if(temp == *(Numbers+j)){
++count;
}
}
for(j=i+1;j<n;j++) {
if(temp == *(Numbers+j)){
found = true;
}
}
if(found) continue;
if(*(Numbers+i+1) != temp)
cout << *(Numbers+i) << "= " << count << endl;
}
The problem is you are only checking against the next number in the list.
if(*(Numbers+i+1) != temp)
cout << *(Numbers+i) << "= " << count << endl;
What you should do is loop over the front on the list (until you get to the number you're on) and check to see if any of those numbers are the same as your current number and only print out if they aren't. You could also check the number before you started the count and not do it if the number has been done already.