Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 132,282 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,266 people online right now. Registration is fast and FREE... Join Now!




Challenge

 
Reply to this topicStart new topic

Challenge, Condensing this program

Renzokusen
post 14 Mar, 2008 - 09:11 PM
Post #1


New D.I.C Head

*
Joined: 11 Mar, 2008
Posts: 32

A couple of days ago on the forums somebody said they were making a math game that would give the user random equations to solve. I thought that might be a fun project to work on myself as a beginner so I've created something simliar to that idea. After finishing the addition part of the program I've noticed this program appears to be growing in size at an alarming rate. Since I'm not very well versed in the lang yet Anybody have any tips to shrink this code while retaining it effective or even optimizing it?
CODE

#include <iostream>
using namespace std;
bool bad_input;
int response = 0;
int firstNum = 0, secondNum = 0;
int correctAnswer = 0;
int playerAnswer = 0;
bool quit = false;

void check()
{
     bad_input= false;
     if(!cin) //check if input is correct
                        {
                          cout << "bad input\n\n";
                          bad_input= true;  //if not set token
                          cin.clear();         //take cin out of 'fail' state
                          cin.ignore(INT_MAX, '\n'); //ignore the input made earlier
                        }
}


void add()
{
     cout << "\n*****Addition*****\n\n";
     cout << " Solve: " << firstNum << " + " << secondNum << " = ? \n";
         correctAnswer = firstNum + secondNum;
     do
         {
          cin >> playerAnswer;
          check();
          }while(bad_input);
          
          if (playerAnswer == correctAnswer)
          {
                           cout << "\nCongratulations you're CORRECT!\n";
                           cout << " Solve: " << firstNum << " + " << secondNum << " = "<< correctAnswer << " \n";
                           cout << "\n Another probelm?  [1] Yes \t [2] No \n";
                                    do
                                      {
                                       cin >> response;
                                       check();
                                       }while(bad_input);
                                      if (response == 1)      
                                        {
                                                  firstNum = rand() % 101;
                                                  secondNum = rand() % 101;
                                                  add();
                                                  }
                                       else
                                       {
                                           cout << "\n***Exiting back to main menu***\n";
                                       }
          }
                           else
                               {
                                   cout << "Sorry you are incorrect would you like to try another addition problem? \n";
                                   cout << "\n[1] Yes \t [2] No \n";
                                    do
                                      {
                                       cin >> response;
                                       check();
                                       }while(bad_input);
                                      if (response == 1)      
                                        {
                                                  firstNum = rand() % 101;
                                                  secondNum = rand() % 101;
                                                  add();
                                                  }
                                       else
                                       {
                                           cout << "\n***Exiting back to main menu***\n";
                                       }
                                  
                                  
                               }
                              
}
  

                        
void menu()
{
    do{
        cout << "\nWhich mathmatical operation would you like to do?\n";
        cout << "     [1] addition\n";
        cout << "     [2] subtraction\n";
        cout << "     [3] multiplication\n";
        cout << "     [4] division\n";
        cout << "     [5] quit\n";
        bad_input= false;
        cin >> response;
        check();
    }while(bad_input); //keep doing this till input is ok
      
}


void calculate()
{
     switch (response)
     {
            case 1:
                 add();
                 break;
            case 5:
                 quit = true;
                 cout << "quit = true";
                 break;
            default:
                   cout << "default\n";
     }
}
    
                        
                          

int main()
{
    srand(time(0));
    while ( quit != true)
    {
          
          firstNum = rand() % 101;
          secondNum = rand() % 101;
          menu();
          calculate();
          
    }

    int t;
    cin >> t;
    return 0;
}
    


Mind you I only use global variables since I cannot seem to get transfering arugments to work correctly. I've also only finish the addition part to this nothing else. Good luck cause I have no idea how to shrink this. tongue.gif "Just trying to learn to optimize whatever I type so I figured learning to optimize as I go will benefit me more than learning it after the fact". I'm just doing this project for fun and to practice.
User is offlineProfile CardPM

Go to the top of the page

KYA
post 14 Mar, 2008 - 09:43 PM
Post #2


#include <nerd.h>

Group Icon
Joined: 14 Sep, 2007
Posts: 4,205



Thanked 50 times

Dream Kudos: 1150
My Contributions


Well, when you say optimize, I think of how to make the program run faster/better. If you are talking about cleaning the code up/making it shorter, that may or may not be optimization. The cleanest way would to have functions that randoming generate e problem (i.e. a seperate function for add, subtract, etc...)
User is offlineProfile CardPM

Go to the top of the page

Renzokusen
post 15 Mar, 2008 - 08:35 AM
Post #3


New D.I.C Head

*
Joined: 11 Mar, 2008
Posts: 32

ah, its just I just read somewhere smaller programs always run better than larger and you should strive to make your programs as small as possiable. Thanks
User is offlineProfile CardPM

Go to the top of the page

baavgai
post 15 Mar, 2008 - 11:10 AM
Post #4


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,960



Thanked 95 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


QUOTE(Renzokusen @ 15 Mar, 2008 - 12:35 PM) *

ah, its just I just read somewhere smaller programs always run better than larger and you should strive to make your programs as small as possiable. Thanks


No exactly smaller. More like less repetitive. However, getting rid of all the code you don't need is good. Never using globals if at all possible is good. Taking code you use over and over again and making it into a function or method will make things smaller.

Here's an example given the code you've offered.

This code gets used over and over. I'm not sure why you'd want it, but at least only do it once.
CODE

//check if input is correct
bool checkForBadInput() {
    if(!cin) {
        cout << "bad input\n\n";
        bad_input= true;  //if not set token
        cin.clear();         //take cin out of 'fail' state
        cin.ignore(INT_MAX, '\n'); //ignore the input made earlier
        return true;
    }
    return false;
}


Another thing you do a lot of is ask the user for int, to the point of making yes and no an int. And you use that funky checker. Make that a single call. Notice here, there's no need for globals. Our check returns a boolean.

CODE

int getUserIntWithCheck() {
    int response;
    do {
        cin >> response;
    } while(checkForBadInput());
    return response
}



One more bit of code to play with, the add function. There's a whole lot that could get fixed here, but the worst thing is that it calls itself. The next worse is that a lot of code repeats. Give the two functions we already made, the function might work like so:

CODE

void add() {
    // loop until they want to leave
    while (true) {
        int firstNum = rand() % 101;
        int secondNum = rand() % 101;
        int correctAnswer = firstNum + secondNum;
        cout << "\n*****Addition*****\n\n";
        cout << " Solve: " << firstNum << " + " << secondNum << " = ? \n";
        int playerAnswer = getUserIntWithCheck()
        if (playerAnswer == correctAnswer) {
            cout << "\nCongratulations you're CORRECT!\n";
        } else {
            cout << "Sorry you are incorrect\nThe correct answer is "<< correctAnswer << "\n";
        }
        cout << "\n Another probelm?  [1] Yes \t [2] No \n";
        if (getUserIntWithCheck()!=1) {
            cout << "\n***Exiting back to main menu***\n";
            return;
        }
    }
}


Again, never a need for a global.

Since you know you have other operations to test for, even add is overkill, you could very well write a single function with that looked like this.

CODE

bool solveProblem(char oper, int a, int b, int ans) {
    // sorry, you can to write this
}


Hope this helps.
User is offlineProfile CardPM

Go to the top of the page

skaoth
post 15 Mar, 2008 - 12:32 PM
Post #5


D.I.C Regular

Group Icon
Joined: 7 Nov, 2007
Posts: 337



Thanked 9 times

Dream Kudos: 100
My Contributions


QUOTE

ah, its just I just read somewhere smaller programs always run better than larger and you should strive to make your programs as small as possiable. Thanks


What you read may be trying to refer to what is called temporal locality. Generally when
a program runs, the code needs to be fetched from memory and placed
on the CPU's cache. Generally code that is executed has a very high probability
of being executed over again. The very fact that code is on the CPU's cache indicates
that that chunk of memory has recently been accessed and will most likely be accessed again.
Take a loop for example, the code within a loop
will execute N times. If the code can fit within the cache then it will fun much faster.
If the code can't then the CPU must go back out to memory is incurs a fairly
large runtime cost.
User is online!Profile CardPM

Go to the top of the page

Reply to this topicStart new topic
Time is now: 11/22/08 12:48AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month