GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 14-Oct-2009, 19:36
mcb413 mcb413 is offline
New Member
 
Join Date: Oct 2009
Posts: 1
mcb413 is on a distinguished road
Question

Void functions with arrays


Hi guys, I need help with arrays and functions. I have to do the following:Write a C++ program that has a main function and one void function.

The void function is to be named sortof and will be called by the main function. The function sortof has two arguments, each of which are one-dimensional arrays of length four. The main program prompts the user for four numbers. These four numbers are stored in one of the two arrays. The function is then called and it sorts the numbers into their proper order, storing them in order (lowest to highest) in the second array. The main program then prints out the unsorted and sorted array to the screen.

You don't have to use a fancy sorting routine, just determine the max, the min and then do the same for the two numbers left behind.
------------------------------------------------
what I've done:

CPP / C++ / C Code:
using namespace std;
#include<iostream>
#include<cmath>
#include<iomanip>
void sortof(int[], int[]);
int main()
{ int st, sr,n;
int storearray[4], sortarray[4];
int a, b , c, d;
cout<<"Enter four numbers: ";
sortof(storearray, sortarray);
for(n=0; n<4; n++)
{
cin>>st;
storearray[n]=st;
}

cout<<fixed<<setw(6)<<"\nUnsorted numbers"<<setw(25)<<"Sorted numbers"<<endl;

for(n=0; n<4; n++)
{
cout<<setw(6)<<storearray[n];
};
if (a==sr)cout<<"The greater number"<<endl;

system ("pause");
return 0;
}

void sortof(int st[], int sr[])
{ int n;
int store, store_ind;
int sort, sort_ind;
store=st[0];
store_ind=0;
for(n=0; n<4; n++)
{ if (store<st[n])
sr[n]=st[n];
};
}
Last edited by LuciWiz : 15-Oct-2009 at 00:53. Reason: Please insert your C++ code between [cpp] & [/cpp] tags
  #2  
Old 15-Oct-2009, 05:43
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 342
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Void functions with arrays


Firstly, your code is poorly formatted and your use of whitespace needs a lot of improvement. Poor coding style makes for difficult to read and understand code. Select an exisiting, accepted, good style and use it.

Secondly, you are being taught and/or are electively using bad variable names.

"sortof" ...what in the world does THAT mean? In English, it is similar to "maybe" or "somewhat." Unless is is supposed to be some kind of acronym, it has no real meaning, at least not by someone reading its name alone and trying to figure out what it is supposed to do or mean.

What about your variable names for your two arrays? st and sr? Which is which just from looking at the names? Which one is "store" and which is "sort?" Doesn't both of the "longer names" each have most of the same letters?

I don't think that anyone likes to hear their "style" being "attacked," but I strongly recommend that you decide to improve it greatly or simply give up programming in your life. Some may consider this to be too harsh, but I believe it is that important. Obviously, you may choose to ignore any advice that you receive from any source, including whether or not to blindly follow the stupid assignment that the name of the function must be named "sortof."

If it was up to me, I'd implement the ridiculously named function and then create a function pointer using an appropriate name and then call it, which, I'd argue, still meets the rather stringent requirements. Of course, there is something to be said about lemmings who blindly follow.

The notion that "sortof" has only two arguments is yet another example of bad programming instruction and/or practices. It says that the integer arrays are of length 4 (assuming count of elements). However, there is no way to ensure that the user does not misuse the function by sending just two elements or two million elements. Of course, if we add the additional arguments for "length in number of elements," there is no guaranty that the user will provide the correct number of elements, all which contribute to undefined behavior for reasonable implementations.

However, in C++, we say that the signature of a "function" is a "contract." That if someone gives us the arguments correctly, then we will produce the correct results. That "contract" is unenforceable when the arguments list is simply two int pointers. In other words, parts of the contract are UNWRITTEN and therefore are worthless. (If you prefer, the value of an unwritten contract is not worth the paper that it is written on.)

It is VERY BAD to use "unwritten contracts" in code. Subsequent programmers and/or users of the code will not readily know that the "unwritten part" exists and will surely break the code or worse, it will continue "to work" without failing, becoming a timebomb waiting to happen. Someday it will blow up, and probably take a month of Sundays to figure out what went wrong.

When an experienced programmer sees "bad code," one must suspect everything, regardless of how ingeniously it may solve a problem, bad traits and poor style give cause for justified alarm.

How about this as a start?

CPP / C++ / C Code:
#include <iostream>

#include <cstdlib>
#include <cstring>

using namespace std;

#ifdef __cplusplus
extern "C" {
#endif

int integer_compare(const void* first, const void* second)
{
    if(first && second)
    {
        const int* pfirst  = (const int*)first;
        const int* psecond = (const int*)second;

        return (*pfirst - *psecond);
    }
    else
    {
        return 0;
    }
}

void sortof(const int* src, const size_t src_len, int* dest, const size_t dest_len)
{
    if(src && dest)
    {
        if(src_len == dest_len)
        {
            memcpy(dest, src, (dest_len * sizeof(int)));
            qsort(dest, dest_len, sizeof(int), integer_compare);
        }
    }
}

#ifdef __cplusplus
}
#endif

typedef void (*INT_ARRAY_SORT)(const int*, const size_t, int *, size_t);

