Search code examples
c#consoleconsole-applicationwindows-console

How to make output : 1 1 2 6 3 11 4 16 5 21


How to make output : 1 1 2 6 3 11 4 16 5 21. when i input start value = 1, and end value = 5

my code :

                Console.Write("input start value : ");
                start = int.Parse(Console.ReadLine());
                Console.Write("input end value : ");
                end = int.Parse(Console.ReadLine());
                Console.WriteLine("");

                for (int i = start; i <= end; i++)
                {
                    Console.WriteLine(i);
                    
                    for (int j = i; j <= end; j++)
                    {
                        int z = 1;
                        if (start != j)
                        {
                            z++;
                            Console.WriteLine((j * j) + z);
                        }
                        else
                        {
                            Console.WriteLine(start + " this j start value");
                        }
                    }
                }

Solution

  • So it's not entirely clear to me if the 5 is used both as an end value for the 1,2,3,4,5 as well as a difference value for the 1,6,11,16,21 but I'll assume yes. Here's an algorithm for you to implement (this looks like homework, so think of this as a tip - you'll get more out of doing the coding yourself but this is how you should approach any coding exercise: write out the algorithm in the language you think in then translate it to c#)

    • ask the user for a start value and convert to int
    • ask the user for an end value and convert to int
    • work out a variable called n which is end minus start
    • make a for loop starting at x = 0, running while x is less than or equal to n ; incrementing x by 1
    • print out startValue plus x
    • print out startValue plus (endValue times x)
    • loop around

    For a start and end of 1 and 5, the loop runs from 0 to 4. The first time the loop runs, x is 0, startValue is 1, so a 1+0 and a 1+(5*0) are printed - both 1. This continues up to the end value where x is 4, 4+1 is printed - which is 5 - and 1+(4*5) is printed - which is 21