Sunday, August 2, 2009

What is wrong with this C++ program?

#include%26lt;iostream%26gt;


using namespace std;





int main()


{


int num, bigNum, power, count;





cout %26lt;%26lt; "Enter an integer: ";


cin %26gt;%26gt; num;


cout %26lt;%26lt; "What power do you want it raised to? ";


cin %26gt;%26gt; power;


bigNum = num;


while (count++ %26lt; power);


bigNum *= num;


cout %26lt;%26lt; "The result is " %26lt;%26lt; bigNum %26lt;%26lt; endl;


return 0;


}

What is wrong with this C++ program?
count = 1 ; // probably count contains some junk value
Reply:Here are some of my few corrections with your program:


1.) Library header should have a ".h" extension


2.) avoid placing "int" in the main part of the program


3.) When you try to increment or decrement a variable, make sure that the variable already contains a value like 0 or 1.


4.)While loop's proper way of writing is while(condition){//statements}.


5.) A rule of thumb. Even if main() is a function, do not let main() return a value. Create another function to do the returning task.


6.) Put your "cout%26lt;%26lt;"The result is "%26lt;%26lt;bigNum%26lt;%26lt;endl;" outside the while statement so that it will not print the output while it is on the process mode. If you place the statement inside the while statement, the ways of reaching the result will be printed as well.





Here is my code (Extracted from your codes):





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





main()


{


int num, bigNum = 1, power, count = 0;





cout %26lt;%26lt; "Enter an integer: ";


cin %26gt;%26gt; num;


cout %26lt;%26lt; "What power do you want it raised to? ";


cin %26gt;%26gt; power;


while (count %26lt; power)


{


bigNum *= num;


count++;


}


cout %26lt;%26lt; "The result is " %26lt;%26lt; bigNum %26lt;%26lt; endl;


}





Hope it helps!

funeral flowers

No comments:

Post a Comment