2

To provide context, I'm very new to C#, and am currently working my way through Wiley's Software Development Fundamentals. The question is the following:

You are developing a library of utility functions for your application. You need to write a method that takes an integer and counts the number of significant digits in it. You need to create a recursive program to solve the problem. How would you write such a program?.

I think I have created a solution to this question, however I'm unsure if this is correct as I don't know how to return a value stating "this is how many significant digits".

class Program
{
    public static void Main(string[] args)
    {
        dig(55535);
    }
    public static int dig(int x)
    {
        if (x < 10)
        {
            return 1;
        }
        else
        {
            return 1 + dig(x / 10);
        }
    }
}
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Jon
  • 33
  • 6
  • What do you mean by *"however I'm unsure if this is correct as I don't know how to return a value stating "this is how many significant digits"."*? – EZI Jun 26 '15 at 22:03
  • 1
    That there is an output to the console saying "55535 has 5 significant digits". Or have I missed the point of the exercise? – Jon Jun 26 '15 at 22:04
  • 5
    So you can write the recursive function but are not able to use `Console.WriteLine` ? Are you sure that it is **your** code? – EZI Jun 26 '15 at 22:06
  • How can you not see that the answer is 5? #confused – leppie Jun 26 '15 at 22:07
  • I can use the Console.Writeline, but where? I've tried this before the if function, and after the "return 1 + dig(x / 10). – Jon Jun 26 '15 at 22:08
  • Recursive program is not the bes option check this http://stackoverflow.com/questions/72209/recursion-or-iteration – DanielVorph Jun 26 '15 at 22:08
  • What result do you expect? What is the actual result when you run your code? – Code-Apprentice Jun 26 '15 at 22:08
  • 4
    @DanielVorph Telling a student to not solve a problem according the instructor's guidelines isn't very constructive. – Code-Apprentice Jun 26 '15 at 22:09
  • @Jon Do you understand what a "return value" is? Do you know how to use the return value after you have called a function? – Code-Apprentice Jun 26 '15 at 22:10
  • I can see that the answer is 5, and if I use a breakpoint, x has the digits 55535 at the end of the program. To be honest I'm unsure if I need to Console.Writeline the result, or is the code shown above sufficient as an answer to the question? I understand what return value does, terminates that part of the code and returns to the calling method i.e. the if statement. – Jon Jun 26 '15 at 22:12
  • @Jon If I make a guess, you even don't know how to calculate it for a number entered by user. – EZI Jun 26 '15 at 22:13
  • No unfortunately I don't, I'm very new to this :), and trying to self-teach (Going round in circles as you can see by my confusion) – Jon Jun 26 '15 at 22:15
  • 1
    Your requirement is to write a function that count how many significant digits are present in an integer. Are you able to determine if the `dig` function is a correct answer to your requirement? (Test, test, test) Nowhere there is a requirement to write it down somewhere. So, in this particular case your main function is just used as a test to verify the entry point of dig and you can add here a simple WriteLine to check the result but it is not required. – Steve Jun 26 '15 at 22:21
  • wait. Up vote for what? `Console.WriteLine()`?. Duplicate question and very simple answer that can be find in google. and some people down vote questions that are clear and is not easy to find solution. I just dont get it! – M.kazem Akhgary Jun 26 '15 at 22:23

6 Answers6

2

You should change your Main function and use Console.WriteLine to write the result to the output window.

public static void Main(string[] args)
{
    // storing the return value of the function in to a variable
    int result = dig(55535); 

    //print the variable
    Console.WriteLine(result);

    //or call Console.WriteLine(dig(55535));
}
BJ Myers
  • 6,617
  • 6
  • 34
  • 50
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
  • 1
    Thank you so much, this had me stuck. Got it working now. Cheers for the patience. – Jon Jun 26 '15 at 22:19
1

You need Console.WriteLine() in your Main() method to print to the console.

Pass your call to dig() as a parameter to Console.WriteLine.

Mark T
  • 785
  • 6
  • 13
