Home > Mobile >  Detecting the first digit in the second digits?
Detecting the first digit in the second digits?

Time:12-06

Needle in the haystack. I'm a beginner in programming and we only learned a thing or two so far, barely reached arrays yet.

Input: 1 4325121
Output: 2
  1. Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer.
  2. Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result.

No arrays to be used here, only while loops and else-if conditions with basic coding knowledge and without the use of advanced coding.

CodePudding user response:

As you said, you need to keep it as simple as possible. Then this can be a solution:

#include <iostream>

int main()
{
    int first { };
    int second { };

    std::cin >> first >> second;

    int quo { second };
    int rem { };
    int count { };

    while ( quo > 0 )
    {
        rem = quo % 10;
        quo /= 10;

        if ( first == rem  )
        {
              count;
        }
    }

    std::cout << "Result: " << count << '\n';
}

CodePudding user response:

Using while loop

    #include <iostream>
    using namespace std;

    int main()
    {
        int a = 1;
        int b = 4325121;
        int count = 0;
        while(b > 0)
        {
            int m = b % 10;
            if(m == a)
            {
                count  ;
            }
            b /= 10;
        }
        cout << count;
        return 0;
    }

CodePudding user response:

Nice little problem:

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

// this is from https://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c 
bool is_number(const string& s)
{
    string::const_iterator it = s.begin();
    while (it != s.end() && std::isdigit(*it))   it;
    return !s.empty() && it == s.end();
}

int main() {

  while (true) {
    cout << "Input, two integer numbers, first one single cipher:" << endl;
    // read line of inupt
    string input;
    std::getline(cin, input);
 
    // split it into two words
    string word1, word2;
    istringstream ss(input);
    ss >> word1 >> word2;

    // check if both are integers
    if (!is_number(word1) || !is_number(word2)) {
      cout << "Input must be two integer values!" << endl;
      continue;
    }
    
    // make sure first input is just single cipher from 0...9
    if (word1.size() != 1) {
      cout << "First input must be a single cipher from 0 to 9." << endl;     
      continue;
    }

    // now count
    int count = 0;
    for (char character : word2) {
      if (character == word1[0]) {  // this is a "char" vs "char" comparison
        count  ; 
      }
    } 

    cout << "Result:" << count << endl;
  }
  
  return 0;
}
  •  Tags:  
  • c
  • Related