Hi I have a algorithm I am trying to create but I cant seem to make it work?

This is what i have to do:

Describe an algorithm that takes integer n and digit d as the parameters, and computes the number of
occurrences of d in the decimal expansion of n.
For instance, if n = 65454871 and d = 4, then the algorithm should return 2.
Implement the corresponding function and test it

And here is my code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
	int co;   // variable count occurences AKA co
	int n, d;
	int rem;  // variable remainder

	cout << "Enter a decimal number: ";
	cin >> n;
	cout  << "Enter a diget to find: ";
	cin >> d;
	cout << "n= "<< n << "  d= "<< d << endl;

	while (n > 0) {
		rem = n % 10;
		n = n / 10;
		if (rem = d) {
			co++;
		}
	}
	return co;

	return 0;
}// end of main

Recommended Answers

All 2 Replies

>>int co; // variable count occurences AKA co
you have not initialize it to zero. So it now contains some junk values. When you increment it will increment the junk values so the output won't be proper.
Write : int co=0; // variable count occurences AKA co Also, the question says that you need to implement it through a function. While you have not defined any function to do that.
You should define a function which takes two integer arguments and return a integer

int occur_digit(int n, int d)
{
    //the definition goes here

}

Ah :) thankyou, will put in a value for co (0) + 'n yeah I gave up on writing it as a fuction when it started to stuff up but thanks :)

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.