Thread: Help with pointers and arrays! (New :P )

  1. #1
    Registered User
    Join Date
    Mar 2014
    Posts
    5

    Help with pointers and arrays! (New :P )

    Hi i am writing a class that dynamically allocates an array that holds a user-defined number of test scores (test scores go from 0 to 10 both included).
    Once all the test scores are entered and validated (values only between 0 and 10, both included), the array should be passed to a function that sorts them in ascending order.
    Another function should be called that calculates theaverage of all the scores.The main program should display the sorted list of scoresand the average of the scores with appropriate headings.

    I am pretty familiar with what needs to be done, i am just having a bit of trouble writing it as a class. Thanks for any help or suggestions!! Ps my goal is to learn and understand these

  2. #2
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Well, you seem off to a good start. Writing out what needs to be done is by far and above one of the most powerful things you can do in programming.

    So let's help you sort out your logic and how you should code this up.

    1. Dynamically allocate array
    2. Fill the array with values (validate the values)
    3. Sort the array
    4. Write a function that finds the average of the array
    5. Print it all out as visual confirmation

    Now, if you have trouble with any of these steps, post what code you have and we'll take it from there

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Break it down into pieces. For example, there may be a function to validate a test score. There may be another function to insert a validated score into the array (resizing if needed). The class will need data members to keep track of things (say, a pointer and a count of elements). A constructor will be needed that initialises those data members in a sane manner, and a destructor (invoked when an instance of your class is destroyed) to clean up. There will be another function to sort the array, and another to compute the average. There may be a function to retrieve values from the array (so main() can print them individually) or a function to simply print the values.

    The decisions you will need to make is which functions need to be members of the class (except for constructors and destructor as those can only be members of the class).

    Generally speaking, the functions need to be considered in terms of preconditions (things that a function assumes to be true when it is called) and post-conditions (things the function guarantees will be true after it returns). The set of preconditions and post-conditions need to be consistent otherwise, if two functions are called one after the other, one will screw it up for the other.

    Once you have all the functions together (whether as member functions of the class, or something else) then you need to write the main() function to create an instance of your class (aka object), call member functions on it in some sequence. When main() returns, the object should be destroyed (and its destructor invoked).

    Generally speaking, data members of the class would be best declared private (so functions outside the class, including main(), cannot directly monkey with them). The member functions will be called by main(), so they should be public (otherwise main() cannot call them). [There are alternatives to this, but don't worry about that - keep it simple].
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Mar 2014
    Posts
    5
    Wow thanks guys! Your help is appreciated. This is what i have written so far. (I know it is not correct but I need to learn what i am doing wrong)

    Code:
    #include <iostream>
    using namespace std;
    
    
    class TestScores
    {
    private:
    	int *score;
    	double average;
    	double total;
    	int size;
    	int numScores;
    public:
    	TestScores();
    	void getScore();
    	void setTotal();
    	void getAverage(int*, int size);
    };
    void TestScores::getScore()
    {
    	score= new int [numScores];
    	for(int i=0;i<numScores;i++)
    	{
    		cout<<"Enter the score for test#"<<i+1;
    		cin>>score[i];
    }
    void TestScores::setTotal()
    {total=0.0;}
    void TestScores::getAverage()
    {
    	double sum=0.0,avg;
    	for(int i=0;i<size;i++)
    	{
    		sum+=score[i];
    	}
    	return avg=sum/size;
    }

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Well, you need a main() function which creates an instance of that class, and calls member functions on it.

    Implementation of a constructor would be useful. What is the difference between size and numScores? How are they to be set? getAverage() is declared void but tries to return a value (so will not compile). There is a missing curly-brace in getScore(), which will also prevent your code compiling.

    In line with my previous comments about preconditions and postconditions needing to be consistent.

    1) There is no code that sets the value of numScores or size. Consider where you might do that. What would happen if getScore() or getAverage() were called before numScores and size are given useful values?
    2) Even if there was code to set the value of numScores (which there isn't) what would happen if getScore() was called twice in succession.
    3) What would happen if your code called getAverage() before getScore() was ever called?
    4) Is it possible to call savely getAverage() without having called getScore()? As you've done it, does getScore() set things up so getAverage() CAN be called?


    The big thing you're doing wrong is not being systematic. Every time you add a variable (or data member), you need to have a concept of what it means. Every time you add a function, you need to think about how it interacts with other functions - that is important if they are acting on the same data.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Consider using std::vector instead of pointers if you are allowed. Dynamic arrays is nothing to scoff at; they're difficult and complex. Thankfully, std::vector takes that complexity out of the picture. That's what it's there for.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Registered User
    Join Date
    Mar 2014
    Posts
    5
    ok Thanks for the input! this is what i have
    Code:
    #include <iostream>using namespace std;
    
    
    class TestScores
    {
    private:
    	double *score;
    	int numScores;
    public:
    	void getScore();
    	void sortScore(double score[], int numScores);
    	void showScore(const double score[], int numScores);
    	double getAverage(double*, int);
    	
    };
    
    
    void TestScores::getScore()
    {
    	score= new double [numScores];
    	for(int i=0;i<numScores;i++)
    	{
    		cout<<"Enter the score for test#"<<i+1;
    		cin>>score[i];
    		while(numScores<0||numScores>10)
    		{
    			cout<<"Error! Invalid score. Please try again."<<endl;
    			cin>>score[i];
    		}
    	}
    }
    
    
    double TestScores::getAverage(double *score,int numScores)
    {
    	double total=0.0,avg;
    	for(int i=0;i<numScores;i++)
    	{
    		total+=score[i];
    	}
    	avg=total/numScores;
    	cout<<"The average is"<<avg;
    	return avg;
    }
    
    
    void TestScores::sortScore(double score[], int numScores)
    {
    	int temp;
    	bool swap;
    	do
    	{
    		swap=false;
    		for(int count=0;count<(numScores-1);count++)
    		{
    			if(score[count]>score[count+1])
    			{
    				temp=score[count];
    				score[count]=score[count+1];
    				score[count+1]=temp;
    				swap=true;
    			}
    		}
    	}while(swap);
    }
    void TestScores::showScore(const double score[], int numScores)
    {
    	for(int count=0;count<numScores;count++)
    		cout<<score[count]<<" ";
    	cout<<endl;
    }
    
    
    int main()
    {
    	int size;
    	double *grades;
    	TestScores student;
    	student.getScore();
    	student.sortScore( grades,size);
    	student.getAverage(grades,size);
    	student.showScore(grades,size);
    	delete grades;
    	system("pause");
    
    
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers to pointers and pointer arrays
    By Dave11 in forum C Programming
    Replies: 5
    Last Post: 02-24-2014, 10:38 PM
  2. Pointers to pointers with arrays
    By Nurumla in forum C Programming
    Replies: 3
    Last Post: 07-18-2011, 11:53 PM
  3. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  4. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  5. pointers and arrays
    By rxg00u in forum C++ Programming
    Replies: 1
    Last Post: 03-19-2002, 07:28 AM

Tags for this Thread