0
class Program
{
    public static void Main(string[] args)
    {
        int value = 55535;
        Console.WriteLine("Number {0} has {1} significant digits", value, dig(value));
    }
    public static int dig(int x)
    {
        // Exactly as you have it
    }
}
abelenky
  • 63,815
  • 23
  • 109
  • 159
  • I think this kind of downvoting and voting to delete an answer is kind of bullying in community and I will report it to the moderators – Hamid Pourjam Jun 26 '15 at 22:18
  • 6
    Some people think homework-type questions are off-topic and shouldn't be answered, and they will downvote. Most of these questions are *terrible*, but this one is actually decent, OP showed his effort and is not asking for a plain solution. Yes, it's trivial but meets the guidelines IMHO, I see no reason it shouldn't be answered. – Lucas Trzesniewski Jun 26 '15 at 22:19
  • http://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions – Hamid Pourjam Jun 26 '15 at 22:31
0

While answers like “look at the return value in the debugger” or

Console.WriteLine("Number {0} has {1} significant digits", value, dig(value));

will answer the question you posed, this is not a good strategy for the future. It may be feasible to have a person inspect a single output for a single variable, but this does not scale to projects involving hundreds (or thousands) of functions with thousands (or billions) of possible return values.

Eventually you will have to implement automated tests; this is where the computer tests your output and alerts you when something goes wrong.

The topic is a large one, but you can implement a simple example like so:

public static void Main(string[] args
{
    var tests = new []
    {
        new []{0, 1},
        new []{1, 1},
        new []{10, 2},
        new []{100, 3}
    };

    foreach (var p in tests)
        if (dig(p[0]) != p[1]) Console.WriteLine("dig({0}) == {1}", p[0], p[1]);
}
Dour High Arch
  • 21,513
  • 29
  • 75
  • 90
0

This does not use recursion, but is a solution to the more general case of counting significant digits in a number. This uses loose rules since it's not possible to know how many trailing zeroes after a decimal point are intended when dealing with non-strings.

public int CountSignificantDigits(decimal num)
{
    if (num == 0) return 1;
    if (num < 0) num = -num;
    while (num < 1m) num *= 10;
    string numStr = num.ToString().Replace(".","");
    for (int i = numStr.Length-1; i > 0; i--)
    {
        if (numStr[i] != '0')
            return numStr.Length - (numStr.Length - i) + 1;
    }
    return 1;
}
Derrick
  • 2,502
  • 2
  • 24
  • 34
0

As perhaps already noted, the original code does not account for the integer trailing zeros. This might be an another approach.

static void Main(string[] args)
{
    do
    {
            Console.Write("Number = ");
            int number = Int32.Parse(Console.ReadLine());
            int abs_number = Math.Abs(number);

            int numTrailingZeros = 0;
            bool check_ntz = true;

            int ndigits = GetSignificantDigits(abs_number, ref check_ntz, ref numTrailingZeros);

            if (numTrailingZeros == 0)
                Console.WriteLine("Number of signficant figures: {0}", ndigits);
            else
                Console.WriteLine("Number of signficant figures: between {0} and {1}", ndigits, ndigits + numTrailingZeros);

            Console.WriteLine();
            Console.WriteLine("Press ESC to terminate, any other to continue.");
            Console.WriteLine();
    }
    while (Console.ReadKey(true).Key != ConsoleKey.Escape);
    return;
}

static int GetSignificantDigits(int n, ref bool check_ntz, ref int ntz)
{
    if (n < 10)
        return 1;
    else
    {
        int new_n = (int)(n / 10);

        if (check_ntz)
        {
            if (n % 10 == 0)
            {
                ntz++;
                return GetSignificantDigits(new_n, ref check_ntz, ref ntz);
            }
            else
            {
                check_ntz = false;
                return 1 + GetSignificantDigits(new_n, ref check_ntz, ref ntz);
            }
        }
        else
            return 1 + GetSignificantDigits(new_n, ref check_ntz, ref ntz);
    }
}

enter image description here

Cobek
  • 33
  • 5