Hi everyone!I've started to learn C++ couple of months ago and having some trouble with the code i'm trying the write.. I have to write a function that converts every digit of the parameter to zero,except 2.And number of digits is unknown..
I made this but its's output is always 0.Even i enter a number that contains 2...I'll be glad if you could help..Thanks:)

#include<iostream>
using namespace std;


int convertNum(int n){

int digits=0;
int remainder;


for(int i=n;n!=0;n/=10)
digits=digits+1;

 


for(int j=1;j<=digits;j++){
n=n/10;
remainder=n%10;
if(remainder==2)
  remainder=2;
if(remainder!=2)
  remainder=0;

}

return remainder;

 
}

 

int main()
{
 int a;

 cout<<"Please enter a positive integer"<<endl;
 cin>>a;

cout<<"The converted version of "<<a<<" is ----> "<<convertNum(a);
 

return 0;
}

Recommended Answers

All 6 Replies

I'd be glad if you could read all the intro threads which describe how to post code.

What I could get out of your unformatted code was
if(remainder==2)
remainder=2;
if(remainder!=2)
remainder=0;
should be better :
if(remainder==2)
remainder=2;leave this away-->if it IS 2 why set it to 2 ?
if(remainder!=2) remainder=0;-->+-OK, because if you want to print 2 it will print 0

Lines 11,12. n is 0 after them and also i don't get why u use for not while and why u need that int i

ok,thanks for your help..
i'll fix it..

You say that you don't know the exact number of digits.
Then why not he input to the function be a string
such that

string convertNum(string num)
{
 //1.set counter to 0
 //2.Check if it is the end of the string(using counter's position).
 // 3.if yes goto goto step 4 
 //   else check if the character in the string is other than 2 
//    if yes, fill  a zero in the string
//increment the counter
// goto step 2 
//4.Display or return your string

}

Hope that i am not twisting the question.:twisted:

Thank you so much zalezog..I've made it:)..I used string and it's way much easier...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.