Home > Net >  How to print numbers in the following pattern with dotnet
How to print numbers in the following pattern with dotnet

Time:04-01

I have a program in C# that takes an integer argument from the command line and prints number patterns from 1 to that number in the format below for a number like 5.

1
22
333
4444
55555

You can see that for each number, that number is printed the same time as itself, like for three its been printed ona single line three times, and so and so forth. I have tried to develop a function that multiplies an integer with a string with String.Concat(string param, int n) and returns that string to another function with a loop that prints the expected output to terminal. My code prints like below

11
22
33
44
55

for a sample integer input like 5. What am I doing wrong and what should I do to correct my loop so it gives me the expected output, Thank You.

Code

static string MakeALine(int k){
    //all this function does is to convert the integer argument to string and multiply it with itself and returns it
    return String.Concat(k.ToString,k);
}

//the function below contains a loop that should invoke the make a line correctly to achieve the desired output above
static string MakeLines(int arg){
    //the arg is the command line argument supplied 
    string outp="";
    //i have a problem in the loop below, please help
    for(int k=1;k<=arg;k  ){
        //call makeALine and pass k as argument and append to the return string
        outp =MakeALine(k) "\n";
    }
    return outp;
}

What am I doing wrong, Thanks.

CodePudding user response:

The problem is in the MakeALine method. You actually concat the number with itself, so for input 1 you actually get "1" "1".

Instead you should repeat the string representation of your number k times. For this you can use Enumerable.Repeat in the following way:

static string MakeALine(int k)
{
    return String.Concat(Enumerable.Repeat(k.ToString(),k));
}

CodePudding user response:

Try with this :

private static string makeLines(int k)
{
    string outPut = "";
    for(int i = 1 ; i < k 1 ; i  )
    {
        outPut  = string.Concat(Enumerable.Repeat(i, i))   "\n";
    }
    return outPut;
}
  • Related