Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print numbers in the following pattern with dotnet

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading