C# - why is this program giving me an error? [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am practicing for my programming exam and that's one of the exams. This program crashes after the first for loop and I can't figure out why. Please help!
int n = int.Parse(Console.ReadLine());
Console.WriteLine("{0}{1}{0}", new string('-', n / 2), new string('*', n + 2));
for (int i = 0; i < n - 1; i++)
{
Console.WriteLine("{0}*{1}*{0}", new string('-', n / 2), new string('-', n));
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(
"{0}{1}{2}{1){0}",
new string('-', ((n - 1) / 2) - i),
new string('*', 1 + 2 * i),
new string('-', n - 2 * i));
if (i < n / 2)
{
i++;
}
else
{
i--;
}
}

"{0}{1}{2}{1){0}",
Your string format is error,you need to change your {1) to {1},but it seems the code never end while input is 5! and other input also take another exception,can you explain what you want to do ?
"{0}{1}{2}{1}{0}",
I changed your code to a method now
static void PrintDemo(int num)
{
if (num < 0 || num % 2 == 0)
{
return;//do nothing
}
Console.WriteLine("{0}{1}{0}", new string('-', num / 2), new string('*', num + 2));
for (int i = 0; i < num - 1; i++)
{
Console.WriteLine("{0}*{1}*{0}", new string('-', num / 2), new string('-', num));
}
for (int i = 0; i < num; i++)
{
var t1 = Math.Abs(num / 2 - i);
var t2 = t1 * 2 + 1;
var t3 = (num * 2 + 1 - t1 * 2 - t2) / 2;
Console.WriteLine(
"{0}{1}{2}{1}{0}",
new string('-', t1),
new string('*', t3),
new string('-', t2));
}
}

The first error has been answered by Sky Fang
After that you will get ArgumentOutOfRangeException. For this you will have to change your second forloop condition to this
for (int i = 0; i < (n-1)/2; i++)
{
....
}
This is because when you are printing this is one of your arguments
new string('-', ((n - 1) / 2) - i)
Your second argument is becoming negative as i increases to (n-1)/2
Edit
Here is the final code. Adding Console.Readline will keep the console up and will enable you to see the output
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
Console.WriteLine("{0}{1}{0}", new string('-', n / 2), new string('*', n + 2));
for (int i = 0; i < n - 1; i++)
{
Console.WriteLine("{0}*{1}*{0}", new string('-', n / 2), new string('-', n));
}
for (int i = 0; i < (n - 1) / 2; i++)
{
Console.WriteLine(
"{0}{1}{2}{1}{0}",
new string('-', ((n - 1) / 2) - i),
new string('*', 1 + 2 * i),
new string('-', n - 2 * i));
if (i < n / 2)
{
i++;
}
else
{
i--;
}
}
Console.ReadLine();
}

Related

How can i optimize this problem while using only 3 for loops?

So the problem that I'm trying to optimize is to find and print all four-digit numbers of the type ABCD for which: A + B = C + D.
For example:
1001
1010
1102
etc.
I have used four for loops to solve this (one for every digit of the number).
for (int a = 1; a <= 9; a++)
{
for (int b = 0; b <= 9; b++)
{
for (int c = 0; c <= 9; c++)
{
for (int d = 0; d <= 9; d++)
{
if ((a + b) == (c + d))
{
Console.WriteLine(" " + a + " " + b + " " + c + " " + d);
}
}
}
}
}
My question is: how can I solve this using only 3 for loops?
Here's an option with two loops (though still 10,000 iterations), separating the pairs of digits:
int sumDigits(int input)
{
int result = 0;
while (input != 0)
{
result += input % 10;
input /= 10;
}
return result;
}
//optimized for max of two digits
int sumDigitsAlt(int input)
{
return (input % 10) + ( (input / 10) % 10);
}
// a and b
for (int i = 0; i <= 99; i++)
{
int sum = sumDigits(i);
// c and d
for (int j = 0; j <= 99; j++)
{
if (sum == sumDigits(j))
{
Console.WriteLine( (100 * i) + j);
}
}
}
I suppose the while() loop inside of sumDigits() might count as a third loop, but since we know we have at most two digits we could remove it if needed.
And, of course, we can use a similar tactic to do this with one loop which counts from 0 to 9999, and even that we can hide:
var numbers = Enumerable.Range(0, 10000).
Where(n => {
// there is no a/b
if (n < 100 && n == 0) return true;
if (n < 100) return false;
int sumCD = n % 10;
n /= 10;
sumCD += n % 10;
n /= 10;
int sumAB = n % 10;
n /= 10;
sumAB += n % 10;
return (sumAB == sumCD);
});
One approach is to write a method that takes in an integer and returns true if the integer is four digits and the sum of the first two equal the sum of the second two:
public static bool FirstTwoEqualLastTwo(int input)
{
if (input < 1000 || input > 9999) return false;
var first = input / 1000;
var second = (input - first * 1000) / 100;
var third = (input - first * 1000 - second * 100) / 10;
var fourth = input - first * 1000 - second * 100 - third * 10;
return (first + second) == (third + fourth);
}
Then you can write a single loop from 1000-9999 and output the numbers for which this is true with a space between each digit (not sure why that's the output, but it appears that's what you were doing in your sample code):
static void Main(string[] args)
{
for (int i = 1000; i < 10000; i++)
{
if (FirstTwoEqualLastTwo(i))
{
Console.WriteLine(" " + string.Join(" ", i.ToString().ToArray()));
}
}
Console.Write("Done. Press any key to exit...");
Console.ReadKey();
}
We can compute the value of d from the values of a,b,c.
for (int a = 1; a <= 9; a++)
{
for (int b = 0; b <= 9; b++)
{
for (int c = 0; c <= 9; c++)
{
if (a + b >= c && a + b <= 9 + c)
{
int d = a + b - c;
Console.WriteLine(" " + a + " " + b + " " + c + " " + d);
}
}
}
}
We can further optimize by changing the condition of the third loop to for (int c = max(0, a + b - 9); c <= a + b; c++) and getting rid of the if statement.

Looking for a way to shorten my code

