简体   繁体   中英

How do I set up a nested repetition?

With this code i can set up with for, where i select a number of rows and for each row the character + increases. But i do not know how i can program it to display on the first row the amount of + but on the second row and so on variable n asigned for rows, n-1 +, until the last row shows 1 +.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nästlade
{
    class nästlade
    {
        static void Main(string[] args)
        {
            Console.Write("Antal rader? ");
            string s = Console.ReadLine();
            int n = int.Parse(S);
            for (int i = 1; i <= n; i = i + 1)
            {
                for (int j = 1; j <= i; j = j + 1)
                    Console.Write("+");

                Console.WriteLine();
            }
        }
    }
}

Well it's relatively simple, you need to "inverse" your outer for-loop:

for (int i = n; i > 0; i = i - 1) 

and you are good to go.

as an aside, you can shorthand the j = j + 1 to j++; (and similar with j--; )

With n = 4 I expext following output:

++++
+++
++
+

Try to inverse your outer loop, ie:

for (int i = n; i > 0; i--)
{
    for (int j = 1; j <= i; j = j + 1)
        Console.Write("+");

    Console.WriteLine();
}

I think you want that first line prints n + ,second line n-1 + and so on. You can try..

for(int i=1;i<=n;i=i+1)
{
    for (int j = 1; j <= n-i; j = j + 1){
       Console.Write("+");
    }
    Console.WriteLine();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM