Create Pyramid with decremental value - c#

I'm trying to create a pyramid in c# using a number input.
I know how to create a normal pyramid that counts from 1-20 but I can't seem to find what to change on my code to make it.
Instead of:
1
2 2
3 3 3
4 4 4 4
I need it to be:
4
3 3
2 2 2
1 1 1 1
Here's my current code:
using System;
public class Exercise17
{
public static void Main()
{
int i,j,spc,rows,k;
Console.Write("\n\n");
Console.Write("Display the pattern like pyramid with repeating a number in same row:\n");
Console.Write("-----------------------------------------------------------------------");
Console.Write("\n\n");
Console.Write("Input number of rows : ");
rows= Convert.ToInt32(Console.ReadLine());
spc=rows+4-1;
for(i=1;i<=rows;i++)
{
for(j=spc;j>=1;j--)
{
Console.Write(" ");
}
for(k=1;k<=i;k++)
Console.Write("{0} ",i);
Console.Write("\n");
spc--;
}
}
}

First, you need to reverse the for loop. So that it starts with rows, loops while greater than zero, and decrements and each iteration
for (i = rows; i > 0; i--)
This is the main part. But you also need to take care of the spaces. So to do this we now need to keep track of how many iterations we have already performed. So we need a new variable initiated before the loop.
int iteration = 1;
for (i = rows; i > 0; i--)
.....
Then we need to use this, in the loop to output the number. And then increment it afterwards.
for (k = 1; k <= iteration; k++)
Console.Write("{0} ", i);
iteration++;
So the whole loop now looks like;
int iteration = 1;
for (i = rows; i > 0; i--)
{
for (j = spc; j >= 1; j--)
{
Console.Write(" ");
}
for (k = 1; k <= iteration; k++)
Console.Write("{0} ", i);
Console.Write("\n");
spc--;
iteration++;
}
Now the challenge is, can you try to optimise this further?

Instead of the following:
Console.Write("{0} ",i);
You can write:
Console.Write("{0} ", (rows - i) + 1);

Related

Magic square array filled with random numbers doesn't accept even numbers

I found this code that i need for an assigment, but it only reads odd numbers and i need it to read even numbers too, but i don't know whats wrong. I need it to make the random magic squares go from 1 to 10.
Still very much a beginner and don't understand functions yet, please let me know if there is a way to dolve this.
using System;
class GFG
{
// Function to generate odd sized magic squares
static void generateSquare(int n)
{
int[,] magicSquare = new int[n, n];
// Initialize position for 1
int i = n / 2;
int j = n - 1;
// One by one put all values in magic square
for (int num = 1; num <= n * n;)
{
if (i == -1 && j == n) // 3rd condition
{
j = n - 2;
i = 0;
}
else
{
// 1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
// 1st condition helper if next number is
// goes to out of square's upper side
if (i < 0)
i = n - 1;
}
// 2nd condition
if (magicSquare[i, j] != 0)
{
j -= 2;
i++;
continue;
}
else
// set number
magicSquare[i, j] = num++;
// 1st condition
j++;
i--;
}
// print magic square
Console.WriteLine("The Magic Square for " + n
+ ":");
Console.WriteLine("Sum of each row or column "
+ n * (n * n + 1) / 2 + ":");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
Console.Write(magicSquare[i, j] + " ");
Console.WriteLine();
}
}
// driver program
public static void Main()
{
Console.WriteLine("Value of n: ");
int n = int.Parse(Console.ReadLine());
// Works only when n is odd
generateSquare(n);
}
}
Step through the program with a debugger. Using n = 2 as an example, on your second loop through the for loop you get to this with i = 1 and j = 1:
if (magicSquare[i, j] != 0)
{
j -= 2;
i++;
continue;
}
And that makes i = 2 on the next loop through. Because there is no 2 index in the array you have created, it crashes when it gets to this same check the next loop.
Presumably odd numbers are working because they are getting floored on division (in the case of n = 5 -> i = 2).
That should be enough to point you in the right direction.

How can I print the following pattern with the for statement?

How can I print the following pattern with the for statement?
AAAA
AAAB
AABB
ABBB
BBBB
What I tried to do:
Code:
int stars = 4;
for (int row = stars; row >= 1; row--)
{
for (int i = 0; i < row; i++)
{
Console.Write("A");
}
Console.WriteLine();
}
You where almost there.
I made a small change in the first for loop to add another row (>= 1 to >= 0). We need 5 rows for 4 stars, 6 rows for 5 stars, etc.
Compared the second for loop to stars as well because we want 4 values on each row (when stars is 4).
Added an if statement to check if we need to write an A or B based on the iteration number of both loops.
See code below:
int stars = 4;
for(int i = stars; i >= 0; i--) {
for(int j = 0; j < stars; j++) {
if(i > j) {
Console.Write('A');
}
else {
Console.Write('B');
}
}
Console.WriteLine();
}

C# print stars pattern

