C++

Soldato
Joined
20 Nov 2002
Posts
11,141
Location
Barnsley
Just starting my Programming C++ resit work and I've forgot most of it :o

Anyway, I wonder if someone can give this a quick check over for me to see if I'm on the right track?

I've been asked the following question:

1. Write a C++ function, called inputValidNumber, which prompts the user for a value in a given range, reads in a number, checks that it is in a range specified and returns it. While the value read in is not in the specified range, the system repeatedly asks for another one until a valid value is input.
The function takes 2 parameters respectively representing the minimum and maximum value of the valid range (both inclusive).

For example, the following statement sets the value of a variable number to the first number input by the user that is greater than or equal to 1 and less than or equal to 20.
int number = inputValidNumber( 1, ROWS);

This is what I've come up with:

Code:
void inputValidNumber ( minValue, maxValue)
int enteredNumber;
{
	cout << “Enter a value between “ << minValue << “and “ << maxValue;
	cin >> enteredNumber;
	while ( enteredNumber >= minValue && =< maxValue)
		cout << enteredNumber;
}

Does that seem OK? Be gentle with me, I really suck at C++ :(
 
As far as I can tell that won't ask for the input again if the number isn't in the range. Try this (don't know C++, so untested):

Code:
void inputValidNumber ( minValue, maxValue)
int enteredNumber;
{
        enteredNumber = -1;
        while ( enteredNumber <= minValue || enteredNumber >= maxValue ) {
		cout << "Enter a value between " << minValue << " and " << maxValue;
		cin >> enteredNumber;
        	cout << enteredNumber;
	}
}

(You should probably do some input checking--you need maxValue to be greater than minValue, for example.)
 
Right, for starters, is there a chance text or any other character will be entered? Because you might need to take that into account too.

Secondly, if you input an incorrect value, the while loop wont be executed at all.

Dont really know much C++ myself, but ive done Java, C and C# for some time.

Hope that can get you started though :)
 
Thanks for the advice guys, I'd not even thought about validation!

The project spec states that I should write down any assumptions that I make, so maybe I could note that I'm assuming that the minValue is lower than the maxValue. Would save me having to code it up.

Thanks again dudes, I'll post up again on my progress :)
 
Your probably best using a do-while loop on this function, Makes a more logical choice in my opinion.

int function(max, min)
{
int number;
do
{
number = get_number;
}
while(check_ranges)

return number;
}
 
Last edited:
Couple of points:

1. The question doesn't ask for validation, whilst I agree it is good programming it will waste time in an exam. Though you might want to ask your tutor if it would be expected.

2. A Do While loop would be more appropriate but you probably won't loose marks using a While loop.

3. Have you tried thinking about this logicaly BEFORE writing any code? Write down in English was you think you need to programme. Like this.


Read the number in

2: See if it is between min and max.
If it is, return the number.

If it is not ask for a number again.
Go back to 2.

Justin
 
It's a couple of years since i did any C++, but i'd agree with assuming no error checking i.e whether the user has actually input an integer, as this can involve a lot more code, unless you can learn it off pat. I loved the challenge of C++, but error checking took a lot of the enjoyment out of programming for me, the tutor could always find a way of crashing it - programming would be easy, if it wasn't for the divvys using it :D
 
You can but it's not proper error checking, it just converts a string to an integer and returns turns a zero if string can't be converted. I suppose you could have it so that if it returns zero you give an error message, as long as zero isn't within the specified range. TBH we had to learn how to code things that had inbuilt functions already in C++ like link lists, just so we could see how they worked, so there are probably lots of shortcuts i don't know about as the experienced tutor left before the course ended and we ended up being taught by by somebody who had just passed the course we were nearly finished.
 
Hi again guys, I'm having a little bit of trouble with the following question.

Write a C++ function, called findMousePosition, which looks for the position of the mouse on the board.
The mouse is represented in the array theGrid by the character '@'.
The function takes three parameters: the first one is an array that represents the current configuration of the board, the second and third ones are respectively set to the row and column numbers of the cell that contains the mouse.
You may assume that the mouse is on the board.

For example, the following statement sets the value of the integer variables rowMouse and colMouse to the coordinates of the character '@' in the array theGrid.
findMousePosition( theGrid, rowMouse, colMouse);

I guess that I need to perform a loop of some sort to check every coordinate in the grid until a find the mouse (@), but I'm confused as to how I would best go about coding it.

Any ideas would be appreciated.

EDIT: This was also written at the top of all the questions:

The following constants have been declared as global to the whole program:
const int ROWS( 20); //vertical dimension
const int COLS( 10); //horizontal dimension
The main program (i.e., top level algorithm) contains the following local variable declaration:
char theGrid[ ROWS+1][ COLS+1];
 
Last edited:
Oh and if anyone is interested what I came to for the first question I got this:

Code:
void inputValidNumber ( const int minValue, const int maxValue)
int enteredNumber;
{
	do {
               cout << “Enter a value between “ << minValue << “and “ << maxValue;
               cin >> enteredNumber;
        } while ( enteredNumber < minValue && enteredNumber > maxValue)

	cout << enteredNumber;
}

Does that look better?
 
int enteredNumber; needs to be inside the { }

Code:
void inputValidNumber (const int minValue, const int maxValue)
{

  int enteredNumber;
	
  do
  {
    cout << “Enter a value between “ << minValue << “and “ << maxValue;
    cin >> enteredNumber;
  }
  while (enteredNumber < minValue && enteredNumber > maxValue)

  cout << enteredNumber;

}

Looks ok otherwise
 
Last edited:
Hey again, thanks for the checking so far. Got another couple for you to have a look at :p

The following questions are assuming that the below is declared globally:

Code:
const int ROWS( 20);				//vertical dimension
const int COLS( 10);				//horizontal dimension
char theGrid[ ROWS+1][ COLS+1];

Here is the first question:

Write a C++ function, called findMousePosition, which looks for the position of the mouse on the board.
The mouse is represented in the array theGrid by the character '@'.
The function takes three parameters: the first one is an array that represents the current configuration of the board, the second and third ones are respectively set to the row and column numbers of the cell that contains the mouse.
You may assume that the mouse is on the board.

For example, the following statement sets the value of the integer variables rowMouse and colMouse to the coordinates of the character '@' in the array theGrid.
findMousePosition( theGrid, rowMouse, colMouse);

This is what I came up with:

Code:
void findMousePosition ( int theGrid[], int& rowMouse, int& colMouse)
{

	for ( int rowNo( 1); rowNo <= ROWS; ++rowNo)
		for (int colNo ( 1); colon <= COLS; ++colNo)
			
			if ( theGrid[rowNo][colNo] == “@”)
				rowMouse = theGrid[rowNo];
				colMouse = theGrid[colNo];

}

Here's the next question:

Write a C++ function, called countApples, which counts the number of apples currently on the grid, i.e., number of cells that contain the character 'O' used to represent an apple.
The function takes two parameters: the first one is an array that represents the current configuration of the board and the second one represents the number of apples it currently contains.

For example, the following statement sets the value of the integer variable totalApples to the number of times (may be 0) the character 'O' is present in the array theGrid.
countApples( theGrid, totalApples);

Here's what I came up with for this one:

Code:
void countApples ( int theGrid[], int& totalApples)

{
	int appleCount;

	for (int rowNo( 1); rowNo <= ROWS; ++rowNo)
		for (int colNo( 1); colNo <= COLS; ++colNo)
			if (theGrid[rowNo][colNo] == “o”)
				appleCount = appleCount + 1;
	
	totalApples = appleCount
	
}

If anyone can spot any errors in this I'd be greatly appreciative of any advice.

Thanks again guys :)
 
