Nested for loop c# [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a school project and I need to complete it but its not working. I have to do a nested for loop in c# , I have managed to do the earlier projects which had the result :
1 2 3 6
1 2 3 6
1 2 3 6
1 2 3 6
static void Main(string[] args)
{
for (int row = 0; row < 4; row++)
{
int x = 1;
int y = 0;
for (int column = 0; column < 3; column++)
{
Console.Write(x);
y = y + x;
x = x + 1;
}
Console.Write(y);
Console.WriteLine();
}
Console.ReadLine();
}
but now i stuck with the second project which must give an output :
1 2 3 6
2 3 4 9
3 4 5 12
5 6 7 18
please help anyone !!

for (var x = 1; x < 5; x++)
{
if (x == 4) x = 5;
Console.Write("{0} ",x);
for (var y = 1; y < 4; y++)
Console.Write("{0} ", y < 3 ? x + y : 3 * (x + 1));
Console.WriteLine();
}
EXPLANATION:
required output is:
1 2 3 6
2 3 4 9
3 4 5 12
5 6 7 18
So here are four rows and four columns
first column in each row is 1,2,3,5, so outer loop in x goes from 1 to 4, and first statement changes the last value of 4 to a 5.
The 2nd & 3rd columns are always just the first column incremented by one, then by one again, and finally, last 4th column is 3 times 1 + the first column. So inner loop in y just goes 1, 2, 3, and, for 2nd and 3rd column, prints the first column plus the y value (1, 2) for 2nd and 3rd column and three times 1 plus the first column for the last (4th) column.
So each row is, effectively
x, x+1, x+2, 3*(x+1)
and each row starts with x one greater than the row before it, except we skip row 4
The expression y < 3 ? x + y : 3 * (x + 1) is a ternary which has three parts, a Boolean condition, followed by a question mark (?), the value to generate when the Boolean is true, followed by a colon (:) and then the value to generate when the Boolean is false. So it reads like this:
if y is less than 3, output x+y, else output 3 times (x+1)
Another simpler option (which only uses one loop), might be:
for (var x = 2; x < 7; x++)
{
if (x == 5) continue; // skip row 4
Console.WriteLine("{0} {1} {2} {3} ",x-1, x, x+1, 3*x);
}

Well, here is the solution for you. But please try to understand it and next time you wont ask us to solve your homework.
int p;
for (int x = 1; x < 6; x++)
{
if (x !== 4)
{
for (int y = x; y < x + 3; y++)
{
p += y;
Console.Write(y);
}
Console.Write(p);
Console.WriteLine();
p = 0;
}
}
Console.ReadLine();
I made it a little different, so you can play with it.

Related

Can you please help me with a clue on how can I find all possible combinations for a given set of number from 1 to N, using +- operators [duplicate]

