I need to write a program that takes an integer as input and outputs it with its digits spaced. The algorithm works fine but prints the digits in reverse order. To get the original order, I used a for loop. The problem is that it prints nothing.
#include <iostream>
using namespace std;
int countDigit(int n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
int main()
{
int Num ;
int sum = 0;
int arr[100];
cout <<"Enter an integer: " ;
cin >> Num ;
int c = countDigit(Num) ;
for (int i = c; i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
cout << " Your digits:";
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
return 0;
}
My issue is here
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
It prints nothing. What could be the problem ?
The input used is 1234
The expected output is 1 2 3 4
For starters the function countDigit is wrong.
int countDigit(int n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
It returns 0 for the valid number 0 that has one digit.
The function can look the following way
size_t countDigit( int n, int base = 10 )
{
size_t count = 0;
do
{
++count;
} while ( n /= base );
return count;
}
In this loop
for (int i = countDigit(Num); i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
the variable Num was changed. So in the next loop
for (int x = 1 ; x <= countDigit(Num) ; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
it will not have the original value You need to use an intermediate variable to make the calculation.
Also take into account that the use can enter a negative number.
EDIT: After you updated your code then you also need to move the output of the sum from the loop
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
}
cout << sum ;
And instead of the large integer array it is better to use an object of the type std::string.
Here is a demonstrative program
#include <iostream>
#include <string>
size_t countDigit( int n, int base = 10 )
{
size_t count = 0;
do
{
++count;
} while ( n /= base );
return count;
}
int main()
{
const int Base = 10;
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
size_t count = countDigit( num );
std::string s( count, ' ' );
int sum = 0;
for ( ; count-- != 0; num /= Base )
{
int digit = num % Base;
if ( digit < 0 ) digit = -digit;
s[count] = digit + '0';
sum += digit;
}
std:: cout << "Your digits: ";
for ( const auto &c : s ) std::cout << c << ' ';
std::cout << '\n';
std::cout << "The sum of digits is " << sum << '\n';
return 0;
}
Its output might look like
Enter an integer: -123456789
Your digits: 1 2 3 4 5 6 7 8 9
The sum of digits is 45
Another approach is to write a recursive function that outputs digits and returns the sum of digits.
#include <iostream>
unsigned int recursive_sum( long long int n, long long int base = 10, std::ostream &os = std::cout )
{
long long int digit = n % base;
if ( digit < 0 ) digit = -digit;
unsigned int sum = digit + ( ( n /= base ) == 0 ? 0 : recursive_sum( n ) );
os << digit << ' ';
return sum;
}
int main()
{
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
unsigned int sum = recursive_sum( num );
std::cout << '\n';
std::cout << "The sum of digits is " << sum << '\n';
return 0;
}
Again the program output might look like
Enter an integer: -123456789
1 2 3 4 5 6 7 8 9
The sum of digits is 45
This gives the expected output. I assigned countDigit(Num) to c and wrote the sum to outside the loop.
int main()
{
int Num ;
int sum = 0;
int arr[100];
cout <<"Enter an integer: " ;
cin >> Num ;
int c = countDigit(Num); //edit 1
// extracts the digits
for (int i = c; i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
cout << "Your digits with spaces: ";
// reverses the order
for (int x = 1 ; x <= c ; x++)
{
cout << arr[x] << " " ;
}
cout << endl << "The sum of the digits is: " << sum ; // edit 2
return 0;
}
Here's a shorter version:
#include <concepts>
#include <cstdio>
#include <string>
template <std::integral T>
void printDigits(T const i) {
for (auto const ch : std::to_string(i)) {
std::printf("%c ", ch);
}
std::fflush(stdout);
}
LIVE
Here's a take that uses strings.
#include <iostream>
#include <string>
int main()
{
std::string input;
std::size_t location;
std::cout << "Enter an integer: ";
std::getline(std::cin, input);
std::stoi(input, &location); // Don't care about the integer, just location
if (location != input.length()) {
std::cout << "Invalid Entry: Non-integer entered\n";
return 1;
}
for (auto i : input) {
std::cout << i << ' ';
}
// Here's a one liner that requires <algorithm>
// std::for_each(input.begin(), input.end(), [](auto i) { std::cout << i << ' '; });
std::cout << '\n';
}
I don't care about an integer at all. I can validate that only digits were entered and quit early if not. The only loop I need is for printing.
stoi() can return the integer, but I don't care about the integer. I just want to know how many characters were converted, and I learn that by feeding it the output argument location. Checking that location is the same as the string length ensures that only digits were entered. No decimal points, no extra letters, just numbers.
The caveats are that this might not fit into your requirements if this is an assignment. It also requires C++11, which is surprisingly not a given yet (for assignments, I get the industry arguments).
Related
Q) Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N.
For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120
Problem: I am able to print the result,but not able to print like this :
let n = 5
Output : 1 * 2 * 3 * 4 * 5 = 120;
My Code:
# include <bits/stdc++.h>
using namespace std;
int Factorial (int N)
{
int i = 0;int fact = 1;
while (i < N && N > 0) // Time Complexity O(N)
{
fact *= ++i;
}
return fact;
}
int main()
{
int n;cin >> n;
cout << Factorial(n) << endl;
return 0;
}
I am able to print the result,but not able to print like this : let n
= 5 Output : 1 * 2 * 3 * 4 * 5 = 120;
That's indeed what your code is doing. You only print the result.
If you want to print every integer from 1 to N before you print the result you need more cout calls or another way to manipulate the output.
This should only be an idea this is far away from being a good example but it should do the job.
int main()
{
int n;cin >> n;
std::cout << "Factorial of " << n << "!\n";
for (int i =1; i<=n; i++)
{
if(i != n)
std::cout << i << " * ";
else
std::cout << n << " = ";
}
cout << Factorial(n) << endl;
return 0;
}
Better approach using std::string and std::stringstream
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cin >> n;
stringstream sStr;
sStr << "Factorial of " << n << " = ";
for (int i = 1; i <= n; i++)
{
if (i != n)
sStr << i << " * ";
else
sStr << i << " = ";
}
sStr << Factorial(n) << endl;
cout << sStr.str();
return 0;
}
For Example, I have number 1 + 6 + 7 + 12 + 13 + 18+.....+ n (n is the input from users which represent the number of elements) the index of this number starts from 1 by this it means​ that if the index is an odd number (1,3,5...) I want to increment the element at that index by 5 and if the index is an even number I want to increment the element at that index by 1 until I reach the of n number of elements. What I want is to sum all those numbers.
Sorry, It may hard to understand because of my poor English So let me write some of my C code here:
using namespace std;
int i, n, result = 0;
cout << "Input number to sum: ";
cin >> n;
// Finding result
for (i = 0; i <= n; i++){
if (i % 2 == 0) {
result +=i;
} else {
result += i * 5;
}
}
// Make last number have equal sign "1+6+7+12 = 36"
for (i = 0; i <= n; i++){
if (i == n) {
cout << i..?? << "=";
} else {
cout << i..?? << "+";
}
}
// Print result out
cout << result;
return 0;
}
Combine the computation with the output (I usually preach the opposite, but in this case it actually simplifies matters).
for (int i = 0; i <= n; i++)
{
int value = i % 2 == 0 ? i + 1 : i + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
I agree with the molbdnilo that combining calculations and output in this case, simplify the code.
I don't agree with the algorithm, though, given OP's description.
In the following the calculations are repeated to output the result
#include <iostream>
int main()
{
int n;
std::cout << "Input number to sum: ";
std::cin >> n;
auto update = [] (int i) { return i % 2 == 0 ? 1 : 5; };
int result = 0;
int value = 0;
for (int i = 0; i < n; i++)
{
value += update(i);
result += value;
}
std::cout << '\n';
for (int i = 0, value = 0; i < n; i++)
{
value += update(i);
std::cout << (i > 0 ? " + " : "") << value;
}
std::cout << " = " << result;
}
Testable here.
I agree with molbdnilo's answer. However the algorithm some changes.
The index starts from 1 , so value check for i in for loop should be
for (int i = 0; i < n; i++)
while updating the values, increment should be done on value and not on i.
Here is my solution:
using namespace std;
int main()
{
int i, n, result, value = 0;
cout << "Input number to sum: ";
cin >> n;
for (i = 0; i < n; i++)
{
value = i % 2 == 0 ? value + 1 : value + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
return 0;
}
Testable here
I am stuck in one of the problem related string in c++. My logic has worked well for some test cases, but not for all test cases. Please suggest me the actual logic of the following question::
I am given a string s of n character, comprising only of A's and B's . I can choose any index i and change s(i) to either A or B. Find the minimum no. Of changes that you must make to string S such that the resultant string is of format : AAAAA.....BBBBB. In other words, your task is to determine minimum no. of changes such that string s has x no. of A's in the beginning, followed by the remaining (n-x) no. of B's.
my code::
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, i, flag = 0;
cin >> n;
string str;
cin >> str;
int cnt = 0, cnt1 = 0;
for (i = 0; i < str.length(); i++) {
if (str[i] == 'A') {
cnt++;
} else {
cnt1++;
}
}
int pp = 0;
//cout << cnt << " " <<cnt1;
for (i = 0; i < cnt; i++) {
if (str[i] == 'B') {
pp++;
}
}
for (i = cnt; i < n; i++) {
if (str[i] == 'A' && str[i - 1] != 'A') {
pp++;
}
}
cout << pp << endl;
}
}
For example: AAB = 0 changes, BABA= 2 changes , AABAA= 1 changes
How to approach this question. Do respond!!!
I wrote the following code to compute the number of changes needing to order a string containing unorderd A e B according to the order that shall be "A[...A]B[...B]". (function countChanges).
The algorithm (countChanges) used to count modifications acts in three steps:
Step 1: counts how much 'A' chars are in the string (cnt).
Step 2: scans how much 'B' chars are in the first cnt chars of the string increasing a counter (sum) for each encounterd 'B'.
Step 3: scans how much 'A' chars are in the remaining chars of the string after the 2nd step increasing a counter (sum) for each encountered 'A'.
At the end of the function sum is the expected result.
The code also computes and executes the minimum number of swaps needing to obtain the string ordered according to the requirement.
The code contains two evaluation functions (the code under the main):
cntChanges. It computes the needing number of changes (The code gives the result as foreseen changes).
executeSwaps. It performs swaps on the string, counts them and may or may not show the steps performed.
Code result:
Do you have a code composed of A and B? [y]es/[n]o/[I] do it/[q]uit y
Insert your code? BABA
Do you want to print swap steps? [y]es/[n]o y
Input: BABA
Step 1 BABA swap(3,0) ==> AABB
Result AABB performed with 1 swap - foreseen changes 2
--
Do you have a code composed of A and B? [y]es/[n]o/[I] do it/[q]uit n
How much codes do you want to generate? 5
What's your preferred length for all generated codes? 10
Do you want to print swap steps? [y]es/[n]o y
Input: AAAAABAABB
Step 1 AAAAABAABB swap(7,5) ==> AAAAAAABBB
Result AAAAAAABBB performed with 1 swap - foreseen changes 2
--
Input: ABBABAAABA
Step 1 ABBABAAABA swap(9,1) ==> AABABAAABB
Step 2 AABABAAABB swap(7,2) ==> AAAABAABBB
Step 3 AAAABAABBB swap(6,4) ==> AAAAAABBBB
Result AAAAAABBBB performed with 3 swaps - foreseen changes 6
--
Input: AAABBAABBB
Step 1 AAABBAABBB swap(6,3) ==> AAAABABBBB
Step 2 AAAABABBBB swap(5,4) ==> AAAAABBBBB
Result AAAAABBBBB performed with 2 swaps - foreseen changes 4
--
Input: BABAABBABB
Step 1 BABAABBABB swap(7,0) ==> AABAABBBBB
Step 2 AABAABBBBB swap(4,2) ==> AAAABBBBBB
Result AAAABBBBBB performed with 2 swaps - foreseen changes 4
--
Input: AAABAABAAA
Step 1 AAABAABAAA swap(9,3) ==> AAAAAABAAB
Step 2 AAAAAABAAB swap(8,6) ==> AAAAAAAABB
Result AAAAAAAABB performed with 2 swaps - foreseen changes 4
--
The code:
#include <iostream>
#include <ctime>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
unsigned int executeSwaps(string &x, bool printSteps);
unsigned int cntChanges(const string& x);
unsigned int cntChangesJarod42(string const &x);
unsigned int cntChangesDamien(string const &x);
void questionToStart(int &c, size_t &cl, char &ync, char &ynps, string &x);
string generateCode(size_t n);
const char char1='A';
const char char2='B';
int main(void)
{
srand(static_cast<unsigned int>(time(nullptr)));
int c;
size_t cl;
char ync='n';
char ynps='n';
string x;
x.clear();
do {
questionToStart(c,cl,ync,ynps,x);
if (ync == 'q')
break;
for(int i=0;i<c;i++) {
unsigned int cnt=0;
if (ync=='n') {
x=generateCode(cl)
}
/* unsigned int fc2 = cntChangesJarod42(x);
unsigned int fc1 = cntChangesDamien(x);*/
unsigned int fc3 = cntChanges(x);
cout << "Input: " << x << endl;
cnt=executeSwaps(x, (ynps=='y')?1:0);
cout << "Result " << x << " performed with "
<< ((cnt>0)?to_string(cnt):"no")
<< " swap"
<< ((cnt>1)?"s ":" ") << " - foreseen changes " << fc3 << endl << "--" << endl;
/* << "foreseen changes (#Damien) " << fc1
<< " - foreseen changes (#Jarod42) " << fc2
<< endl << endl;*/
}
} while(ync != 'q');
return 0;
}
unsigned int cntChanges(const string& x)
{
const char * s;
unsigned int cnt=0,sum=0,i;
if (x.empty())
return 0;
s=x.c_str();i=0;
// count char1
while(*(s+i))
if (*(s+i++) == char1)
cnt++;
/* verify how much elements, from start to cnt,
* are different than char1 (equal to char2).
*/
for(i=0;i<cnt;i++)
if (*(s+i)==char2)
sum++;
cnt=static_cast<unsigned int>(strlen(s));
/* verify how much of the remaining elements
* are different than char2 (equal to char1).
*/
for(;i<cnt;i++)
if (*(s+i)==char1)
sum++;
return sum;
}
// #Jarod42
unsigned int cntChangesJarod42(const string& s)
{
if (s.empty()) { return 0; }
std::vector<std::size_t> switch_count(s.size());
{ // Count 'B' before index
unsigned int sum = 0;
std::size_t i = 0;
for (auto c : s) {
switch_count[i++] += sum;
sum += c == 'B';
}
}
{ // Count 'A' after the index
unsigned int sum = 0;
std::size_t i = 0;
for (auto c : std::string(s.rbegin(), s.rend())) {
switch_count[s.size() - 1 - i++] += sum;
sum += c == 'A';
}
}
return static_cast<unsigned int>(*std::min_element(switch_count.begin(), switch_count.end()));
}
// #Damien Algorithm
unsigned int cntChangesDamien (string const &x)
{
size_t n = x.length();
int cntCh_1 = 0, cntCh_2 = 0;
// there's nothing to swap!! :p
if (n < 2)
return 0;
for (size_t i = 0; i < n; ++i) {
if (x.at(i) == char1) {
cntCh_1++;
} else {
// x.at(i) is equal to char1
cntCh_1 = min (cntCh_2, cntCh_1);
// Now the foreseen swap are equal to cntCh1
cntCh_2++;
}
}
return static_cast<unsigned int>(std::min (cntCh_2, cntCh_1));
}
unsigned int executeSwaps(string &x, bool printSteps)
{
unsigned int cnt =0;
size_t apos=0;
size_t bpos=0;
// cout << "Start: " << x << " " << apos << " " << bpos << endl;
do {
apos=x.find_last_of(char1);
if (apos == string::npos)
break;
bpos=x.find_first_of(char2);
if (bpos == string::npos)
break;
if (apos>bpos) {
++cnt;
if (printSteps) {
cout << "Step " << cnt << " " << x << " swap(" << apos << "," << bpos <<") ==> ";
}
x.at(bpos)=char1;
x.at(apos)=char2;
if (printSteps)
cout << x << endl;
}
} while(apos>bpos);
return cnt;
}
string generateCode(size_t n)
{
string x;
x.clear();
size_t i,cb=0;
char ch;
if (n==0) {
n=rand()%10;
}
for (i=0;i<n-1;i++) {
ch = ( char1 + (rand()&1) );
if (ch == char2 )
cb++;
x +=ch;
}
if (cb==n-1) {
ch=char1;
} else if (cb==0) {
ch=char2;
} else {
ch=( char1 + (rand()&1) );
}
x += ch;
return x;
}
void questionToStart(int &c, size_t &cl, char &ync, char &ynps, string &x)
{
int ex=1;
do {
ex=1;
cout << "Do you have a code composed of "<<char1 << " and " << char2 <<"? [y]es/[n]o/[I] do it/[q]uit ";
cin >> ync;
switch(ync) {
case 'n':
cout << "How much codes do you want to generate? ";
cin >> c;
cout << "What's your preferred length for all generated codes? ";
cin >> cl;
break;
case 'I':
c=10; cl=(rand()&7)+9;
cout << c <<" attempts with " << cl << " characters long strings will be executed" << endl;
break;
case 'y':
c=1;
cout << "Insert your code? ";
cin >> x;
cl = x.length();
break;
case 'q':
break;
default:
ex=0;
}
} while(!ex);
if ( ync != 'q' ) {
if ( ync != 'I' ) {
cout << "Do you want to print swap steps? [y]es/[n]o ";
cin >> ynps;
} else {
ynps = 'y';
ync = 'n';
}
cout << endl;
}
}
As state by Tfry,
you might count the number of switch needed to have
XBBB
AXBB
AAXB
AAAX
which is the number of 'B' before the index + number of 'A' after the index.
Then take the minimum:
std::size_t count_switch_for_ab(const std::string& s)
{
if (s.empty()) { return 0; }
std::vector<std::size_t> switch_count(s.size());
{ // Count 'B' before index
int sum = 0;
std::size_t i = 0;
for (auto c : s) {
switch_count[i++] += sum;
sum += c == 'B';
}
}
{ // Count 'A' after the index
int sum = 0;
std::size_t i = 0;
for (auto c : std::string(s.rbegin(), s.rend())) {
switch_count[s.size() - 1 - i++] += sum;
sum += c == 'A';
}
}
return *std::min_element(switch_count.begin(), switch_count.end());
}
Demo.
The solution can be found in a simple loop, considering a 2-state process.
A state corresponds to the fact that for the given index, we decide to be in the A part or the B part. The transition from B state to A state is not allowed.
The corresponding number of changes up to index i can then be calculated iteratively.
For index i, let us call countA[i] the number of changes to get A only until index i, and let us call countB[i] the optimal number of changes up to i, assuming that somewhere before i, or at i time, we decided that the following part of the last string will containt B only.
It the current character s[i] is equal to A, then
countA[i] = countA[i-1]
countB[i] = countB[i-1] + 1
If the current character is B, then
countA[i] = countA[i-1] + 1
countB[i] = min (countB[i-1], countA[i-1])
if the last equation, countB[i] = countB[i-1] corresponds to the case that the transition to B state already occurs, and
countB[i] = countA[i-1] corresponds to the case that the transition occurs now.
In practice, we don't need an array to update countA and countB.
Here is the code:
#include <iostream>
#include <string>
int nb_changes (const std::string &s) {
int n = s.size();
if (n < 2) return 0;
int countA = 0, countB = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == 'A') {
countB++;
} else {
countB = std::min (countA, countB);
countA++;
}
}
return std::min (countA, countB);
}
int main() {
std::string s;
s = "AAB";
std::cout << "number of changes for " << s << " is " << nb_changes(s) << "\n";
s = "BABA";
std::cout << "number of changes for " << s << " is " << nb_changes(s) << "\n";
s = "AABAA";
std::cout << "number of changes for " << s << " is " << nb_changes(s) << "\n";
}
I am kinda a newbie in C++ and I am a having hard time with a situation.
My task is to create a decimal to [2:9] number system conversion. I am dividing the input number to the base and then, taking the quotient as the divident and continuing the same process.
For example if the decimal number is 149 and that number is calculated on base 2, my output is like this:
Remainder 1
Remainder 0
Remainder 1
Remainder 0
Remainder 1
Remainder 0
Remainder 0
Remainder 1
The outputs are the elements of an array named remainder.
And then I have to merge these array elements in reverse order (1001010) to form the new base number as an integer. How can I do this? I am stuck at this point. The above output is just the part of my output. The number will be prompted from user and it is going to be calculated on bases from 2 to 9. So, array lenghts may change (I have the code for the digit calculation, I have no issues with that).
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int merge(int a[]);
int main(int argc, char*argv[])
{
int dNumber;
int system[8];
for (int i = 0; i < 8; i++)
{
system[i] = i + 2;
}
cout << "Please enter the decimal base number which you want to use in the conversion: " << endl;
cin >> dNumber;
int permanent = dNumber; //to keep the input number intact as it changes through the loops (used in line 53)
int ndigits[8]={1};
for (int i = 0; i < 8; i++)
{
while(dNumber > pow(system[i], ndigits[i]))
{
ndigits[i] ++;
}
}
int dNumberNew = dNumber;
for (int k = 0; k < 8; k++){
for (int i=0; i>=0; i++)
{
int Remainder[i], quotient[i];
Remainder[i] = dNumberNew % system[k];
quotient[i] = dNumberNew / system[k]; // since the variables are integers, this line does not assign decimals and finds the quotient easily.
cout << dNumberNew << " " << system[k] << "'e bolundu. " << "Sonuc " << quotient[i] << " Kalan " << Remainder[i] << " cikti." << endl;
dNumberNew = quotient[i];
if (quotient[i] == 0)
{
break;
}
}
cout << "(" << dNumber << ")" << "_(" << system[k] << ")" << "=" << endl;
cout << "" << endl;
dNumberNew = permanent;
}
}
Here is a function you can use as DecimalToBinary converter, analyze the code yourself
string toBinary(unsigned long long* arr, unsigned long long size) {
string answer;
for (unsigned long long i = 1; i < size; i++) {
string binaryNum = "";
while (arr[i] >= 1) {
binaryNum = static_cast<char>((arr[i] % 2) + '0') + binaryNum;
arr[i] = arr[i] / 2;
}
answer += binaryNum + " ";
}
return answer;
}
I have with my code. This is about recursion. I have to create function digitAppear( int findDigit, int value) where value is the user input, and findDigit is single digit number ranging from 0 to 9. The function read user input and return each digit number from the user input and count how many times each digit number occurs in the user input. For example, if I type 1234 then the output say 1 appear 1 time, 2 appear 1 time and so on (I hope my explanation is clear) The problem is the only run once and can only return 1 value.
#include <iostream>
using namespace std;
int countOccurence(int, int);
int main()
{
int findDig;
int value;
int n = 0;
cout << "Please enter a positive number: " << endl;
cin >> value;
cout << "The value is " << value << endl;
while ((value < 0) || (value > 9999))
{
cout << "Invalid value. Please try again!" << endl;
cout << "Please enter a positive number: " << endl;
cin >> value; //you need this here, otherwise you're going to be stuck in an infinite loop after the first invalid entry
}
//process the value
for (findDig = 0; findDig < 9; findDig++)
{
cout << endl;
cout << cout << "the " << findDig << "appear in digit " << value << " is " << countOccurence(findDig, value) << " times" << endl;
}
//countOccurance(findDig, value);
//cout
}
int countOccurence(int findDig, int value)
{
int n = value;
while( n > 10 )
{
int a = n / 10; //eliminate the right most integer from the rest
int aa = n % 10; //separate the right most integer from the rest
int b = a / 10; //eliminate the second integer from the rest
int bb = a % 10; //separate the second integer from the rest
int c = b / 10; // eliminate the third integer from the rest
int cc = b % 10; //separate the third integer from the rest
for (findDig = 0; findDig < 9; findDig++)
{
int i = 0;
if (findDig == aa) // see if the findDigit value is equal to single digit of b;
{
i += 1;
} else
{
i += 0;
}
return i;
if (findDig == bb)
{
i += 1;
} else
{
i += 0;
}
return i;
if (findDig == cc)
{
i += 1;
} else
{
i += 0;
}
return il;
}
}
}
The problem is my function countOccurence() doesn't seems right. I wonder if there a way to do it. I have been stuck with this for days and I really appreciate your input, thank you.
To use recursion, you must think about the problem in a different way.
The easiest way of thinking about how you could incorporate recursion into the function is the process of 'peeling off' each number.
A very simple way of doing this is by looking at the first/last digit in the number, compute that, then call itself on the remainder of the number.
Hopefully you can figure out the code from there.
If you mean that function digitAppear itself has to be recursive then it can look the following way as it is shown in the demonstrative program below
#include <iostream>
#include <cstdlib>
size_t digitAppear( int findDigit, int value )
{
return ( std::abs( value ) % 10u == std::abs( findDigit ) ) +
( ( value /= 10 ) ? digitAppear( findDigit, value ) : 0 );
}
int main()
{
int i = 0;
for ( int x : { 0, 11111, 1234, 34343 } )
{
std::cout << "There are " << digitAppear( i, x )
<< " digit " << i
<< " in number " << x
<< std::endl;
++i;
}
return 0;
}
The program output is
There are 1 digit 0 in number 0
There are 5 digit 1 in number 11111
There are 1 digit 2 in number 1234
There are 3 digit 3 in number 34343
Of course you may rewrite function main as you like for example that it would count each digit in a number.