I'm having a hard time writing a correct LCV for the while loops in my program. Also, could someone provide an explanation as to why my program freezes after it prompts the user to input an integer?
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int num, num2, sum = 0;
int div, num3, count = 0;
cout << "Enter an integer: ";
cin >> num;
cout << endl; //This is where it freezes.
count = 0;
while (num != 0)
{
num2 = num / 10;
count++; //Needs appropriate LCV
}
num = num2;
do
{
div = static_cast<int>(pow(10, --count)); //Not sure
num3 = num2 / div; //if this is the
num2 = div % div; //right equation
cout << num3 << ' ';
sum = sum + num3;
}
while (count != 0); // I think this is
cout << "The sum of the integers is: " << sum // the only right
<< endl; // right thing about
// the whole program
return 0;
}
while (num != 0)
{
num2 = num / 10;
count++; //Needs appropriate LCV
}
This is an endless loop. Your num is never going to get back to 0 to exit the loop. num variable never changes, so it has no chance to exit the first loop at all! Put cout<<count<<endl; in there, and you'll see. I think that's seriously it...That's the only issue I can see, although I'm not sure if the --count is right syntax. I always used x+=1 or x-=1, etc.
I'll be honest, I'm not sure what num!= 0 is trying to accomplish.
while (num != 0)
{
num2 = num / 10;
count++; //Needs appropriate LCV
}
it means that while the number is not zero the loop will execute, but I don't know how I could get the number to go back to zero. I'm currently trying to com up with a better while statement. I'm trying to get the program to be able to read any integer and put out each digit as a single number and also out the sum of all the integers. For example: 23947823 would output; 2 3 9 4 7 8 2 3 and also the sum of them.