I want to print pattern like
but i have a problem with output.
my code is:
int i, j, k;
for (i = 5; i >= 1; i--)
{
for (j = 5; j > i; j--)
{
Console.Write(" ");
}
for (k = 1; k < (i * 2); k++)
{
Console.Write("*_");
}
Console.WriteLine();
}
Console.ReadLine();
There are just a couple of issues:
You're writing "*_" for every iteration, including the last. Instead, we should only write "*" on every iteration, followed by "_" on every iteration except the last one. We can do this with two different Console.Write calls, where the second one checks to see if our iterator is at the last position.
You're iterating twice as many times as you need to when you do k < (i * 2) (on the first iteration, i == 5, so i * 2 == 10, which means we'll iterate 9 times). We can fix this by changing it to k <= i
As a side note, we can declare our loop variables locally in the for loops. This reduces their scope, which is usually a good thing.
For example:
for (int i = 5; i >= 1; i--)
{
for (int j = 5; j > i; j--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write("*");
if (k < i) Console.Write("_");
}
Console.WriteLine();
}
Console.ReadLine();
The code can be simplified a little bit if we use the string constructor that takes in a character and a number of times to repeat it to write our spaces, and if we iterate one less time in our inner loop we can write "*_" followed by a WriteLine("*"):
for (int i = 5; i >= 1; i--)
{
// Write (5 - i) spaces at once
Console.Write(new string(' ', 5 - i));
// Write 'i' count of "*", joined with a "_"
Console.WriteLine(string.Join("_", Enumerable.Repeat("*", i)));
}
Console.ReadLine();
So many ways to do this...here's another one using StringBuilder and a slight cheat by getting rid of the last "_" with Trim(). It's written generically to take the desired number of rows:
public static void Main()
{
StarPattern(7);
Console.WriteLine("Press Enter to Quit...");
Console.ReadLine();
}
public static void StarPattern(int numberStarsInTopRow)
{
StringBuilder sb = new StringBuilder();
for(int row=0; row<numberStarsInTopRow; row++)
{
sb.Clear();
sb.Append(new string(' ', row));
for(int stars=0; stars<(numberStarsInTopRow-row); stars++)
{
sb.Append("*_");
}
Console.WriteLine(sb.ToString().TrimEnd('_'));
Console.WriteLine();
}
}
Output:
*_*_*_*_*_*_*
*_*_*_*_*_*
*_*_*_*_*
*_*_*_*
*_*_*
*_*
*
Press Enter to Quit...
Here's a compact version using the trick posted in the comments by LarsTech:
public static void Main()
{
StarPattern(7);
Console.WriteLine("Press Enter to Quit...");
Console.ReadLine();
}
public static void StarPattern(int numberStarsInTopRow)
{
for(int row=0; row<numberStarsInTopRow; row++)
{
Console.WriteLine(new string(' ', row) + String.Join("_", Enumerable.Repeat("*", numberStarsInTopRow - row)) + Environment.NewLine);
}
}

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

Numbers cube, each row rotated to left by one

Basic C# question:
I need to have that result when entering some number (this case was entered 4):
4 3 2 1 0
3 2 1 0 4
2 1 0 4 3
1 0 4 3 2
I was trying that code, but cant figure out my mistake:
Console.WriteLine("Please write a Number: ");
Console.Write("Number: ");
int num = int.Parse(Console.ReadLine());
for (int i = 0; i <= num; i++)
{
for (int j = num - i; j >= 0; j--)
{
Console.Write(j);
}
for (int j = 1; j <= i; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
Console.ReadLine();
This is the output I get:
4 3 2 1 0
3 2 1 0 1
2 1 0 1 2
1 0 1 2 3
0 1 2 3 4
Try this:
Console.WriteLine("Please write a Number: ");
Console.Write("Number: ");
int num = int.Parse(Console.ReadLine());
for (int i = 0; i <= num; i++)
{
for (int j = num - i; j >= 0; j--)
{
Console.Write(j);
}
for (int j = num; j > num - i; j--)
{
Console.Write(j);
}
Console.WriteLine();
}
Console.ReadLine();
The problem is that your second inner loop is starting at one and counting up rather than starting from num and counting down.
Change that loop to:
for (int j = num; j > num -i; j--)
{
Console.Write(j);
}
Also I'm not clear if you want the last line of 04321 or not. If you don't (as in the original example) then just change your loop check to i<num.
Try something like this
get a number(x) from user.
create a list of integer containing x to 0.
run a loop for x times.
every time print the list and pop the first number and push it at the end
var ints = new List<int> { 4, 3, 2, 1, 0 };
for (int i = 0; i < 4; i++)
{
ints.ForEach(n => Console.Write(n + " "));
Console.WriteLine("");
var a = ints[0];
ints.RemoveAt(0);
ints.Add(a);
}
As a hint I give you the main loop as a pseudo code:
for i from 0 to number_input-1 {
for j from number_input to 0 {
print((j-i)%(number_input+1) + " ")
}
print("\n")
}
Just for fun:
const int NUM = 4; // num from user
for (int start = NUM; start > 0; start--)
{
for (int i = 0; i <= NUM; i++)
{
int current = (start - i) >= 0 ? start - i : NUM + (start - i) + 1;
Console.Write(current + " ");
}
Console.WriteLine();
}
Honestly this is a classic sorting task. it's just hidden beyond "user types and bla bla bla" but I remember at school it was..
There is an array [4,3,2,1,0].. so
we swap 1 and 2 and get [3,4,2,1,0].
we swap 2 and 3 and get [3,2,4,1,0].
we swap 3 and 4 and get [3,2,1,4,0].
we swap 4 and 5 and get [3,2,1,0,4].
so just simple code
int[] numbers let say you have this array [4,3,2,1,0]
for(int i = 0; i < numbers.length - 2; i++){
for(int y = 0; y < numbers.length - 1; y++){
int buf = numbers[y];
numbers[y] = numbers[y + 1];
numbers[y + 1] = buf;
}
}

Categories