Decimal to Binary conversion using recursion [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
#include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;
long int d2b(int);
static long int binary=0;
static int i=0;
long int d2b(int num)
{
if(num!=0)
{
binary=binary+pow(10,i)*(num%2);
d2b(num/2);
i++;
}
return(binary);
}
int main()
{
int num;
long int binary_ans=0;
cout<<"Enter the number.";
cin>>num;
binary_ans=d2b(num);
cout<<"Ans = "<<binary_ans;
getch();
return(0);
}
I am using Dev C++ compiler and this code doesnt seem to work. Can somebody please run this code on their compilers and give me a feedback. Also if the code seems incorrect to you, please tell me the reason why you think so.

A correct implementation with neither static variables nor globals (both are just plain evil, try to avoid them at any cost) that gives you the desired output can be something as simple as
#include <iostream>
long int d2b(int x)
{
return x ? (x%2 + 10*d2b(x/2)) : 0;
}
int main()
{
std::cout << "enter a number:" << std::endl;
int input;
std::cin >> input;
long int binary = d2b(input);
std::cout << "ans = " << binary << std::endl;
}
Take note that, as we're using int to store our binary representation, the whole thing breaks for any input > 524287.
This of course assumes your integer is 64bit.
The largest number you can write using only 0 and 1 is int x = 1111111111111111111, which when you interpret it as binary translates to 524287.
For 32bit and even 16bit integers this range is significantly lower.
Also have a look at: Are global variables bad?

Obviously i++ must be done before the recursion takes place.
#include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;
long int d2b(int);
static long int binary=0;
static int i=0;
long int d2b(int num)
{
if(num!=0)
{
binary=binary+pow(10,i)*(num%2);
i++;
d2b(num/2);
}
return(binary);
}
int main()
{
int num;
long int binary_ans=0;
cout<<"Enter the number.";
cin>>num;
binary_ans=d2b(num);
cout<<"Ans = "<<binary_ans;
_getch();
return(0);
}
Get used to debugging your code!

As mentioned earlier, you can use it also in this manner:
#include<iostream>
#include<math.h>
using namespace std;
string d2b(int);
static string binary;
string d2b(int num)
{
if(num!=0)
{
binary= to_string(num%2) + binary;
d2b(num/2);
}
return(binary);
}
int main()
{
int num;
string binary_ans="";
cout<<"Enter the number.";
cin>>num;
binary_ans=d2b(num);
cout<<"Ans = "<<binary_ans;
getch();
return(0);
}

Related

Sum of first and last digit of a number [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
The problem is to find sum of first and second digit of a number.
If number is smaller than 10 then print number itself.
I wrote this code but i don't know why output is wrong.
#include <iostream>
using namespace std;
int main()
{
int t,a,n,l;
cin>>t;
while(t--)
{
cin>>n;
if(n<10)
{
cout<<n;
}
else
{
a=n%10;
l=n/10;
cout<<a+l<<endl;
}
}
return 0;
}
The reason your solution is wrong because n/10 won't give you the first digit :)
If this is for a question for competitive programming(since you're taking in t test cases), I'll suggest taking input as a string assuming that input is always a valid int.
std::string s;
cin >> s;
if (s.size() == 1) std::cout << s << std::endl;
else std::cout << int(s.front() - '0') + int(s.back()-'0') << std::endl;
extracting of required digits is wrong in your solution.
Please find solution for adding first and last digit of a number at
https://onlinegdb.com/Byro9hCMI or below:
its small and hence pasting it here as well:
#include <iostream>
using namespace std;
int main()
{
int first, last, number;
cin>>number;
first = number % 10;
while((number = number/10)>0)
{
last = number;
}
cout << endl << first+last << endl;
return 0;
}
Two Add first two digit (unit and tens)at https://onlinegdb.com/SJXNThAzI or below:
#include <iostream>
using namespace std;
int main()
{
int first, second, number;
cin>>number;
first = number % 10;
number = number/10;
second = number %10;
cout << endl << first+second << endl;
return 0;
}

How to repeat the string in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have to write a program in which integer value is entered from user and the string has to be displayed that many times. But I am getting errors.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
cout << string(N, "Well Done");
return 0;
}
Note: I am not permitted to use a loop in this assignment.
If you may not use a loop, you may use goto to get around the restriction:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
{
int i = 0;
goto test;
begin:
cout << "Well Done";
++i;
test:
if (i < N)
goto begin;
}
return 0;
}
Note that goto is widely considered bad practice.
EDIT2: IN THE ORIGINAL ASKER's COMMENTS, LOOPS OF ANY KIND ARE PROHIBITED IN THIS ASSIGNMENT.
Use recursion.
void printN(int n, string s) {
if (n <= 0) return;
cout << s << endl;
printN(n-1, s);
}
Then you can call this from your main program as follows:
printN(userInput, "Hi my name is ricky bobby");
EDIT: just saw you haven't learned recursion yet. Look up this term, and familiarize yourself with it. This is a way to do iteration without looping (this is the most simplistic way I can describe it)
std::string does not have a constructor that repeats a string N times (it does have one for repeating a single character N times, though). What you need is a loop instead, eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
for (int i = 0; i < N; ++i)
cout << "Well Done";
return 0;
}

