4
\$\begingroup\$

It's a task from a C#-course I'm currently taking. The task is to write a method, which returns the first twenty Fibonacci-numbers.

I have done it the following way.

using System;
namespace CrashCourse
{
    public class Fibonacci
    {
        // ... The actual method 
        public static List<int> GetNumbers() {
            var numbs = new List<int> { 1, 1 }; // Provided. Not by myself.

            for (var i = 2; i < 20; i++) {
                var prev2 = numbs[i - 2];
                var prev1 = numbs[i - 1];
                numbs.Add(prev1 + prev2);
            }

            return numbs;
        }
    }
}


// Usage
var numbs = Fibonacci.GetNumbers();
foreach(var numb in numbs) {
    Console.WriteLine(numb);
}

What's your opinion about my coding concerning naming, style and algorithm?

What should I do differently and why?

\$\endgroup\$
1
  • \$\begingroup\$ Stretch your knowledge of C# and look at iterator methods and LINQ, specifically Take. \$\endgroup\$ Commented Jun 26, 2023 at 17:09

2 Answers 2

4
\$\begingroup\$

Welcome to CR.

The Good: Your indentation and spacing is decent enough. You separate the tasks of gathering the numbers and displaying the numbers into 2 different methods.

The Bad: The first comment // ... The actual method is utterly useless. The method GetNumbers() would be better suited to be named GetFirst20Numbers() as it is hardcoded to do just that.

In C#, the convention is to put the opening brace on a new line.

While your solution, most likely for homework or training, is very specific, I would suggest it is too specific. The more flexible and reusable solution would be to create a method that produces Fibonacci numbers, and let a calling method determine how many that should be. This could be done 1 of 2 ways: one would be to pass in an integer of the desired count, e.g. GetNumbers(20). The other would be to use an enumeration to produce the next Fibonacci number in a sequence. Each subsequent call would return 1 value.

\$\endgroup\$
2
\$\begingroup\$

What's your opinion about my coding concerning naming, style and algorithm?

algorithm

First twenty Fibonacci numbers commonly begin with 0,1,1..., not 1,1,2...

Perhaps OP is stuck with { 1, 1 }. A comment like "Provided. Not by myself." alone does not excuse this non-convention.

Code to your contract requirements, yet when they differ from convention, note it.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.