Saturday, May 22, 2010

How to make C++ program loop again.?

I wrote a C++ program for a class, but I'm having some trouble. How do you get the program to run again?





e.g.


1. Ask for 2 numbers to multiply


2. Multiply the 2 numbers


3. Ask if user would like to multiply another 2 numbers





This is my code (It's long, so I'll have to break it up):





#include %26lt;stdafx.h%26gt;


#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;





using namespace std;





int main()


{


//declare variables


char fname [31] = "";


char lname [31] = "";


int age = 0;


char id_num [7] = "";


char classification [9] = "";


double gpa = 0;


char address [51] = "";


char birthdate [12] = "";


char zip [7] = "";


char city [31] = "";


char state [15] = "";


char phone [20] = "";


char city_state_zip [56] = "";


char rerun ;

How to make C++ program loop again.?
To make a function you need to specify:





%26lt;return type%26gt; %26lt;function name%26gt; (%26lt;parameters%26gt;) {


// code goes here


return %26lt;return_type%26gt;


}





Usually you want to have a function prototype, this would simply be:





%26lt;return type%26gt; %26lt;function name%26gt; (%26lt;parameters%26gt;);





As an example, I'll give you a sample source of the example you gave above (read 2 numbers, multiply and loop)





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





int multiply(int a, int b); // function prototype





int main() {


string resp = "y";


do {


int a, b;


cin %26gt;%26gt; a %26gt;%26gt; b;


cout %26lt;%26lt; "Product is " %26lt;%26lt; multiply(a,b) %26lt;%26lt; "\n";


cout %26lt;%26lt; "Do you want to continue? (y/n) ";


cin %26gt;%26gt; resp;


} while (resp == "y");


return 0;


}





// function definition


int multiply(int a, int b) {


return a*b;


}





Of course, in a real application you wouldn't make useless functions such as multiply() since it's simpler to just type a*b than to call multiply() every time. (Didn't actually compile to test but should work)
Reply:you can have a function for getting the input.


another function for modifying the input


and another one for the output.





this way it will be easier to find errors in the code and makes it more pleasing to the eye :-)
Reply:The quick way is to put the main part of your program inside a loop that terminates when the user enters a particular value.





A better way is to take your code, make a separate function out of it, and call that function from within such a loop.





Hope that helps.


No comments:

Post a Comment