Well, a first thought arises. By the time the while loop begins, the only variables used so far are
n
and
k
. So we know those will need to remain outside the loop as at present. Similarly the variable
m
is used after the loop has ended, so that needs to remain outside too.
That leaves two other variables,
i
and
d
which belong inside the loop.
First step. Change
to
Next, just before the end of the loop body, there is a
++i;
That looks very much like the sort of thing that might be put into the for statement.
Now the for statement looks like this:
Also, move the declaration/initialisation of
i
into the same statement:
|
for (int i = 0; n>0; ++i)
|
Finally, for completeness, move the declaration of
d
inside the loop body since it is not used at all outside the loop.
That leaves the finished version:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
int n = 0;
int k = 0;
int m = 0;
cout << "Enter a value for n: " << endl;
cin >> n;
cout << "Enter the digit (k) that you want deleted: "<<endl;
cin >> k;
for (int i = 0; n>0; ++i)
{
int d = n%10;
n = n/10;
if (d==k)
{
--i;
d = 0;
}
m += d*pow(10,i);
}
cout << m << endl;
|
There, step by step and it should fall into place.