An issue with an output of a code in C++ - c++

I have a problem with my code.
my code is:
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int min(int A[], int s)
{
int x = A[0];
for (int i = 0; i<s; i++)
if (A[i]<x)
x = A[i];
return x;
}
int max(int A[], int s)
{
int x = A[0];
for (int i = 0; i<s; i++)
if (A[i]>x)
x = A[i];
return x;
}
int main()
{
int Array[10] = { 15,20,8,0,17,14,2,12,10,5 };
while (1)
{
string UserInput;
cin >> UserInput;
if (UserInput == "Minimun")
{
int Minimum = min(Array, 10);
}
if (UserInput == "Maximum")
{
int Maximum = max(Array, 10);
}
if (UserInput == "Dropped ones")
{
int count = min(Array, 10) + 1;
for (int i = min(Array, 10); i<max(Array, 10) - 1; i++)
cout << count++ << "\n";
}
}
return 0;
}
it has no error, but it doesn't work as I want.
If I have an array: int Array[10]= {15,20,8,0,17,14,2,12,10,5};
And I found the max and min value in this array. I want to make a counter which print the values from 0 to 20, except the values in the array.
It means that the output should be:
1
3
4
6
7
9
11
13
15
16
18
19
Why my code doesn't print this output?
Please help me, I don't know where is the wrong sentence in this code.
Thanks in advance.
Another try but give an error with "cbegin" and "cend":
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int Array[] = { 15, 20, 8, 0, 17, 14, 2, 12, 10, 5 };
auto Minimum = *min_element( cbegin( Array ), cend( Array ) );
auto Maximum = *max_element( cbegin( Array ), cend( Array ) );
cout << "Min: " << Minimum << '\n';
cout << "Max: " << Maximum << '\n';
for( auto i = 1; i <= 20; ++i ) {
if( find( cbegin( Array ), cend( Array ), i ) == cend( Array ) ) {
cout << i << "\n";
}
}
return 0;
}

If I understand your post correctly. As per your request I changed the code from using vectors to using c arrays. I took out the user input stuff to give you a smaller sample to look at.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int Array[] = { 15, 20, 8, 0, 17, 14, 2, 12, 10, 5 };
// part of the xutility header
// better to use cbegin( Array );
auto begin = &Array[ 0 ];
// better to use cend( Array );
auto end = begin + sizeof( Array ) / sizeof( Array[ 0 ] );
auto Minimum = *min_element( begin, end );
auto Maximum = *max_element( begin, end );
cout << "Min: " << Minimum << '\n';
cout << "Max: " << Maximum << '\n';
for( auto i = 1; i <= 20; ++i ) {
if( find( begin, end, i ) == end ) {
cout << i << "\n";
}
}
return 0;
}

It doesn't work because your cin gets only the first word "Dropped" instead of "Dropped ones". Seems to work just fine if you make it 1 word: http://ideone.com/AjtOc7.
If you want multiple words use getline
std::string UserInput;
std::getline (std::cin, UserInput);
Also, consider using STL library like the ones mentioned in the answers.

Related

How to remove duplicate elements from a c++ Bidimensional array

