my code freezes whenever i enter 12-19.

#include <cmath>
#include <iostream>

using namespace std;

int main()
{


 int multiples;
 int answer;
 int square;
 int cube;
 int num;




 cout << "Please enter a positive number less than or equal to 20: ";\
 cin >> num;

do
{

 if(num >=20)
 cout << "Invalid number. Enter another one in range." << endl;
 cin >> num;

}while(num>0 && num <=20);

for(int num=1;num<=num;num++)
 {
 square = (num * num);
 cube = (num * num * num);
}

 cout << square << endl;
 cout << cube << endl;


return 0;
 system("pause");




}

I don't know about freezing, but it looks like it will be waiting for you to enter another number, regardless of whether the user enters one in the valid range or not.

You need a set of { } around the two statements following the if( num >= 20 ) inside the do..while.

And you need to look at the test for that do..while - that could keep a user that enters good input spinning there forever.

in fact something like:

while (num>=20)
{
    cout << "Invalid number. Enter another one in range." << endl;
    cin >> num;
}

Gets rid of the if statement all together.
Also if I read your code right you don't need the for loop at all just the 'square' and 'cube' statements.

Edited 3 Years Ago by tinstaafl

This article has been dead for over six months. Start a new discussion instead.