This question already has answers here:
Linq query to get all numbers (positive and negative) up to N that sum up to number K
(5 answers)
Listing all permutations of a string/integer
(28 answers)
Closed 1 year ago.
Given input: N = 6, X = 3
The output should be:
1 + 2 + 3 - 4 - 5 + 6 = 3
1 + 2 - 3 + 4 + 5 - 6 = 3
1 - 2 - 3 - 4 + 5 + 6 = 3
So far I could manage this:
//returns a string of numbers from 1 to N
static string Numbers(int maxNumber) => maxNumber > 1 ? Numbers(maxNumber - One) + maxNumber :"1";
and a function that generates all possible combinations for +- but the problem is that I want to combine the +- resulted string with numbers from 1 to N:
static void Permute(char[] arry, int i, int n)
{
int j;
if (i == n)
Console.WriteLine(arry);
else
{
for (j = i; j <= n; j++)
{
Swap(ref arry[i], ref arry[j]);
Permute(arry, i + 1, n);
Swap(ref arry[i], ref arry[j]); //backtrack
}
}
}
static void Swap(ref char a, ref char b)
{
char tmp;
tmp = a;
a = b;
b = tmp;
}
This looks like a very different form of "permute". For N integers, you have D=N-1 decisions to make, each of which can be either a + or a -. Two options is: "binary", so, if this is me, I would compute (2^D)-1 (which gives us the upper bound), then do a for loop from zero to that number (inclusive), and do the math: each binary digit is a decision point, and we could say 0===- and 1===+; see what the result is: if it is the number you wanted: log it.
For N=6 we have D=5, and 32 attempts to do; 0 thru 31:
int N = 6, X = 3;
// how many decisions is that?
var decisions = N - 1;
// treat each -/+ as one of "decisions" binary digits
var binaryUpperLimit = (1 << decisions) - 1;
for (int i = 0; i <= binaryUpperLimit; i++)
{
// compute the sum
int sum = 1; // the 1 is a permenant fixture, it seems
// determine each decision using binary arithmetic
for (int place = 0; place < decisions; place++)
{
int digit = place + 2;
if ((i & (1 << place)) == 0)
{
sum -= digit;
}
else
{
sum += digit;
}
}
// is that what we wanted?
if (sum == X)
{
// we have a "hit"; repeat the above to output this
Console.Write("1");
for (int place = 0; place < decisions; place++)
{
if ((i & (1 << place)) == 0)
{
Console.Write(" - ");
}
else
{
Console.Write(" + ");
}
int digit = place + 2;
Console.Write(digit);
}
Console.Write(" = ");
Console.WriteLine(sum);
}
}
(if the initial 1 can be negative, you'll need to adjust to add an extra decision, start the sum at zero, and make digit be +1 instead of +2)

positioning a pair of chars(*) center instead of left [duplicate]

This question already has an answer here:
C# christmas tree
(1 answer)
Closed 4 years ago.
So i am struggling with a console application. It is required the line of chars to form a tree like pattern instead of right wing triangle. Like this(3):
*
***
*****
so far i have this:
int rows = int.Parse(Console.ReadLine());
for(int i = 1; i <= rows; i++)
{
for(int x = 1; x <= i; x++)
{
Console.Write("*");
}
Console.WriteLine("\n");
}
I think you're looking for the PadLeft function. It adds spaces to your string on the left side, so you can position it correctly. Also, you need to multiply the amount of rows by 2 and increase the step size by 1. You'll get the following code:
int rows = int.Parse(Console.ReadLine()) * 2;
for (int i = 1; i <= rows; i += 2) {
Console.Write( "".PadLeft( (rows - i) / 2) );
for(int x = 1; x <= i; x++) {
Console.Write("*");
}
Console.WriteLine();
}
Also, if you really want to make your triangle look like this, you might need to remove this line:
Console.WriteLine("\n");
... and change it to this:
Console.WriteLine();
(This will remove the unnessecary newline, WriteLine already prints a newline).

How to increment i in for loop in C#

I'm trying to modify the code below so each first number in column is based on the row number.
int i, sum = 0;
for (int row = 0; row < 7; row++)
{
for (i = 1; i < 6; i++)
{
sum = sum + i;
Console.Write("{0} ", i);
}
Console.WriteLine(sum);
sum = 0;
}
Console.Read();
presents this in console:
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
But I'm trying get like this:
1 2 3 4 5 sum
2 3 4 5 6 sum
3 4 5 6 7 sum
4 5 6 7 8 sum
and so on..
......
....
Any idea on how to solve this?
Change the inner loop to be
for (int i = row + 1; i < row + 6; i++)
Replace
sum = sum + i;
Console.Write("{0} ", i);
enter code here
with
number = number + row
sum = sum + number;
Console.Write("{0} ", number);
This way you use the variable row to keep track of the starting number for the row.
If you don't need the console statements and just the sum, you can just use no inner loop and:
sum = Enumerable.Sum(Enumerable.Range(row+1, 5));
It's LINQ
or, if you need the console statement:
Enumerable.Range(row+1, 5).ToList().ForEach(c => sum += c; Console.Write(c));

C# array wont accept "size" [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
the noob, again. todays question is:
int[] forArray = new int[10];
for (int k = 1; k <= 10; k++)
{
forArray[k] = k * 2;
Console.WriteLine(k); // test
}
for (int k = 0; k < 10; k++)
{
Console.WriteLine(forArray[k]);
}
it gives an "out of bounds" error. I would like my program to output natural numbers from 2 to 20. Instead gives off an error. when I change the first for loops condition to k <= 9 it runs but gives me 0 instead of 20. its like it returns the last value as 0 and "re-positions" it to the "front". sorry for the really simple question.
Arrays are zero-based, when it comes to referencing the elements. So, for 10 items in an array (which is what you allocated), it's forArray[0] through forArray[9]. Your code tries to loop from forArray[1] through forArray[10], and there is no index position 10 (which is when you end up going out of bounds).
Your second for-loop is fine, as it goes from 0 to 9.
Note: Since your loop needs to be zero-based, you'll need to adjust how you calculate the number you stuff into the index positions, if you want it starting with 2.
Debug your code and step through, as you see below you are trying to assign to index [10], which doesn't exist.
{
int[] forArray = new int[10];
for (int k = 1; k < 10; k++) // k < 10 instead of k <= 10
{
forArray[k] = k * 2;
Console.WriteLine(k); // test
//forArray[0] = SKIPPED
//forArray[1] = 2
//forArray[2] = 4
//forArray[3] = 6
//forArray[4] = 8
//forArray[5] = 10
//forArray[6] = 12
//forArray[7] = 14
//forArray[8] = 16
//forArray[9] = 18
//forArray[10] INVALID
}
for (int k = 0; k < 10; k++)
{
Console.WriteLine(forArray[k]);
}
}
Tested here
Change your condition to k
forArray[k - 1] = k * 2;

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