Havin trouble with a program for class..

SuperU

Lifetime Member
Joined
Feb 26, 2007
Messages
257
Reaction score
3
Points
18
Since you guys have been so helpful through the years with macros and scripts, I figured it was the best place to come for a little help.

I'm finally starting my programming classes, and its the best. However, I'm having a little bit of trouble rationalizing my if commands, and was wondering what you guys might be able to offer.

Background:

All thats required is a simple program to do adding/subtracting/multiplying/dividing. I've gotten the program down no problem. My issue that I've come to, is I'm an overachiever, and my book fails to mention how to fix my issue in a way myself or my friend have been able to put into common terms.

Issue:

I'm trying to demonstrate an if statement that checks for the number zero in number2, since its impossible to divide by zero currently, and output a message while returning to the beginning of the program again. Another issue, is that while returning to the main after the attempted if statement, I haven't found the proper terms to simply return to the beginning without a complete interrupt of the program if the second number is or isn't zero.

Code:
PS- All commands are documented for simple grading reasons. Not obligated to post documented reasons for commands; I can always review and learn from the things I overlooked.

Code:
// Purpose: Create a program to add, subtract, divide and multiply input numbers.
//Extra Credit: Identify the zeros of the denumerator, and write a solution to restart with proper inputted numbers.
#include <iostream> // Allows the program to carry out input and output commands

using namespace std; // Allows program to use names from std library

int main()
{
	// Variable Declaration
	int number1; // First number to add
	int number2; // Second number to add
	
	cout << "Enter first integer: "; // Prompts user for number1
	cin >> number1; // Grabs the first integer inputted

	cout << "Enter second integer: "; // Prompts user for number2
	cin >> number2; // Grabs the second integer inputted
		
	int sum; // Sum of number1 and number2
	sum = number1 + number2; // Adds numbers together
	cout << "Sum is " << sum << endl; // Displays sum and ends line
	int difference; // Difference of number 1 and number2
	difference = number1 - number2; // Subtracts number1 by number2
	cout << "Difference is " << difference << endl; // Displays difference and ends line
	int product; // Product of number1 and number2
	product = number1 * number2; // Multiplies number1 and number2 together
	cout << "Product is " << product << endl; // Displays product and ends line
	int quotient; // Quotient of number1 and number2
	quotient = number1 /  number2; // Divides number1 by number2
	cout << "Quotient is " << quotient << endl; // Displays quotient and ends line
	{
		if (number2 == 0)
			cout << "Cannot be divided by zero, please try again." << quotient << endl; // Calls out the impossibility of zero division.
		return main ();
	}
	
	

	return main();  // Returns to beginning of script
} // Ends main function


Look forward to hearin back from some of you guys :)

-Kyle
 
Last edited:
Follow each line of code as it will be executed.

Code:
// Purpose: Create a program to add, subtract, divide and multiply input numbers.
//Extra Credit: Identify the zeros of the denumerator, and write a solution to restart with proper inputted numbers.
#include <iostream> // Allows the program to carry out input and output commands

using namespace std; // Allows program to use names from std library

int main()
{
	// Variable Declaration
1.	int number1; // First number to add
2.	int number2; // Second number to add
	
3.	cout << "Enter first integer: "; // Prompts user for number1
4.	cin >> number1; // Grabs the first integer inputted

5.	cout << "Enter second integer: "; // Prompts user for number2
6.	cin >> number2; // Grabs the second integer inputted
		
7.	int sum; // Sum of number1 and number2
8.	sum = number1 + number2; // Adds numbers together
9.	cout << "Sum is " << sum << endl; // Displays sum and ends line
10.	int difference; // Difference of number 1 and number2
11.	difference = number1 - number2; // Subtracts number1 by number2
12.	cout << "Difference is " << difference << endl; // Displays difference and ends line
13.	int product; // Product of number1 and number2
14.	product = number1 * number2; // Multiplies number1 and number2 together
15.	cout << "Product is " << product << endl; // Displays product and ends line
16.	int quotient; // Quotient of number1 and number2
17.	quotient = number1 /  number2; // Divides number1 by number2
18.	cout << "Quotient is " << quotient << endl; // Displays quotient and ends line
	{
19.		if (number2 == 0)
20.			cout << "Cannot be divided by zero, please try again." << quotient << endl; // Calls out the impossibility of zero division.
21.		return main ();
	}
	
	

22.	return main();  // Returns to beginning of script
} // Ends main function