Tommy D said:
Code:
void findMousePosition ( int theGrid[], int& rowMouse, int& colMouse)
{

	for ( int rowNo( 1); rowNo <= ROWS; ++rowNo)
		for (int colNo ( 1); colon <= COLS; ++colNo)
			
			if ( theGrid[rowNo][colNo] == “@”)
				rowMouse = theGrid[rowNo];
				colMouse = theGrid[colNo];

}

break out of the loop after finding it, to save going through the rest of the array needlessly. Also, I think your for syntax is out (see question two).

Tommy D said:
Code:
void countApples ( int theGrid[], int& totalApples)

{
	int appleCount;

	for (int rowNo( 1); rowNo <= ROWS; ++rowNo)
		for (int colNo( 1); colNo <= COLS; ++colNo)
			if (theGrid[rowNo][colNo] == “o”)
				appleCount = appleCount + 1;
	
	totalApples = appleCount
	
}

Shouldn't this be:

Code:
void countApples ( int theGrid[], int& totalApples ) {
	for ( int row = 0; row <= ROWS; row++ ) {
		for ( int col = 0; col <= COLS; col++ ) {
			if ( theGrid[row][col] == "o") {
				appleCount++;
			}
		}
	}
	return totalApples
}
 
robmiller said:
break out of the loop after finding it, to save going through the rest of the array needlessly. Also, I think your for syntax is out (see question two).



Shouldn't this be:

Code:
void countApples ( int theGrid[], int& totalApples ) {
	for ( int row = 0; row <= ROWS; row++ ) {
		for ( int col = 0; col <= COLS; col++ ) {
			if ( theGrid[row][col] == "o") {
				appleCount++;
			}
		}
	}
	return totalApples
}

Right, so question 2 I can see I've made an extra variable unessecarily.

I was 50/50 whether to use the appleCount++ or appleCount = appleCount + 1, guess I chose the wrong one hehe :p

I'm not too sure about the syntax? I've tried to stick to examples in my books, so I would have thought it was alright.

Thanks a ton for the suggestions mate :)

Oh and this breaking bussiness, I need to break out of both for loops seperatley right? Given that I'm using 2 nested? Something like this?

Code:
void findMousePosition ( int theGrid[], int& rowMouse, int& colMouse)
{

	for ( int rowNo( 1); rowNo <= ROWS; ++rowNo)
		for (int colNo ( 1); colon <= COLS; ++colNo)
			
			if ( theGrid[rowNo][colNo] == “@”)
				rowMouse = theGrid[rowNo];
				colMouse = theGrid[colNo];
		break;
	break;

}
 
Last edited:
Tommy D said:
I'm not too sure about the syntax? I've tried to stick to examples in my books, so I would have thought it was alright.

Every C-like language I've ever used has had a for syntax of initialisation/condition/incrementation. I'm 99.99% certain C++ is the same.

Presuming that that's what you want to do--initialise rowNo/colNo to 1--should you really be starting with 1? Array indexes typically start at 0.

Also, you probably shouldn't pre-increment in the for-loop--this would result in (if you're initialising rowNo/colNo to 0) the loop starting at 1, skipping an array element. Instead, post-increment: i++ rather than ++i.

Tommy D said:
Oh and this breaking bussiness, I need to break out of both for loops seperatley right? Given that I'm using 2 nested? Something like this?

Yep, although my comments about the for syntax still stand.
 
robmiller said:
Every C-like language I've ever used has had a for syntax of initialisation/condition/incrementation. I'm 99.99% certain C++ is the same.

Presuming that that's what you want to do--initialise rowNo/colNo to 1--should you really be starting with 1? Array indexes typically start at 0.

Also, you probably shouldn't pre-increment in the for-loop--this would result in (if you're initialising rowNo/colNo to 0) the loop starting at 1, skipping an array element. Instead, post-increment: i++ rather than ++i.



Yep, although my comments about the for syntax still stand.
Right, I think that actually makes sense. I'll go over it again later.

Thanks again dude ;)
 
Back
Top Bottom