Okay, so this is the program I was assigned to write.
"Delete k-th digit from the natural number n, counting the digits starting from the last digit in the number."
I've written a complete program, but the problem is that when I input the number and the digit I wanted deleted, it won't show me the result. I input 123 for 'n' and 2 for 'k', so I should get 13, but instead I get a blank. I'm not sure where my mistake is as I've tried changing the program at least 10 times, but the problem remains unsolved. Here is the program. Also, for the record, I am only allowed to use functions such as while, do while, and if else. Those are the restrictions for this assignment. I can't use 'for'.
//Deleting k-th digit from 'n' number
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, k, d, i=0;
double m=0, a, b;
cout<<"Enter a value for n: "<<endl;
cin>>n;
cout<<"Enter the digit (k) that you want deleted: "<<endl;
cin>>k;
I thought that 'i' being equivalent to 'k' would mean that the loop would stop... was I wrong? Should I change the condition of the while to something else?
i == k is the condition of your if statement. Which means it will enter if i==k, and do whats in the statement. Which is continue, this doesnt leave the while loop.
If you wanted to leave the loop if i==k you should use break, or change how the logic overall is performed.
Infinite loops altogether arent typically the best idea. You could easily have your while loops terminating condition be:
1 2 3 4 5 6
while(i != k)
{
//do the things
i++
}
Eliminating the if else altogether and the infinite loop. Because so long as k is greater than 0 i will eventually equal it.
Thank you! I actually got an answer.. so the problem was that I was using continue, but now my issue is that I'm not actually getting the CORRECT answer.. I don't think that what I'm using under the while statement is correct.
#include <iostream>
#include <math.h>
int main()
{
int n = 0 , r = 0 , m = 0 , k = 0 , i = 0 ;
std::cin >> n ;
std::cin >> k ;
while( n > 0 )
{
r = n % 10 ;
n = n / 10 ;
if( r == k )
{
--i ;
r = 0 ;
}
m += r * pow( 10 , i ) ;
++i ;
}
std::cout << m << '\n' ;
return 0;
}