lines 1-16 are straight forward.
line 17 does the division
line 19 checks to see if divisor is zero

Seems like you would want to switch the order and only do the division if you know number is not zero.

if ( num == 0 ) {
cout << num is zero can't do division
} else {
count << num1 / num2
}

Notice that the { } braces contain the code you execute if num == 0 then if num is not == 0


The use of return main() on lines 21 and 22 are classic. It works but ...
 
What about the return? I know I didn't make any sub main routines or specific classes. Wasn't exactly sure how else to restart without such a definitive command? Mq writing is a bit diff from real programmin lol.
 
What you really want is a loop.

While ( some condition is true ) {
do something
do something else
do something that can change the condition above
}

for example :

cin << a ;
while ( a != 0 ) {
count << " a was " << a ;
cin << a;
}

is a basic loop to read in a number until the number you enter is zero.
 
I appreciate the help man, gave me just what I needed to satisfy my needs. Thanks a ton!
 
As someone pointed out, your if statement was a bit whack. You use { } to define blocks of code, and blocks of code are usually started with some kind of description, such as a conditional if/while or a function.

The main of your program is actually a function:
Code:
int main() {
  // Some code here
}

It's just a special function that the compiler knows to look for and create as the beginning of your program.

You returns, however, are incorrect. Return main() will actually call another copy of main() since you're using the function. Remember, in most programming languages statements are evaluated inside to out, right to left. So main() gets evaluated before your "return" does. Another example is an if statement:

Code:
if (myVar == 0) {
  // Do Things
}

Now if is really just expecting a true or a false, that's all if understands. myVar==0 is being evaluated first, and becomes evaluated to either true or false, then the if happens, and when the conditional is true, the code in the code block happens.

To me, it looks like you're trying to take input, and have a conditional so you don't divide by zero. Basic error handling, really. I would write something like this:

Code:
int main() {
  int number1;
  cout << "Yo, give me an integer: ";
  cin >> number1;

  int number2;
  cout << "Hey dawg, I need another one of those: ";
  cin >> number2;

  cout << "sum = " << number1 + number2 << endl;  
  cout << "difference = " << number1 - number2 << endl;
  cout << "product = " << number1 * number2 << endl;
  if (number2==0) {
    cout << "quotient = undefined, division by zero" << endl;
  } else {
    cout << "quotient = " << number1 / number2 << endl;
  }

  return 0;
}

That gives you your first step, the stuff you need to do. The next thing is to work on what's called flow control. You have to define what your flow control is, which you don't do in your setup. For sake of example, I'm going to say you want to exit the program if two zero's are entered, otherwise you want to show the results of your basic operations.

I'm going to make this easy on myself, and turn the above in to a function, and show you how this works.

Code:
int main() {
  int a;
  int b;

  // Infinite loop, this is bad
  while (true) {
    a = getInteger();
    b = getInteger();

    // I'm providing an exit condition to the infinite loop here, making it less bad.
    if (a == 0 && b == 0) {
      return 0;
    } else {
      doOperations(a, b);
    }
  }
  
  return 0;  // This return should actually never be gotten to
}

int getInteger() {
  int a;
  cout << "Hey bro, can you give me an integer?  Put it here ==> ";
  cin >> a;

  // TODO: You should really do input verification here and make sure they actually entered an integer.

  return a;
}

void doOperations(int number1, int number2) {
  cout << "sum = " << number1 + number2 << endl;  
  cout << "difference = " << number1 - number2 << endl;
  cout << "product = " << number1 * number2 << endl;

  // Check for division by zero
  if (number2==0) {
    cout << "quotient = undefined, division by zero" << endl;
    cout << "remainder = undefined, division by zero" << endl;
  } else {
    cout << "quotient = " << number1 / number2 << endl;
    cout << "remainder = " << number % number2 << endl;
  }

  return;
}

Hope that helps. Hopefully you can see how the functions work, why the returns work the way they do. You're returning a value that should match the type of the function. If you function is an "int" such a main, you should be returning an int. If it's void, you don't need to return anything, but you still need to exit the function. So on and so forth.

PS - this is all pseudo code, my syntax may be off, I haven't used c++, especially stuff like cin/cout, in probably 10 years easy. The concepts should be there though.



Edit: just tried this out for shits and grins
Code:
[root@localhost test]# g++ test.cpp
[root@localhost test]# ./a.out
Hey bro, can you give me an integer?  Put it here ==> 1
Hey bro, can you give me an integer?  Put it here ==> 5
sum = 6
difference = -4
product = 5
quotient = 0
remainder = 1
Hey bro, can you give me an integer?  Put it here ==> 1234
Hey bro, can you give me an integer?  Put it here ==> 2
sum = 1236
difference = 1232
product = 2468
quotient = 617
remainder = 0
Hey bro, can you give me an integer?  Put it here ==> 0
Hey bro, can you give me an integer?  Put it here ==> 0
[root@localhost test]# cat test.cpp
#include <iostream>
using namespace std;

int getInteger() {
        int a;
        cout << "Hey bro, can you give me an integer?  Put it here ==> ";
        cin >> a;

        // TODO: You should really do input verification here and make sure they actually entered an integer.

        return a;
}

void doOperations(int number1, int number2) {
        cout << "sum = " << number1 + number2 << endl;
        cout << "difference = " << number1 - number2 << endl;
        cout << "product = " << number1 * number2 << endl;

        // Check for division by zero
        if ( number2 == 0 ) {
                cout << "quotient = undefined, division by zero" << endl;
                cout << "remainder = undefined, division by zero" << endl;
        } else {
                cout << "quotient = " << number1 / number2 << endl;
                cout << "remainder = " << number1 % number2 << endl;
        }

        return;
}

int main() {
        int a;
        int b;

        // Infinite loop, this is bad
        while (true) {
                a = getInteger();
                b = getInteger();

                // I'm providing an exit condition to the infinite loop here, making it less bad.
                if (a == 0 && b == 0) {
                        return 0;
                } else {
                        doOperations(a, b);
                }
        }

        return 0;  // This return should actually never be gotten to
}

[root@localhost test]#
 
Last edited:
i'm pretty sure you got an answer already but didn't see this solution so I figured I'd stick in my 2 cents :)

I think 40oz had a good solution that will help you get into the practice of making a function (or method if your using java) to do something you need done. That will make life much easier later on when you get into the more advanced programming stuff. If you do something more than twice it's better to build a private method for it that way you can just call it when you need it.

Because your just doing a simple math one I would put the checks in right as they enter in the number. Basically the same way 40oz did it but without going to a method call for anything.


Code:
	int number1 = 0; // First number to add
	int number2 = 0; // Second number to add
	
	do{
                 cout << "Enter first non-zero integer: "; // Prompts user for number1
	         cin >> number1; // Grabs the first integer inputted
        } while (number1 == 0);

	do{
             cout << "Enter second non-zero integer: "; // Prompts user for number2
	     cin >> number2; // Grabs the second integer inputted
        }while (number2 == 0);

I know some teachers don't want you to initialize a var. with a value in it but personally I can't stand not giving it something right off the bat. Then you KNOW it's not going to get some crazy number and you can use the default number in checks you build into the code.

Anyways the above will just keep looping for each number until the user figures out how to enter a non-zero number.
 
When you get in to far more advanced programming, one thing that can bite you in the ass is how you initialize your variables - especially when you're working directly with memory (making your own types, etc.). During a types construction, it may or may not have a default value already assigned to it.

