Home > Blockchain >  How do I input 2 variables in one line and count them in output?
How do I input 2 variables in one line and count them in output?

Time:11-14

Out of all activity I've been tasked with, this was by far one of the most challenging one.

I am an IT student, ie a beginner in the C language, and so far I've only been taught how to make use of while loops and if conditions. By this, we have to use these two in the following activity:

Count how many of a certain digit is present on a given number.

  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 (see sample input and output for example).

In short, a program that reads the first value and checks how many of this first value is present in the second value.

Supposed Input: 2 1242182
Expected Output: 3

As you can see, it counts how many 2s are present in the second value (1242182). The result is 3 since there are three 2s present in it.

I find it impossible to create a program that can read 2 values in one line just using if conditions and a while loop, but this was given by us from an official programming website.

It should look like this.

#include <iostream>
using namespace std;

int main() {

    int v1;
    cin >> v1;

    if (...) {
        ....
    }
        while (...) {
            ...
        }
    return 0;
}

Also, no using arrays.

CodePudding user response:

 #include <iostream>
 using namespace std; 

 int main() {
   int v1, v2; 
   cin >> v1 >> v2;
 }

CodePudding user response:

You need to get the two numbers, and then convert the second one to a string and iterate through that, checking it and incrementing.

#include <iostream>
#include <string>
using namespace std;
int main(){
    int number, count, digit;
    string num;
    cin >> number >> num;
    for(int i = 0; i < num.length(); i  ){
        digit = stoi(num[i]);
        if(number == digit){
            count  ;
        }
    }
    cout << "count: " << count << "\n";
}
  •  Tags:  
  • c
  • Related