Reputation: 878
I have a simple quastion. I have this C# code:
static void Main(string[] args)
{
int num1, i, j, x, y;
Console.WriteLine("enter number");
num1=int.Parse(Console.ReadLine());
for (i=1; i<=num1; i++){
for (j=1; j<i+1; j++) {
Console.Write(i);
}Console.Write("\n");
}
for (x=num1; x>=0; x--){
for (y=0; y<x; y++) {
Console.Write(x);
}Console.Write("\n");
}
Console.ReadLine();
}
The middle line is repeat twice
Which print triangle from numbers. The problem is that the middle line is repeated twice. My question is how can I change the loop, so the middle line numbers will repeat twice? Wish for help, thanks!
Upvotes: 1
Views: 2168
Reputation: 236188
Console.Write("enter number: ");
int num = Int32.Parse(Console.ReadLine());
Enumerable.Range(1, num)
.Concat(Enumerable.Range(1, num - 1).Reverse())
.Select(x => String.Join("", Enumerable.Repeat(x.ToString(),x)))
.ToList()
.ForEach(line => Console.WriteLine(line));
Upvotes: 2
Reputation: 152491
Because both for loops include num1
as an inclusive condition:
for (i=1; i<=num1; i++){
// num1 is the last number in this loop
}
for (x=num1; x>=0; x--){
// num1 is the first number in this loop
}
Change the first loop to stop BEFORE num1
:
for (i=1; i<num1; i++){
Upvotes: 2
Reputation: 486
static void Main(string[] args)
{
int num1, i, j, x, y;
Console.WriteLine("enter number");
num1=int.Parse(Console.ReadLine());
for (i=1; i<num1; i++){
for (j=1; j<i+1; j++) {
Console.Write(i);
}Console.Write("\n");
}
for (x=num1; x>=0; x--){
for (y=0; y<x; y++) {
Console.Write(x);
}Console.Write("\n");
}
Console.ReadLine();
}
Upvotes: 1
Reputation: 10533
Uhh change
for (x=num1; x>=0; x--){
to
for (x=num1-1; x>=0; x--){
Upvotes: 3