When creating and duplicating the matrix, it writes it the way I want, my question is how can I eliminate the duplicate elements of matrix1 because I need it to only show me the values of the matrix without showing the duplicates. It would be more or less as follows.
enter number of rows: 3.
enter number of columns: 4.
Original Array:.
3 7 14 2.
6 2 3 15.
10 8 11 6.
Result Array:
3.
7.
14.
2.
6.
15.
10.
8.
11.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int f = 0;
int c = 0;
cout<<"Ingresar numero de filas: ";
cin>>f;
cout<<"Ingresar numero de columnas: ";
cin>>c;
int matriz[f][c];
int matriz1[f][c];
srand(time(0));
for (int i = 0 ; i < f; i++ )
for (int j = 0 ; j < c ; j++ )
matriz[i][j] = 1 + rand()% 15;
cout<< "Arreglo Original"<< endl;
for (int i = 0 ; i < f; i++ ){
for (int j = 0 ; j < c ; j++ ){
cout<<matriz[i][j]<<" "; }
cout<< endl;
}
cout<< "Arreglo resultante "<<endl;
for (int i = 0 ; i < f; i++ ){
for (int j = 0 ; j < c ; j++ ){
matriz1[i][j] = matriz[i][j];
cout<< matriz1[i][j]<<endl;}
}
return 0;
}
Here you are:
#include <vector>
#include <memory>
#include <bitset>
#include <algorithm>
#include <iterator>
#include <iostream>
int main() {
std::vector<std::vector<int>> example{
{ 3, 7, 14, 2 },
{ 6, 2, 3, 15 },
{ 10, 8, 11, 6 }
};
int const max = 15; // while reading example find out max
auto is_avail = std::make_unique<std::bitset<max + 1>>();
std::vector<int> ans;
for (auto const& v : example) {
for (auto const e : v) {
if (!is_avail->test(e)) {
ans.emplace_back(e);
is_avail->set(e, true);
}
}
}
std::copy(ans.cbegin(), ans.cend(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
In case you want ans to be 2D too replace the code following the line
auto is_avail = std::make_unique<std::bitset<max + 1>>();
with
std::vector<std::vector<int>> ans{ example };
for (auto& v : ans) {
for (auto& e : v) {
if (!is_avail->test(e)) {
is_avail->set(e, true);
}
else {
e = -1; // error state
}
}
}
for (auto const& v : ans) {
for (auto const e : v) {
if (e != -1) {
std::cout << std::setw(2) << e;
}
else {
std::cout << std::setw(2) << ' ';
}
std::cout << '\t';
}
std::cout << '\n';
}
and don't forget to
#include <iomanip>
for std::setw.

Program to find sum of elements in a given array

I have to find the elements in a given array, and I found a program in other site, but when I try to interpret the code in my way, I have error.
That is from the other site:
#include <iostream>
using namespace std;
// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
int sum = 0; // initialize sum
// Iterate through all elements
// and add them to sum
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
int main()
{
int arr[] = { 12, 3, 4, 15 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Sum of given array is " << sum(arr, n);
return 0;
}
That's mine:
#include <iostream>
using namespace std;
int Function(int arr[], int Broi)
{
int suma = 0;
for (int i = 0; i < Broi; i++) {
cin >> arr[Broi];
suma += arr[i];
}
return suma;
}
int main()
{
int arr;
int Broi = sizeof(arr) / sizeof(arr[0]);
cout << "Srednoto Aritmetichno e: " << Function(arr[], broi);
return 0;
}
Also the first programe gives the numbers of the array, but I want the user to cin>> them when u write the length of the arr.
Your code is not declaring an array at all. It is declaring a single int.
You said in comments that:
The task is to read 10 numbers, and to put them in array
So, you should declare a 10-int array in main() and fill it with user values before passing it to Function(), similar to how the original code was doing. The user input doesn't really belong in Function() to begin with.
Try something more like this instead:
#include <iostream>
using namespace std;
int Function(int arr[], int Broi)
{
int suma = 0;
for (int i = 0; i < Broi; i++) {
suma += arr[i];
}
return suma;
}
int main()
{
int arr[10];
cout << "Enter 10 numbers: ";
for(int i = 0; i < 10; ++i){
cin >> arr[i];
}
cout << "The sum is: " << Function(arr, 10);
return 0;
}
The line arr[Broi] is accessing the array out of bounds, causing undefined behavor, because the array consists only of a single element. Even if it consisted of Broi elements, it would be accessing the array out of bounds, because valid indexes would be 0 to Broi - 1.
In the comments section (but not in the question), you stated that you are supposed to read 10 numbers from the user. If arr were pointing to an array of 10 elements instead of 1 element, then it would make sense to write arr[i] instead of arr[Broi].
The simplest solution to the problem would be to not use arrays at all:
#include <iostream>
constexpr int NUM_INPUTS = 10;
int main()
{
int input;
int sum = 0;
for ( int i = 0; i < NUM_INPUTS; i++ )
{
//prompt user for input
std::cout << "Please enter integer #" << i + 1 << ": ";
//attempt to read integer from user
if ( ! ( std::cin >> input ) )
{
std::cout << "Input failure!\n";
return 1;
}
//add user input to sum
sum += input;
}
//print sum
std::cout << "\nThe sum of all numbers is: " << sum << ".\n";
return 0;
}
However, since you stated in the comments section that you are supposed to use arrays, then you are probably supposed to first read all 10 numbers from std::cin into an array of 10 elements and then calculate the sum afterwards:
#include <iostream>
#include <cstdlib>
constexpr int NUM_INPUTS = 10;
void input_array( int arr[] )
{
for ( int i = 0; i < NUM_INPUTS; i++ )
{
//prompt user for input
std::cout << "Please enter integer #" << i + 1 << ": ";
//attempt to read integer from user
if ( ! ( std::cin >> arr[i] ) )
{
std::cout << "Input failure!\n";
std::exit( EXIT_FAILURE );
}
}
}
int calculate_sum( int arr[] )
{
int sum = 0;
for ( int i = 0; i < NUM_INPUTS; i++ )
{
sum += arr[i];
}
return sum;
}
int main()
{
int arr[NUM_INPUTS];
//fill array with user input
input_array( arr );
//print sum
std::cout << "\nThe sum of all numbers is: " << calculate_sum( arr ) << ".\n";
return 0;
}
Both programs have the following output:
Please enter integer #1: 20
Please enter integer #2: 30
Please enter integer #3: 10
Please enter integer #4: 5
Please enter integer #5: 31
Please enter integer #6: 17
Please enter integer #7: 6
Please enter integer #8: 14
Please enter integer #9: 18
Please enter integer #10: 50
The sum of all numbers is: 201.
The simple fix without too many complicated features would be like below:
#include <iostream>
int Function( int* const array, const std::size_t elementCount)
{
int suma { };
for ( std::size_t idx = 0; idx < elementCount; ++idx )
{
std::cin >> array[ idx ];
suma += array[ idx ];
}
return suma;
}
int main( )
{
int myArray[ 4 ] { };
int suma = Function( myArray, sizeof( myArray ) / sizeof( *myArray ) );
std::cout << "Srednoto Aritmetichno e: " << suma << '\n';
return 0;
}
That's it. You can change the size of myArray to anything that fits onto stack memory.

How to solve the problem that program works in the same way in case of negative numbers? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
As a result, the program must display the 3 largest elements of the sequence. Elements must be displayed from small to large and not using array...
Examples
Input:
3 1 2 3
Work result:
1 2 3
Input:
5 2 -4 16 0 15
Work result:
2 15 16
Input:
3 0 -1 -2
Work result:
-2 -1 0
Here is my code:
#include <iostream>
int main() {
int n;
std::cin >> n;
int number;
std::cin >> number;
int max1, max2, max3;
max1 = max2 = max3 = number;
for (int i = 1; i < n; i++) {
std::cin >> number;
if (number > max3) {
if (number > max2) {
if (number > max1) {
max3 = max2;
max2 = max1;
max1 = number;
} else {
max2 = number;
}
} else {
max3 = number;
}
}
}
std::cout << max3 << " " << max2 << " " << max1;
}
I'd use standard algorithms to keep it as simple as possible.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<std::vector<int>> tests{
{5, 2, -4, 16, 0, 15},
{3, 0, -1, -2}
};
for(auto& test : tests) {
// sort the vector to get the three largest last
std::sort(test.begin(), test.end());
// create an iterator 3 steps back from the end
// (or less if the vector doesn't have 3 elements)
auto first = std::prev(test.cend(), std::min(test.size(), static_cast<size_t>(3)));
// copy to std::cout
std::copy(first, test.cend(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
}
}
Output:
5 15 16
-1 0 3
A slightly more complicated way involves partially sorting the vector. This makes it more effective since you only need 3 elements sorted.
std::partial_sort puts the smallest elements first so we need to sort it in decending order (using std::greater<>).
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<std::vector<int>> tests{
{5, 2, -4, 16, 0, 15},
{3, 0, -1, -2}
};
for(auto& test : tests) {
// calculate how many elements to show, 0-3
auto elems = std::min(test.size(), static_cast<size_t>(3));
// sort "elems" elements in decending order
std::partial_sort(
test.begin(),
std::next(test.begin(), elems),
test.end(),
std::greater<>()
);
// copy the result to std::out, in reverse order since they are sorted "backwards"
std::copy(
std::prev(test.crend(), elems),
test.crend(),
std::ostream_iterator<int>(std::cout, " ")
);
std::cout << '\n';
}
}
My five cents.:)
#include <iostream>
#include <utility>
int main()
{
size_t n = 0;
int max1, max2, max3;
std::cin >> n;
size_t i = 0;
for ( int number; n-- && std::cin >> number; i = i < 3 ? i + 1 : i )
{
if ( i == 0 )
{
max3 = number;
}
else
{
if ( max3 < number )
{
std::swap( max3, number );
}
if ( i == 1 )
{
max2 = number;
}
else
{
if ( max2 < number )
{
std::swap( max2, number );
}
if ( i == 2 || max1 < number )
{
max1 = number;
}
}
}
}
if ( i > 0 )
{
std::cout << max3;
}
if ( i > 1 )
{
std::cout << ", " << max2;
}
if ( i > 2 )
{
std::cout << ", " << max1;
}
std::cout << '\n';
return 0;
}
If to enter
6
5 2 -4 16 0 15
then the output is
16, 15, 5
If to enter
6
-5 -2 4 -16 0 -15
then the output is
4, 0, -2
Or if to enter
4
3 0 -1 -2
then the program output is
3, 0, -1
Pay attention to that in general the user can enter less than 3 numbers.:)
The solution above allows duplicated maximum values.
If it is required that maximum values shall not be repeated then the program can look the following way.
#include <iostream>
#include <utility>
int main()
{
size_t n = 0;
int max1, max2, max3;
std::cin >> n;
size_t i = 0;
for ( int number; n-- && std::cin >> number; )
{
if ( i == 0 )
{
max3 = number;
i = 1;
}
else
{
if ( max3 < number )
{
std::swap( max3, number );
}
if ( number < max3 )
{
if ( i == 1 )
{
max2 = number;
i = 2;
}
else
{
if ( max2 < number )
{
std::swap( max2, number );
}
if ( number < max2 )
{
if ( i == 2 || max1 < number )
{
max1 = number;
i = 3;
}
}
}
}
}
}
if ( i > 0 )
{
std::cout << max3;
}
if ( i > 1 )
{
std::cout << ", " << max2;
}
if ( i > 2 )
{
std::cout << ", " << max1;
}
std::cout << '\n';
return 0;
}
For example if to enter
5
-1 -1 -1 -1 -1
where all numbers are equal each other then the output will contaoin onky one maximum number
-1
If to use standard containers then the standard container std::set is the most appropriate container.
For example
#include <iostream>
#include <set>
#include <iterator>
#include <algorithm>
int main()
{
size_t n = 0;
std::set<int> set;
std::cin >> n;
std::copy_n( std::istream_iterator<int>( std::cin ), n,
std::inserter( set, std::end( set ) ) );
size_t i = 3;
for ( auto it = std::rbegin( set ); i-- != 0 && it != std::rend( set ); ++it )
{
std::cout << *it << ' ';
}
std::cout << '\n';
return 0;
}
If to enter
6
5 2 -4 16 0 15
then the output is
16 15 5
int main () {
int n;
std::cin >> n;
int number;
std::cin >> number;
int max1, max2, max3;
max1 = max2 = max3 =number;
for(int i = 1; i < n; i++) {
std::cin >> number;
if (number > max3) {
if (number > max2) {
if (number > max1) {
max3 = max2;
max2 = max1;
max1 = number;
} else {
max3 = max2;
max2 = number;
}
} else {
max3 = number;
}
}
}
std::cout << max3 << " " << max2 << " " << max1;
}
If the number is greater than max2 but smaller than max1 then max2 is the new max3 and max2 is number, that was the mistake.
Do not write everything in main. Slice code to smaller pieces to make it easy to read.
Here is an example (a bit to fancy):
class AccumulateTopThree
{
public:
void update(int x)
{
if (!isUnique(x)) return;
keepInOrder(c, x);
keepInOrder(b, c);
keepInOrder(a, b);
}
void print(std::ostream& out)
{
// TODO: handle case when count of input nubers is less then 3
out << c << ' ' << b << ' ' << a << '\n';
}
private:
bool isUnique(int x) const
{
return a != x && b != x && c != x;
}
static void keepInOrder(int &a, int &b)
{
if (a < b) std::swap(a, b);
}
private:
int a = std::numeric_limits<int>::min();
int b = a;
int c = a;
};
https://wandbox.org/permlink/OFkQUaGI9PygAV6D

C++ multiple returns from single function

still pretty new to C++.
Had to write a function in class to count the number of each digit in a multi-dimensional array.
Now I didn't think you could return multiple int values from a single called function and then use all of these returns in a text based answer, so I attempted to return a different value depending on the value requested as parameter for each digit.
The code below is unnecessarily long and I'm still receiving the following errors.
main-1-3.cpp: In function 'int main()':
main-1-3.cpp:12:21: error: too few arguments to function 'int
count_numbers(int(*)[4], int)'
count_numbers(array);
^
main-1-3.cpp:7:12: note: declared here
extern int count_numbers(int array[4][4], int);
With a bit of debugging I could likely fix up these compile errors, but I feel like my method is extremely convoluted and was wondering if it were possible to call the function as:
count_number(array[4][4])
(Removing the need for the Q parameter) and then have count_numbersreturn all ten of the number values and the just output them as text like << ",3:" << three << instead of << ",8:" << count_numbers(array, 8) <<
Anyway, the function.cpp and main.cpp are below.
If anyone could point me in the right direction it would greatly appreciated. Just need to know the correct method so I can condense this code.
function.cpp
#include <iomanip>
#include <locale>
#include <sstream>
#include <string>
#include <iostream>
int count_numbers(int array[4][4], int Q)
{
int X=0;
int Y=0;
int zero=0;
int one=0;
int two=0;
int three=0;
int four=0;
int five=0;
int six=0;
int seven=0;
int eight=0;
int nine=0;
while(X<4)
{
if(array[X][Y]==0)
{
zero=zero+1;
}
if(array[X][Y]==1)
{
one=one+1;
}
if(array[X][Y]==2)
{
two=two+1;
}
if(array[X][Y]==3)
{
three=three+1;
}
if(array[X][Y]==4)
{
four=four+1;
}
if(array[X][Y]==5)
{
five=five+1;
}
if(array[X][Y]==6)
{
six=six+1;
}
if(array[X][Y]==7)
{
seven=seven+1;
}
if(array[X][Y]==8)
{
eight=eight+1;
}
if(array[X][Y]==9)
{
nine=nine+1;
}
Y++;
if(Y==4)
{
Y=0;
X++;
}
}
if(Q==0)
{
return zero;
}
if(Q==1)
{
return one;
}
if(Q==2)
{
return two;
}
if(Q==3)
{
return three;
}
if(Q==4)
{
return four;
}
if(Q==5)
{
return five;
}
if(Q==6)
{
return six;
}
if(Q==7)
{
return seven;
}
if(Q==8)
{
return eight;
}
if(Q==9)
{
return nine;
}
}
main.cpp
#include <iomanip>
#include <locale>
#include <sstream>
#include <string>
#include <iostream>
extern int count_numbers(int array[4][4], int);
int array[4][4] = { {1,2,3,4} , {1,2,3,4} , {1,2,3,4} , {1,2,3,4}};
int main()
{
count_numbers(array);
std::cout << ",0:" << count_numbers(array, 0) << ",1:" << count_numbers(array, 1) << ",2:" << count_numbers(array, 2) << ",3:" << count_numbers(array, 3) << ",4:" << count_numbers(array, 4) << ",5:" << count_numbers(array, 5) << ",6:" << count_numbers(array, 6) <<",7:" << count_numbers(array, 7) << ",8:" << count_numbers(array, 8) << ",9:" << count_numbers(array, 9) << std::endl;
}
PS. Ignore incorrect indentation its just from pasting to this site
PPS. Thanks for any assistance.
EDIT
Thank you "Vlad From Moscow" for the assistance.
My initial (terrible) code would have worked if I'd simply removed the (unintentional) count_number(array); call from main.cpp
However the for loop system proposed by Vlad allowed me to shrink the code by 80%. It now looks like this:
int count_numbers(int array[4][4], int Q)
{
int ans=0;
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
ans += array[i][j] ==Q;
}
}
return ans;
}
Thank you for the assistance which was great, I began coding on Python so it was my lack of understanding of loops in C++ which was the real problem here.
Anyway, problem solved..
This call
count_numbers(array);
does not make sense and moreover is invalid because the function requires two arguments instead of one.
The function itself can be written the following way
const size_t N = 4;
size_t count_number( const int ( &a )[N][N], int value )
{
size_t n = 0;
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
n += a[i][j] == value;
}
}
return n;
}
and called like
std::cout << "0: " << count_number( array, 0 )
<< ", 1: " << count_number( array, 1 )
<< ", 2: " << count_number( array, 2 )
<< ", 3: " << count_number( array, 3 )
<< ", 4: " << count_number( array, 4 )
<< ", 5: " << count_number( array, 5 )
<< ", 6: " << count_number( array, 6 )
<< ", 7: " << count_number( array, 7 )
<< ", 8: " << count_number( array, 8 )
<< ", 9: " << count_number( array, 9 )
<< std::endl;
Here is a demonstrative program
#include <iostream>
const size_t N = 4;
size_t count_number( const int ( &a )[N][N], int value )
{
size_t n = 0;
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
n += a[i][j] == value;
}
}
return n;
}
int main()
{
int array[N][N] =
{
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 }
};
bool first = true;
for ( int value = 0; value < 10; ++value )
{
size_t n = count_number( array, value );
if ( n )
{
std::cout << ( first ? first = false, "" : ", " )
<< value << ": " << n;
}
}
std::cout << std::endl;
}
Its output is
1: 4, 2: 4, 3: 4, 4: 4
A more general approach can look the following way
#include <iostream>
#include <iterator>
#include <algorithm>
template <typename InputIterator, typename T>
size_t count_number( InputIterator first,
InputIterator last,
const T &value )
{
size_t n = 0;
for ( ; first != last; ++first )
{
n += std::count( std::begin( *first ), std::end( *first ), value );
}
return n;
}
int main()
{
const size_t N = 4;
int array[N][N] =
{
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 }
};
bool first = true;
for ( int value = 0; value < 10; ++value )
{
size_t n = count_number( std::begin( array ), std::end( array ), value );
if ( n )
{
std::cout << ( first ? first = false, "" : ", " )
<< value << ": " << n;
}
}
std::cout << std::endl;
}
The program output will be the same as it is shown above.
If the array contains only digits that you need to count then the function can look like
const size_t N = 4;
void count_digits( const int ( &a )[N][N], size_t ( &digits)[10] )
{
for ( size_t &x : digits ) x = 0;
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
++digits[a[i][j]];
}
}
}
To call the function you need to declare in main an array like for example
size_t digits[10];
you can return int[] or event better since you are using c++ return vector<int>.
In your function you can replace one, two, .. with something like
vector<int> result(10);
This will create a vector with 10 entries, all of them 0.
Then replace thing like three = three + 1 with result[3] = result[3] + 1 or even more condensed result[3]++
Then at the end you can write ... << ",0:" << result[0] << ... or even do a for loop like:
for (int i = 0; i < 10; ++i) count << "," << i << ":" << result[i];
You can do all this with int[] as well if that's required but you need to take care of allocating and deallocating the memory. vector will simplify your code a lot.

How to move elements in an array, putting odds to the beginning of the array (smallest to largest), and evens to the back ( largest to smallest )

I have to write a functioncalled moveAndSortInt() that will receive an array of integers as an argument, and move all the even values down to the second half of the array and sort them from largest to smallest, while all the odd values will be sorted from smallest to largest. How can I improve my code?
#include <iostream>
using namespace std;
void moveAndSortInt(int[], int);
void displayName();
int main() {
int ary1[] = { -19, 270, 76, -61, 54 };
int size = 5;
int i;
int ary2[] = {9, 8, -103, -73, 74, 53};
int size2 = 6;
int j;
displayName();
cout << endl;
cout << "Original ary1[]" << endl;
for (i = 0; i < size; i++) {
cout << " " << ary1[i] << " ";
}
cout << endl;
cout << "\nCallingMoveAndSortInt() --\n " << endl;
moveAndSortInt(ary1, size);
cout << "Updated ary1[]" << endl;
for (i = 0; i < size; i++) {
cout << " " << ary1[i] << " ";
}
cout << endl;
cout << "\nOriginal ary2[]" << endl;
for (j = 0; j < size2; j++) {
cout << " " << ary2[j] << " ";
}
cout << endl;
cout << "\nCallingMoveAndSortInt() --\n" << endl;
moveAndSortInt(ary2, size2);
cout << "Updated ary2[]" << endl;
for (j = 0; j < size2; j++) {
cout << " " << ary2[j] << " ";
}
}
void moveAndSortInt(int ary[], int size) {
int i, j;
int temp;
for (i = 0; i < 1 + size / 2; i++) {
if (ary[i] % 2 == 0) {
for (j = size - 1; j > size / 2; j--) {
if (ary[j] % 2 != 0) {
temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
j = 0;
}
}
}
}
return;
I would suggest using std::sort, the standard algorithm for sorting, which is often implemented with a Quicksort. It is very fast, and also supports custom comparison. Here's some code to get you started:
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> data = { 2, 213, 2, 2, 3 ,123, 4, 213, 2132, 123 };
std::sort(data.begin(), data.end(), [](int lhs, int rhs)
{
if (lhs % 2) // if lhs is odd
if (rhs % 2) // and rhs is odd then just use comparision
return lhs < rhs;
else // and if rhs is even then rhs is "bigger"
return false;
else // if lhs is even
if (rhs % 2)
return true; // and rhs is odd then lhs is "bigger"
else // and if they are both even just use comparision.
return lhs < rhs;
});
}
I'm sorry if that code is a little hard to read, but it does the trick.
This of course would work with C-style arrays too, just replace data.begin() with data and data.end() with data + size.
Alright, so I looked at it a bit. Let's start with conventions.
int i;
for (i = 1; i < 10; i++)
Can be shortened to:
for (int i = 1; i < 10; i++)
Which looks better and is more readable. It would also be nice to have a few more comments, but that's something everyone needs to get better at, no matter how good they are.
So it seems that your code does correctly sort the array into even and odd halves. That's all you need to do yourself as long as you know where they end because sorting them largest to smallest is something that std::sort can do for you.
Edit: It was pointed out to me that my previous example is not exactly the same, as with the second one i can only be used in the loop. For your purposes, they work the same.
You can just reorder it
#include <algorithm>
#include <climits>
#include <iostream>
#include <vector>
int main()
{
auto const shuffle = [] (int input)
{
if ( input % 2 )
{
unsigned const dist_from_min = (unsigned)input - INT_MIN;
return dist_from_min >> 1;
}
else
{
unsigned const dist_from_max = INT_MAX - (unsigned)input;
return INT_MIN + (dist_from_max >> 1);
}
};
auto const ordering = [shuffle] (int left, int right)
{ return shuffle (left) < shuffle (right); };
std::vector <int> data =
{ 5, 2, 3, 0, -1, -3, 1, 100
, INT_MIN, INT_MIN + 1, INT_MAX, INT_MAX - 1
, -567, -765, 765, 567, -234, -432, 234, 432
};
std::sort ( data.begin ( ), data.end ( ), ordering );
for ( auto item : data )
std::cout << item << "\n";
}