int main()
{
    int unsorted[4] = {0};
    for(size_t i = 0; i < sizeof(unsorted)/sizeof(int); i++)
    {
        cout << "Enter an integer number: ";
        int tmp;
        cin >> tmp;
        if(!cin.fail() && cin.good())
        {
            unsorted[i] = tmp;
        }
        else
        {
            cout << "\nUser failure to follow simple instructions\nresult in computer dismay.\nExiting...\n";
            exit(cin.fail());
        }
    }
    int sorted[4];
    INT_ARRAY_SORT IntegerArraySort = &sortof;
    IntegerArraySort(unsorted, sizeof(unsorted)/sizeof(int), sorted, sizeof(sorted)/sizeof(int));

    for(size_t i = 0; i < sizeof(unsorted)/sizeof(int); i++)
    {
        cout << unsorted[i] << " ";
    }
    cout << endl;
    for(size_t i = 0; i < sizeof(sorted)/sizeof(int); i++)
    {
        cout << sorted[i] << " ";
    }
    cout << endl;

    return 0;
}


Output:

Code:
$ ./mcb413 Enter an integer number: 1 Enter an integer number: 5 Enter an integer number: 3 Enter an integer number: 29128 1 5 3 29128 1 3 5 29128 $ ./mcb413 Enter an integer number: 1928 Enter an integer number: -839 Enter an integer number: 9837827 Enter an integer number: -3333 1928 -839 9837827 -3333 -3333 -839 1928 9837827 $ ./mcb413 Enter an integer number: 232 Enter an integer number: 39.2834 Enter an integer number: User failure to follow simple instructions result in computer dismay. Exiting...

I'll leave it to you to decide how you want to complete the other "requirements." Also, if you wish to review the obvious issue with the fail/good test and the output to the user (has a bug!), it needs to be "fixed," but that is up to you to decide how to proceed.


MxB
  #3  
Old 16-Oct-2009, 06:21
Kimmo Kimmo is offline
Regular Member
 
Join Date: Mar 2007
Location: Finland
Posts: 350
Kimmo is a jewel in the roughKimmo is a jewel in the roughKimmo is a jewel in the rough

Re: Void functions with arrays


You could do what Bob says or you could do it the mortal way. That is, fixing what is broken learning as you go.

I'll try highlight the parts that most likely will give you trouble.

CPP / C++ / C Code:
 int st, sr,n;
int storearray[4], sortarray[4];
int a, b , c, d;
Non-descriptive names are sure to fire back at you sooner or later. Uninitialized variables aren't much better (which can be seen in your code already; you compare two uninitialized variables later in your code).
CPP / C++ / C Code:
cout<<"Enter four numbers: ";
sortof(storearray, sortarray);
Sorting the array before the user has actually entered any values at all isn't going to do any good. Those values are overwritten anyway.

CPP / C++ / C Code:
if (a==sr)cout<<"The greater number"<<endl;
While this line probably won't give you any troubles at all... It has no meaning at all either. You never assign values to 'a' or 'sr' so what could be the point of comparison? And how does the output relate to this comparison? If a equals sr, then they are equal. Neither is greater than the other.

CPP / C++ / C Code:
void sortof(int st[], int sr[])
Your sortof() does not work. That is, it doesn't actually sort anything. If you have to implement the sort yourself (as I understood), then the simplest sort of all times is bubble sort. What's more, it's perfectly good for an array with only 4 elements.
You could do it something like this.
CPP / C++ / C Code:
#include <iostream>

using std::cout;
using std::endl;

void bubbleSort(int[], int);

const int ARRAY_SIZE = 4;

int main()
{
    int intArray[ARRAY_SIZE] = {1, 36, -534, 2};
    
    cout << "The original array\n" << endl;
    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        cout << intArray[i] << endl;
    }
    cout << "\n";
    
    bubbleSort(intArray, ARRAY_SIZE);
    
    cout << "The array sorted.\n" << endl;
    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        cout << intArray[i] << endl;
    }
    
    return 0;
}

// Simplest sort ever.
// First argument is array, second is number of elements in array
void bubbleSort(int intArray[], int size)
{
    // This variable signals if the array is possibly not sorted.
    // If elements are moved during an iteration, this
    // is set to false to signal that the array MIGHT not be sorted yet.
    bool sorted = false;

    // We continue to loop as long as the array is (possibly) not sorted
    while (!sorted)
    {
        // We're optimistic and assume that THIS time finally the array IS sorted
        // (This way we also avoid an infinite loop)
        sorted = true;
        
        // We go through the array each time.
        // i starts at 1 because we access elements at i - 1
        for (int i = 1; i < size; i++)
        {
            if (intArray[i - 1] > intArray[i])
            {
                // If the element in the lower index really is greater than the one in the
                // higher index, we swap the elements. So the greater elements slowly move to the
                // end of the array
                int temp = intArray[i];
                intArray[i] = intArray[i - 1];
                intArray[i - 1] = temp;
                // Finally we set sorted to false to signal that a swap operation has occurred
                // and the sequence must continue.
                sorted = false;
            }
        }
    }
    
}

Output:
Code:
The original array 1 36 -534 2 The array sorted. -534 1 2 36
 
 

Recent GIDBlogNot selected for officer school by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Assembly Tutorial? zatora Assembly Language 76 22-Apr-2009 21:19
Linked Lists advice request promsan C Programming Language 74 23-May-2007 08:29
triangle (polygon), drawing, sizing, and rotation programme using linked lists... promsan C Programming Language 12 14-May-2007 14:03
need help with a console menu system BullBuchanan C++ Forum 6 20-Aug-2006 14:46
Shapes Functions Version 2 - Arrays! Cecil C Programming Language 1 09-Jul-2006 20:39

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 12:26.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.