The basics of programming in c++ for beginners

A task: counting numbers

We introduce an integer. Count the number of times the software in its decimal notation includes some figures, let us say 3. That's all the condition. For example: 123 -> 1; 54321345 -> 2; 3333 -> 4 etc.

The task is very simple … at the high school level. But in order, to do the task is not quite so trivial – complicate:
– offer several (as much as possible) different ways to implement;
– for each realization reduce code writing so, that it, more concise as possible.

Solutions (It is where to turn because of the simplicity of the task, solutions can be very, Fill your):

It all fits into the solution one operator do … while. But, pay attention to, what “injected integer” – This input is always a string, representing a number (Here the trick in the formulation of the problem). Then:

Or so:

Or even so:

And that's how it looks:

P.S. This problem is a good illustration of the fundamental programming principles, what any the problem can be solved many and very various ways.

8 thoughts on “A task: counting numbers

  1. I decided to like this

  2. You are welcome, can anyone explain in human language, why use in the solution “unsigned”? I searched for information on Google, but my brain was not ready for the influx of too scary words.

    1. because perhaps the testing system is typing a lot of numbers. Therefore, for numbers such as length 10 degree 16 or more the keyword 'unsigned' is used.

  3. #include
    using namespace std;
    int main() {
    unsigned long long int a, c;
    int k=0;
    cin>>a;
    while(a>0) {
    c=a;
    a/=10;
    if(c==3) k ;
    }
    cout<<k;
    return 0;
    }

  4. #include
    #include
    using namespace std;
    int main()
    {
    string file;
    getline(cin, file);
    int sum = 0;
    for (int z = 0; from < file.size(); with ++)
    {
    if (file[from] == '3')
    {
    sum++;
    }
    }
    cout << sum;
    return 0;
    }

  5. Solution with error checking:
    #include
    #include

    using namespace std;

    int main()
    {
    string aboba = “”;
    char bebra = 0;
    int even = 0;

    cout << "Input nubmer: ";
    getline(cin, they are afraid);
    cin.clear();

    for (int i = 0; i < aboba.size(); i )
    {
    if (!(isdigit(they are afraid[i])))
    {
    cout << "Error: You did not enter a number, or there were other characters in the number." << endl;
    return 1;
    }
    }

    cout <> bebra;

    if (!(isdigit(bebra)))
    {
    cout << "Error: You did not enter a number, or there were other characters in the number." << endl;
    return 1;
    }

    for (int i = 0; i < aboba.size(); i )
    {
    if (they are afraid[i] == bebra)
    {
    even++;
    }
    }

    cout << "Numbers found: " << even << endl;

    return 0;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *