samedi 21 octobre 2017

Write this code with switch in c#

I'm new to programming, especially when it comes to C#, but I'm studying it this year and I realize I do like it and really want to comprehend it. However, our teacher leaves us to learn it on our own. Ok, no problem with that, the internet is as amazing as it is.

So I've got this exercise as homework:

==== Calculate the sum, product of digits not equal to 0 and the number of digits of an integer.====

Thing is, I only know how to make it with do while and if and it works perfectly, but she wants us to do it also with SWITCH and this is where I'm lost because I just don't know how to build the cases (it's fine when case is 0, but how do I write the case when digit or n != to 0?!)

I really need some help with this one and would appreciate sosososo much any help given! Also, could you provide also an explanation? Thank you so much! :D

        int n, s = 0, p = 1, d = 0, digit;
        Console.Write("Number n : ");
        n = Convert.ToInt32(Console.ReadLine());

        if (n == 0)
            p = 0;
        do
        {
            digit = n % 10;
            s += digit;
            if (digit != 0)
                p *= digit;
            d++;
            n /= 10;
        } while (n != 0);
        Console.WriteLine("The sum of the digits is: {0} ", s);
        Console.WriteLine("The product of the digits not equal to 0 is : {0} ", p);
        Console.WriteLine("The number of the digits is: {0}", d);
        Console.ReadKey();

Aucun commentaire:

Enregistrer un commentaire