This is my code:
static void Main(string[] args)
{
Console.Write("How many tests would you like to do? 1 to 10: ");
int tests = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
}
can someone help me out with my code please? i have no idea what im doing
Thanks
Make an array int[] counts = new int[13] and just use counts[total]++;; at the end, loop over it:
for(int i = 2 ; i <= 12 ; i++)
// etc
(note: you could use an array of 11 items and constantly handle the off-by-two, but... it probably isn't worth it)
Something like:
static void Main()
{
Console.WriteLine("Investigation 1");
Console.WriteLine("===============");
Console.WriteLine();
Console.Write("How many sets of tests? 1 to 10: ");
int sets = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Random r = new Random();
int[] counts = new int[13];
for (int ctr = 0; ctr < 36 * sets; ctr++)
{
int a = r.Next(1, 7), b = r.Next(1, 7), total = a + b;
Console.WriteLine($"Roll {(ctr + 1)}: {a} + {b} = {total}");
counts[total]++;
}
Console.WriteLine("=======================");
Console.WriteLine();
Console.WriteLine("Total Expected Actual");
Console.WriteLine("===== ======== ======");
for(int i = 2; i <= 12; i++)
{
var expected = sets * (6 - Math.Abs(7 - i));
Console.WriteLine($" {i} {expected} {counts[i]}");
}
}
For a histogram:
var maxCount = counts.Max(); // needs "using System.Linq;" at the top
for (int i = 2; i <= 12; i++)
{
var width = ((Console.WindowWidth - 10) * counts[i]) / maxCount; // make it proportional
Console.WriteLine($"{i}\t{new string('*', width)}");
}

Hollow isosceles triangle # Console

There are a lot of examples to create a triangle in C#
but now i need a hollow one here fore there are a lot of examples in C or C++ but i need one in C# console , can some body give me a few examples
*
* * *
* * * *
* * * * *
* * * * * *
int i, j;
for (i = 0; i < 5; i++)
{
for (j = 5 - i; j > 0; j--)
Console.Write(" ");
for (j = 0; j <= 2 * i; j++)
Console.Write("*");
Console.WriteLine();
}
*
* *
* *
* *
* * * * * *
This Works...But if the value is greater than that s printable on a single line it breaks into next line. The maximum possible value without line break is 40. Till 40 it works well and good in my system. For larger values you have to increase the width of command prompt. It can be done using commands or by changing the width in properties of command prompt.
int i, j,n=5;
for (i = 0; i < n; i++)
{
for (j = n - i; j > 0; j--)
Console.Write(" ");
for (j = 0; j <= 2 * i; j++)
{
if (j < 2 * i && j > 0&&i!=(n-1))
Console.Write(" ");
else
Console.Write("*");
}
Console.WriteLine();
}
Try this:
void Main()
{
Int32 totalLines = 9;
for (Int32 i = 0; i <= totalLines; ++i)
Console.WriteLine(Line(i, totalLines));
}
String Line(Int32 i, Int32 totalLines)
{
Int32 charCount = 2 * totalLines + 1;
Int32 center = charCount / 2;
// Last line is filled completely
if (i == totalLines) return new String(Enumerable.Repeat('*', charCount).ToArray());
Char[] chars = Enumerable.Repeat(' ', charCount).ToArray();
chars[center-i] = '*';
chars[center+i] = '*';
return new String(chars);
}
This will only work with monospace fonts.

How do I print the output in one row below another?

For example I am trying to print the output in following way:
disk: 1 2 3 4 5
move: 1 3 7 15 31
How can I do that, can someone help me out please?
{
class Program
{
static void Main(string[] args)
{
int n = 2;
for (int j = 1; j <= 5; j++)
Console.WriteLine("disk: {0}", j);
for (int i = 1; i <= 5; i++)
Console.WriteLine("moves: {2:N0}",
n, i,(long)Math.Pow(n, i) - 1);
}
}
}
Console.WriteLine will, as it sounds, write a new line each time. If you don't want that behavior, use Console.Write.
Console.Write("Disk:");
for (int j = 1; j <= 5; j++)
Console.Write(" {0}", j);
Console.WriteLine();
Console.Write("Moves:");
for (int i = 1; i <= 5; i++)
Console.Write(" {2:N0}", (long)Math.Pow(n, i) - 1);
Console.WriteLine();
Use the string.PadLeft() method to justify your text. Of course you can replace the magic numbers with a constant value. This gives you the advantage of not having to count spaces, and automatically adds the right amount of spaces to bring the string up to the desired length.
Note that you can also get rid of the format insertion (i.e. no more curly braces).
static void Main(string[] args)
{
int power = 2;
Console.Write("disk:".PadLeft(8));
for (int j = 1; j <= 5; j++)
Console.Write(j.ToString().PadLeft(5));
Console.WriteLine();
Console.Write("moves:".PadLeft(8));
for (int i = 1; i <= 5; i++)
Console.Write(((long)Math.Pow(power, i) - 1).ToString().PadLeft(5));
Console.WriteLine();
Console.ReadLine();
}
This is the result:
You can use Console.Write and it wont print a carriage return.
However you dont need a for loop in this case. Just use Enumerable.Range
var n = 2;
var disks = Enumerable.Range(1, 5).ToList();
var moves = Enumerable.Range(1, 5).Select(i => (long) Math.Pow(n, i) - 1);
Console.WriteLine("disk: {0}", string.Join(" ", disks));
Console.WriteLine("moves: {0:N0}", string.Join(" ", moves));
Results:
disk: 1 2 3 4 5
moves: 1 3 7 15 31

Output custom shape in ConsoleApplication - C#

I have this shape and I want to output it to ConoleApplication Windows.
I have this code but it doesn't work as I need :
int i,j;
for(i=0;i<5;i++)
{
for(j=5-i;j>0;j--)
Console.WriteLine(" ");
for(j=0;j<=2*i;j++)
Console.WriteLine("*");
Console.WriteLine("\n");
}
Thanks in advance.
EDIT : I am very sorry
As everyone knows, everything Just Works™ when using LINQ... so, have you tried doing it with LINQ?
int n = 6;
var result = string.Join("\r\n", from i in Enumerable.Range(1, n)
where i != 2
let stars = Enumerable.Repeat('*', i)
let indent = new string(' ', n - i)
select indent + string.Join(" ", stars));
Console.WriteLine(result);
*
* * *
* * * *
* * * * *
* * * * * *
Something like:
for (j = 0; j <= 2 * i; j += 2)
{
printf("*");
printf(" ");
// or Console.Write("* ") if we are talking C#
}
which writes the spaces between asterisks (plus a spare one; you could remove that if it is important).
You just used WriteLine instead of Write
Here is the correct code:
int i, j;
for (i = 0; i < 5; i++)
{
for (j = 5 - i; j > 0; j--)
Console.Write(" ");
for (j = 0; j <= 2 * i; j++)
Console.Write("*");
Console.WriteLine();
}

Categories