Declaring an integer with "int a;" only assigns a 4 byte piece of memory, referenced by the name "a". It does nothing. Whatever is already in that memory is what that variable will equate to.

Whereas, the std::string type constructor explicitly sets the value of the string to be a null string ("").

It's just good coding practice to always initialize a variable to a known value, or alternatively have as few lines of code between declaration and value assignment. If you note, I have practically no logic between my variable declaration and assigning it a value. I probably should have still assigned a default value to it, (0 would have been safe, in this case), but I did not. It's mostly that you have a conscious decision on how that variable is used between declaration and value assignment - i.e. it shouldn't be. Good coding practices like always initializing your variable to a value will help you avoid such mistakes.

For example, say you have 6 bytes of memory as such that previously had data, but that data is now out of scope and unused:

| 0x00 | 0x30 | 0x00 | 0x00 | 0x00 | 0x00 |

Now you ask for an integer, and lets say the machine assigns the first 4 bytes of memory to it. If you were to check the value of that integer, it would be "3145728" as the type constructor for integers does nothing to assign a default value. Certainly that's not what you're expecting it to be, or isn't useful to you - thus you should assign a meaningful value as quickly as possible alongside a variable declaration, or even do it as part of the declaration (int a = 0;)
 
Last semester ended up going rather well, although the teacher ended up being completely incapable of teaching.

Unfortunately, he's the only teacher at the school, so I have him again this semester lol.

Stuck on a few bits of code tho.

Goal: To write a program that deals 5 "cards", and notifies of pairs.

My issue: I'm stuck trying to find the proper if command for the pairs, and how to interpret the constant char I'm using.

Header:

Code:
// Fig. 9.25: DeckOfCards.h
// Definition of class DeckOfCards that 
// represents a deck of playing cards.

// DeckOfCards class definition
class DeckOfCards
{
public:
   DeckOfCards(); // constructor initializes deck
   void shuffle(); // shuffles cards in deck
   void deal(); // deals cards in deck
   void pair(); // Matches pairs in deck
private:
   int deck[ 4 ][ 13 ]; // represents deck of cards
}; // end class DeckOfCards

Main function:
Code:
// Member-function definitions for class DeckOfCards that simulates
// the shuffling and dealing of a deck of playing cards.
#include <iostream>
using std::cout;
using std::left;
using std::right;

#include <iomanip>
using std::setw;

#include <cstdlib> // prototypes for rand and srand
using std::rand;
using std::srand;

#include <ctime> // prototype for time
using std::time;

#include "DeckOfCards.h" // DeckOfCards class definition

// DeckOfCards default constructor initializes deck
DeckOfCards::DeckOfCards()
{
   // loop through rows of deck
   for ( int row = 0; row <= 3; row++ )
   {
      // loop through columns of deck for current row
      for ( int column = 0; column <= 12; column++ )
      {
         deck[ row ][ column ] = 0; // initialize slot of deck to 0
      } // end inner for
   } // end outer for
   
   // seed random number generator
   srand( static_cast< unsigned >( time( 0 ) ) ); 
} // end DeckOfCards default constructor

// shuffle cards in deck
void DeckOfCards::shuffle()
{
   int row; // represents suit value of card
   int column; // represents face value of card

   // for each of the 52 cards, choose a slot of the deck randomly
   for ( int card = 1; card <= 52; card++ ) 
   {
      do // choose a new random location until unoccupied slot is found
      {
         row = rand() % 4; // randomly select the row (0 to 3)
         column = rand() % 13; // randomly select the column (0 to 12)
      } while( deck[ row ][ column ] != 0 ); // end do...while

      // place card number in chosen slot of deck
      deck[ row ][ column ] = card;
   } // end for
} // end function shuffle

