0

I am a newbie and currently taking as a subject data structures and algorithms. I have posted the function I'm currently working on down below. It works the problem is I would like to ensure I'm meeting the professors intent. I'm supposed to write a recursive and nonrecursive function to print out nonnegative integers in binary. The functions should not use bitwise operations. The function below is my recursive function. Please advise me if I am going in the wrong direction.

#include <iostream>
 
using namespace std;
 
void binequ( int, int );
 
int main()
{
	int posint;
	cout << "The purpose of this program is to convert\na nonnegative integer into binary form.\n"; 
	cout << "\nEnter a positive Integer: ";
	cin >> posint; 
 
	cout << "\nThe Binary equivalent is: ";
	binequ( posint, 2 ); 
	cout << endl; 

	system("PAUSE");
 
	return 0; 
 } 
 
void binequ(int num, int base)
{
 
	if (num > 0)
	{
		binequ(num/base, base);
		cout<< num % base;
 
	}
 
}
4
Contributors
7
Replies
8
Views
7 Years
Discussion Span
Last Post by program_helm
0

>It works the problem is I would like to ensure I'm meeting the professors intent.
I can't claim to know what your professor intended, but I'd say you're on the right track.

0

You are on the right track. Consider making the name of that function
better. Also you might want to make the base case more explicit like this :

void convertDecimalToRadix(int num, int base)
{
	if( num == 0 ) return; //base case
 	
	binequ(num/base, base);
	
	cout<< num % base; 
}
0

I appreciate your help here is the new code.

#include <iostream>
 
using namespace std;
 
void binaryEquivalent(int num, int base);
 
int main()
{
	int posint;
	cout << "The purpose of this program is to convert\na nonnegative integer into binary form.\n"; 
	cout << "\nEnter a positive Integer: ";
	cin >> posint; 
 
	cout << "\nThe Binary equivalent is: ";
	binaryEquivalent( posint, 2 ); 
	cout << endl; 

	system("PAUSE");
 
	return 0; 
 } 
 
void binaryEquivalent(int num, int base)
{
 
	if (num == 0)return;
	{
		binaryEquivalent(num/base, base);
		cout<< num % base;
	
	}
 
}
0

I'm going to start on the nonrecursive solution next. Am I correct in assuming that I can keep the main function the same and alter the binary equivalent function? And that function will be the long process of conversion?

0

>Am I correct in assuming that I can keep the main function
>the same and alter the binary equivalent function?

Yes. But make a copy of it first, otherwise you'll lose the recursive version. ;)

>And that function will be the long process of conversion?
It'll use a loop, obviously, but that doesn't necessarily mean it's the "long process". :icon_rolleyes:

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.