How can i modify this nested for loop in C#? - c#

I am trying to print out a pyramid/Pascal Triangle that will give output in series of 3. You can see it in the example below.
1
1 3 1
1 3 9 3 1
1 3 9 27 9 3 1
1 3 9 27 81 27 9 3 1
1 3 9 27 81 243 81 27 9 3 1
1 3 9 27 81 243 729 243 81 27 9 3 1
1 3 9 27 81 243 729 2187 729 243 81 27 9 3 1
Instead of getting the above output, I am getting this:
Here is my code:
using System;
namespace ConsoleApp
{
class PiscalTriangle
{
static void Main(string[] args)
{
Console.WriteLine("Enter length : ");
int num = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < num; i++)
{
for (int j = num; j > i; j--)
{
Console.Write(" ");
}
int val = 1;
for (int j = 0; j <= i; j++)
{
Console.Write(val + " ");
val = val * (i - j) / (j + 1);
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}

There are three main aspects to be considered for generating the desired ouput:
The depth of the pascal tree which is defined with the help of num variable and an iterator i which ranges from 1 to num
The elements in each row of the pascal tree are in the sequence 1,3,5,7.. which when correlated with depth of tree is equivalent to 2i-1. Hence the row values iterator j ranges from 1 to 2i-1
And finally the value (For example 3rd row, 1 3 9 3 1), can be written in the form of 3 power x, where x increases from 0 to i and then decreases to 0
By summing up the 3 conditions, we can get our desired output.
using System;
namespace ConsoleApp
{
class PiscalTriangle
{
static void Main(string[] args)
{
Console.WriteLine("Enter length : ");
int num = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= num; i++)
{
for (int j = num; j > i; j--)
{
Console.Write(" ");
}
var x = 0;
for (double j = 1; j <= 2*i-1; j++)
{
double val = Math.Pow(3, x);
Console.Write(val + " ");
if(j < i)
{
x++;
}
else
{
x--;
}
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}

Related

How do i get this output? (For loop)

I'm trying to get the end result:
1
2 1
3 2 1
4 3 2 1
This is what I have tried so far and I have the shape but I need the number to decrease. How do I solve this? I understand that I have to subtract somewhere but it compromises the shape.
public static void DrawDiamond(int size)
{
int i, j;
for (i = 1; i <= size; i++)
{
for (j = 1; j < i; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
}
My current results is this:
1
1 2
1 2 3
1 2 3 4
Hello JeremyM,
Logic
int i, j;
for (i = 1; i <= no_of_row; i++)
{
for (j = i; j>=1; j--)
{
Console.Write(j);
}
Console.WriteLine();
}
Solution
using System.IO;
using System;
class Program
{
static void Main()
{
int i, j;
for (i = 1; i <= no_of_row; i++)
{
for (j = i; j>=1; j--)
{
Console.Write(j);
}
Console.WriteLine();
}
}
}
For Example:
no_o_rows = 5 so output,
1
21
321
4321
54321
I hope my answer is helpful.
If any query so comment please.
Print value of i-j+1 insted of only j
Or if you prefer to work with Linq:
Enumerable.Range(1, 5).ToList().ForEach(x =>
{
Console.WriteLine();
Enumerable.Range(1, x).Reverse().ToList().ForEach(y => Console.Write(y));
});
which produces:
1
21
321
4321
54321
This works too:
Console.WriteLine(String.Join(Environment.NewLine,
Enumerable
.Range(1, 4)
.Select(x => String.Join(" ", Enumerable.Range(1, x).Reverse()))));
I get:
1
2 1
3 2 1
4 3 2 1

print diagonal routes array

I make this code to print array if the number of array is
{
1, 2, 3, 4, 5,
6, 7, 8, 9,
10,11,12,13,
14,15,16,17,
18,19,20,21,
22,23,24,25
}
the out put of this code is
1,2,6,3,7,11,4,6,12,16,5,9,13,17,21,10,14,18,21,15,19,23,20,24,25
I want to make change in this my code to be the out put begging from
21 16 22 11 17 23 6 12 18 24 1 7 13 19 25 2 8 14 203 9 15 4 10 5
and this my Code
int [,] p = new int [5,5];
int sum = 1;
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
p[i, j] = sum;
richTextBox1.Text += p[i, j].ToString();
sum++;
}
}
int C;
int R=1;
for (int i = 1; i <= 5; i++)
{
C = i;
for (int r = 1; r <= i; r++)
{
Output = Output + p[r, C];
C--;
}
}
richTextBox2.Text += Output.ToString();
for (int i = 2; i >= 5; i++)
{
R = i;
for (C = 5; C >= i; C--)
{
Output = Output + p[R, C];
R++;
}
}
richTextBox2.Text += Output.ToString();
This is more fiddly than you might think!
You want to traverse the diagonals of this matrix:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
starting at the bottom left and traversing each diagonal as depicted in this very badly-drawn diagram:
I've written a helper method called DiagonalIndices() that for a given maximum index (in the case of your 5x5 matrix, it will be 4) will produce a sequence of (row,col) indices in the correct order to traverse all the diagonals.
Note that the input array MUST be square - I'm assuming that is the case for your data! It clearly is for a 5x5 matrix.
The output of the following program is
21 16 22 11 17 23 6 12 18 24 1 7 13 19 25 2 8 14 20 3 9 15 4 10 5
Here's the code:
using System;
using System.Collections.Generic;
namespace ConsoleApplication4
{
public sealed class Index
{
public Index(int row, int col)
{
Row = row;
Col = col;
}
public readonly int Row;
public readonly int Col;
}
public static class Program
{
private static void Main()
{
int [,] p = new int[5, 5];
for (int i = 0, n = 1; i < 5; ++i)
for (int j = 0; j < 5; ++j, ++n)
p[i, j] = n;
// This is the bit you will use in your program.
// Replace the Console.WriteLine() with your custom code
// that uses p[index.Row, index.Col]
int maxIndex = p.GetUpperBound(1);
foreach (var index in DiagonalIndices(maxIndex))
Console.Write(p[index.Row, index.Col] + " ");
Console.WriteLine();
}
public static IEnumerable<Index> DiagonalIndices(int maxIndex)
{
for (int i = 0; i <= maxIndex; ++i)
for (int j = 0; j <= i; ++j)
yield return new Index(maxIndex-i+j, j);
for (int i = 0; i < maxIndex; ++i)
for (int j = 0; j < maxIndex-i; ++j)
yield return new Index(j, i+j+1);
}
}
}
This is a more efficient of printing only the diagonal values in a positive direction in a matrix.
int [,] p = new int [5,5]
{
{1, 2, 3, 4,5},
{6, 7, 8, 9},
{10,11,12,13},
{14,15,16,17},
{18,19,20,21},
{22,23,24,25}
};
for (int i = 4, j = 4; i >= 0 && j > = 0; i--, j--)
{
Console.Writeline(p[ i, j ]);
}

Reading a multi-dimensional array in a different order

So I have a number array like this
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
And know what I want to know is how to make it read the number 7 after the number 3, and number 8 after number 4. And so on, like this:
0 -> 1 -> 2 -> 3
|
\/
4 <- 5 <- 6 <- 7
|
\/
8 -> 9 -> 10 -> 11
|
\/
12 <- 13 <- 14 <- 15
However if I use nested incremental for it will read in normal sequential order.
I have no idea how to make it read from 3 to 7, 4 to 8 and so on...
How can I achieve that?
You can store a flag indicating if the next iteration is going to start on the left or right. So...
static void Main(string[] args)
{
// initializing values
int[,] arr = new int[4, 4];
int n = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
arr[i, j] = n++;
}
}
n = 0;
// initialization end
// starts from the left
bool left = true;
// go line by line
for (int i = 0; i < 4; i++)
{
// if it starts from the left, set start point a index 0
// otherwise start from max index
for (int j = left ? 0 : 3; left ? j < 4 : j >= 0; )
{
arr[i, j] = n++;
// increment/decrements depending on the direction
j = left ? j + 1 : j - 1;
}
// if it started from the left, the next iteration will
// start from the right
left = !left;
}
}
Results:
Initialized:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
After navigating on it:
0 1 2 3
7 6 5 4
8 9 10 11
15 14 13 12
If you have:
_arr = new int[,] { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 }, { 12, 13, 14, 15 } };
Then try:
public void PrintArr()
{
for (int i = 0; i < 4; i++)
{
if (i % 2 == 0)
{
for (int j = 0; j < 4; j++)
Console.Write(_arr[i, j] + " ");
Console.WriteLine();
}
else
{
for (int j = 3; j >= 0; j--)
Console.Write(_arr[i, j] + " ");
Console.WriteLine();
}
}
}
Here's a short, simple solution:
int h = array.GetLength(0), w = array.GetLength(1);
for(int i = 0, j = 0, c = 1; i < h; i++, c = -c, j += c)
{
for(int k = 0; k < w; k++, j += c)
{
Console.WriteLine(array[i, j]);
}
}

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;
}
}

How can I calculate the number at a given row and column in Pascal's Triangle?

I'm trying to create a function that, given a row and column, will calculate the value at that position in Pascal's Triangle.
Example:
val = GetPasVal(3, 2); // returns 2
So here I'm specifying row 3, column 2, which as you can see:
1
1 1
1 2 1
...should be a 2.
The Pascal's triangle contains the Binomial Coefficients C(n,k);
There is a very convenient recursive formula
C(n, k) = C(n-1, k-1) + C(n-1, k)
You can use this formula to calculate the Binomial coefficients.
Using Armen's equation the recursive code for implementing pascals triangle will be like below:
using System;
using System.Collections.Generic;
public class Program
{
public void Main()
{
for(int i =0 ; i<5;i++)
{
int sum = 1;
Console.WriteLine();
for(int j =0 ; j<=i;j++)
{
Console.Write(pascal(i,j));
//Console.Write(sum); //print without recursion
sum= sum *(i-j) / (j + 1);
}
}
}
public int pascal(int x, int y)
{
if((x+1)==1 || (y+1)==1 || x==y)
{
return 1;
}
else
{
return pascal(x-1,y-1)+ pascal(x-1,y);
}
}
}
There is a formula from Combinations for working out the value at any place in Pascal's triangle:
It is commonly called n choose k and written like this:
n choose k = n! / k!(n-k)!
Notation: n choose k can also be written C(n,k), nCk.
static void Main(string[] args)
{
var x = GetPasVal(3, 2);
Console.WriteLine(x);
}
public static long GetPasVal(int row, int col)
{
int factOfRow = 1,i;
for(i = 1;i<=(row - 1);i++)
factOfRow *= i;
int factOfRowMinusCol = 1;
for(i = 1;i<=(row - 1)- (col - 1);i++)//check out below link to understand condition
factOfRowMinusCol *= i;
int factOfCol = 1;
for(i = 1;i<= (col - 1);i++)
factOfCol *=i;
int fact = factOfRow / (factOfCol * factOfRowMinusCol);
return fact;
}
https://www.mathsisfun.com/pascals-triangle.html
for row in range(10):
print('{: ^45}'.format(' '.join(str(pascal(row, col)) for col in range(row+1))))
Use the above code to print out your pascal triangle and thereby modify the code. The first 10 should look like:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
The GetPasVal method will calculate all the numbers in the Pascal's Triangle up to the point that you will give (height) and after that the method will return the value of the index on that row(width). This is something you can use. It's quite simple. You just have to use a jagged array.
static void Main(string[] args)
{
var x = GetPasVal(3, 2);
Console.WriteLine(x);
}
public static long GetPasVal(int height, int width)
{
long[][] triangle = new long[height][];
for (int i = 0; i < height; i++)
{
triangle[i] = new long[i + 1];
triangle[i][0] = 1;
triangle[i][i] = 1;
if (i >= 2)
{
for (int j = 1; j < i; j++)
{
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
}
return triangle[height - 1][width - 1];
}

Categories