I feel like my code is right, but the execution is still wrong, why?

I'm trying to make a digit counter with loop. I am quite sure that my code is right, but the execution is different than what I wanted to. Can someone tell me where I did it wrong?
Here is my code
#include <iostream>
using namespace std;
int main()
{
long long x,y;
int i;
cout << "Input X : ";
cin >> x;
i=0;
y=x;
while(x>0){
x=x/10;
i++;
cout <<i;
}
cout <<y<<" is made up of "<<i<<" digits."<<endl;
return 0;
}
So, the execution is :
Input X : 5000
12345000 is made up of 4 digits
Why the ouput is not the same as the input? What is wrong?
The 1234 in front of 12345000 is due to you having the cout <<i statement at the end of your while loop.
#include <iostream>
using namespace std;
int main()
{
long long x,y;
int i;
cout << "Input X : ";
cin >> x;
i=0;
y=x;
while(x>0){
x=x/10;
i++;
}
cout <<y<<" is made up of "<<i<<" digits."<<endl;
return 0;
}
Now your code will run properly

How to write c++ functions by returning parameters?

Need help in figuring out how to write function and returning parameters. Wrote the question below and answer from solution manual, not sure how to write the function though very confused :(
Here's what I've tried:
#include <iostream>
using namespace std;
char Answer;
void max();
void main () {
int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
print();
system("pause");
}
There's a few problems with the question. In the answer you gave there are 3 parameters (int nb1,nb2, nb3) but the question says there are two. Also there should be an int before each identifier if this is C++, is this C++? Also it's not specified what to do if the parameters are equal (e.g. max(6, 6)) though presumably this isn't important. Here's what I'd do:
int max(int nb1, int nb2)
{
if(b1 > b2)//this could be b1 >= b2, I think that's what your solution manual has
return b1;
else
return b2;
}
EDIT in response to comment:
Given what you have done so far this is what I would change to get things to work. The following has somethings you should try to avoid
int main() and return 0 should be used instead of void main()
system("pause") should not be used instead you could wait for a user to press enter
But it seems like you have enough to get your head around without the above two concerns :-)
You had the function print you should use cout << "text goes here" << endl; when programing in C++ (C uses printf). I'm guessing your hard-coding the input so set the values of num1 and num2 to whichever two numbers to be compared.
#include <iostream>
using namespace std;
int max(int nb1, int nb2)
{
if(nb1 > nb2)
return nb1;
else
return nb2;
}
void main()
{
int num1 = 6;//put one number to be compared here
int num2 = 8;//put second number to be compared here
int result = max(num1, num2)
cout << result << endl;
system("pause");
}

A large input from console in C++

I need to enter more than 10000 integers, smaller than max long long directly into console. The console accepts something more than 9000 of them using getline(cin,string). Inputting them one by one slows my program dramatically. Is there anyway that I can override the console's getline maximum input?
[Edited to include the OP's comment:]
#include <iostream>
using namespace std;
int main()
{
long long n=0,i=0,a,b;
cin>>n;
for(i=0;i<n;i++) { cin>>a>>b; cout<<a+b<<endl; }
return 0;
}
This code gives a "Time Limit Exceeded" error on the task when more than 10000 integers are inputted.
EDIT:
After rewriting the code with help from one answer:
#include <iostream>
static inline int error(int n) { std::cerr << "Input error!\n"; return n; }
int main()
{
long long a,b,n; // number of colours and vertices
if (!(std::cin>> n)) { return error(1); }
for (int i = 0; i != n; ++i)
{
if (!(std::cin >> a>>b)) { return error(1); }
std::cout << a+b << "\n";
}
}
Now it gives me a Runtime Error(NZEC) on the test case with 10000+ integers
EDIT 2:
I found something that would help me but it is only in C# : How to read very long input from console in C#?
Couldn't find an equivalent in C++
By default iostreams are synchronized with C stdio functions and that makes them too slow for algorithmic contests. Disable synchronization at the beginning of your program:
std::ios::sync_with_stdio(false);
You can take input from file. All you have to do is to redirect the stdin like this
if (!freopen("filename.txt", "r", stdin)) {
cout << "Could not open file";
return 1;
}
long long n=0,i=0,a,b;
cin>>n;
for(i=0;i<n;i++) { cin>>a>>b; cout<<a+b<<endl; }
return 0;