// deal cards in deck
void DeckOfCards::deal()
{
   // initialize suit array
   static const char *suit[ 4 ] = 
      { "Hearts", "Diamonds", "Clubs", "Spades" };

   // initialize face array
   static const char *face[ 13 ] = 
      { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", 
      "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

   // for each of the 52 cards
   for ( int card = 1; card <= 5; card++ ) // Modified dealt number
   {
      for ( int row = 0; row <= 3; row++ )
      {
         // loop through columns of deck for current row
         for ( int column = 0; column <= 12; column++ )
         {
            // if slot contains current card, display card
            if ( deck[ row ][ column ] == card ) 
            {
               cout << setw( 5 ) << right << face[ column ] 
                  << " of " << setw( 8 ) << left << suit[ row ]
                  << ( card % 2 == 0 ? '\n' : '\t' );
            } 
			// end if
         } // end innermost for
      } // end inner for
   }
   
} // end outer for

Additional source file:

Code:
// Card shuffling and dealing program.
#include "DeckOfCards.h" // DeckOfCards class definition

int main()
{
   DeckOfCards deckOfCards; // create DeckOfCards object
   
   deckOfCards.shuffle(); // shuffle the cards in the deck
   deckOfCards.deal(); // deal the cards in the deck
   
  return 0; // indicates successful termination
} // end main

Now, what I've attempted::

Adding

Code:
if (*face == *face)
{
	cout << "You have a pair of" << *face << "!" << std::endl; 
}

to the main.cpp

As well as
Code:
if ("Aces" == "Aces" || "Two" == "Two")
{
	cout << "You have a pair of" << *face << "!" << std::endl; 
}
[code]
etc.

Any recommendations or see any clear errors? I can't see where I'm going wrong, the book is insufficient, and I haven't found any real clear explanations online for what I'm looking for.

Thanks for all the help guys :)

- Kyle
 
It's been a while since I've done any real c programming besides playing with plugins for MQ2.

But I don't believe you can just compare *face to *face without giving an index of what you are comparing. I believe you are going to need a counter to count the number of each face as you deal.

The way you have it set up I'd do something like this for your deal function (note you may need to initialize the counter array to 0, I can't remember offhand):

Code:
void DeckOfCards::deal()
{
   // initialize suit array
   static const char *suit[ 4 ] = 
      { "Hearts", "Diamonds", "Clubs", "Spades" };

   // initialize face array
   static const char *face[ 13 ] = 
      { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", 
      "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

   int counter[13];

   // for each of the 52 cards
   for ( int card = 1; card <= 5; card++ ) // Modified dealt number
   {
      for ( int row = 0; row <= 3; row++ )
      {
         // loop through columns of deck for current row
         for ( int column = 0; column <= 12; column++ )
         {
            // if slot contains current card, display card
            if ( deck[ row ][ column ] == card ) 
            {
               cout << setw( 5 ) << right << face[ column ] 
                  << " of " << setw( 8 ) << left << suit[ row ]
                  << ( card % 2 == 0 ? '\n' : '\t' );
               counter[column]++;
            } 
			// end if
         } // end innermost for
      } // end inner for
   }
   for (int hand=1; hand<=13; hand++)
   {
        if (counter[hand] >= 2)
             cout << "You have a pair of" << face[hand] << "!" << std::endl;
   }
} // end outer for

That might need some modifications and could have a syntax error for all I know atm since I can't test it right now, but I think it will give you an idea of what I'm talking about.

Also using it the way I did there, if you have 3 of a kind or 4 of a kind, it will list it as a pair. You can change the if to a switch and check for 2, 3, or 4 and cout an appropriate message if you want.

Another thing to point out, is it supposed to deal 5 new cards every time you call deal? Or do you only need it to work for the first hand dealt from a shuffled deck? Because the way it is right now, every time you call deal, it's going to deal the same 5 cards off the top of the shuffled deck. Assuming you ever changed it to run for longer than just one iteration of shuffle / deal.
 
Last edited:
I'd prefer it to be a fresh 5 cards every deal, but I know it's not required for the overall solution. Also, I did plan to put a loop in there to do repetitive runs for multiple deals.

I appreciate the help Dev, once I get done with class I'll be able to sit down and play around with it a bit more.

Thanks again guys!

-Kyle