Read integer input and print a matrix - c#

I am trying to write a program that reads from the console a positive integer N (N < 20) and prints a matrix like these ones:
N = 3
1 2 3
2 3 4
3 4 5
N = 5
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
This is my code:
using System;
namespace _6._12.Matrix
{
class Program
{
static void Main()
{
Console.WriteLine("Please enter N ( N < 20): ");
int N = int.Parse(Console.ReadLine());
int row;
int col;
for (row = 1; row <= N; row++)
{
for (col = row; col <= row + N - 1; )
{
Console.Write(col + " ");
col++;
}
Console.WriteLine(row);
}
Console.WriteLine();
}
}
}
The problem is that the console prints one extra column with the number from 1 to N and I dont know how to get rid of it. I have an idea why this might be happening but still can't find a solution.

simple, change Console.WriteLine(row); for Console.WriteLine();
while your at it;
static void Main()
{
int N;
do
{
Console.Write("Please enter N (N >= 20 || N <= 0): ");
}
while (!int.TryParse(Console.ReadLine(), out N) || N >= 20 || N <= 0);
for (int row = 1; row <= N; row++)
{
for (int col = row; col <= row + N - 1; )
{
Console.Write(col + " ");
col++;
}
Console.WriteLine();
}
Console.Read();
}
Please enter N (N >= 20 || N <= 0): 5
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9

Just change this line Console.WriteLine(row); to this Console.WriteLine();
The problem here is that; at the end of each inner loop, you are writing the row value again; which is not needed.

The first question is what do you think Console.WriteLine(row) is doing? It is critical, when you are learning to program, to 'see' what the code is doing and why it is doing it, rather than running it, tweaking it, and then running it again to see if it acts the way you want it to. Once you see, in your head, clearly and concisely what the code is doing, you will notice that the Console.WriteLine(row) is not right and that you just need to write a newline at that point.

Here is another approach using an if statement instead of using a do while, the code looks a little simpler:
static void Main(string[] args)
{
Console.Write("Give a number from 1 to 20: ");
int n = int.Parse(Console.ReadLine());
int row,col;
Console.WriteLine("");
if (n > 0 && n < 21)
{
for (row = 1; row <= n; row++)
{
for (col = row; col <= row + n - 1;col++ )
{
Console.Write(col + " ");
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("This number is greater than 20 or smaller than 1");
}
}

// All the above answer i tired are wrong u should once try this and then reply me...
Console.Write("Enter N: (N < 20) ");
int n = Int32.Parse(Console.ReadLine());
for (int row = 1; row <= n;row++)
{
Console.Write(row+" ");
for (int col = row+1; col <= row + n - 1; )
{
Console.Write(col + " ");
col++;
}
Console.WriteLine();
}
Console.ReadLine();

using System;
namespace _6._12.Matrix
{
class Program
{
static void Main()
{
Console.WriteLine("Please enter N ( N < 20): ");
int N = int.Parse(Console.ReadLine());
int row;
int col;
for (row = 1; row <= N; row++)
{
for (col = row; col <= row + N - 1; )
{
Console.Write(col + " ");
col++;
}
Console.WriteLine(row);
}
Console.WriteLine();
}
}

Related

Nestled loops with IF statements c#

Trying to solve a simple c# question and I did but my teacher wants me to do it with a nestled loop instead of with a boolean.
Problem: Show all numbers from input number that is divisible by 3 and 7. If no number is found show "No number found".
How i solved it with bool:
Console.WriteLine("Put in a number: ");
int nummer = int.Parse(Console.ReadLine());
bool FoundLegitNumber = false;
for (int i = 1; i <= nummer; i++)
{
if (i % 3 == 0 && i % 7 == 0)
{
FoundLegitNumber = true;
Console.WriteLine($"The number {i} is evenly divisible by 3 and 7");
}
}
if (!FoundLegitNumber)
{
Console.WriteLine("Didnt find any number...");
}
How I'm trying to solve it with a for loop:
Console.WriteLine("Put in a number: ");
int nummer = int.Parse(Console.ReadLine());
for (int i = 0; i <= nummer; i++)
{
for (int j = 0; i >= j; j++)
{
if (i % 3 == 0 && i % 7 == 0)
{
Console.WriteLine($"The number {i} is evenly divisible by 3 and 7");
}
else if (j == 0)
{
Console.WriteLine("Didnt find any number...");
break;
}
}
}
I know, it doesnt make any sense but I cant figure out how to solve it. I know that I want to give J + 1 if (i % 3 == 0 && i % 7 == 0) was not true.
If you want a method that involves a nested for without distorting the basic problem, maybe you could add a dividers array like this:
int number = 21;
int[] dividers = new int[] { 3, 7 };
for (int i = 0; i <= number; i++)
{
bool matchAllDividers = true;
for (int j = 0; j < dividers.Length; j++)
{
if (i % dividers[j] != 0)
{
matchAllDividers = false;
break;
}
}
if (matchAllDividers)
{
Console.WriteLine("The number {0} is evenly divisible by all dividers".FormatWith(i));
}
else
{
Console.WriteLine("The number {0} is not evenly divisible by all dividers".FormatWith(i));
}
}

How do I print x number of integers per line and only display the odd numbers in those lines?

So far I can display the correct amount of integers per line, but I need to show only the odd numbers in the sequence. This is what I have so far:
Edited code:
for ( counter = 1; counter <= max; ++counter)
{
if( counter % 2 != 0 )
{
Console.Write(counter+"");
int printcounter = counter;
if (printcounter % 4 == 0)
{
Console.WriteLine();
}
else
{
Console.Write('\t');
}
printcounter++;
}
Console.WriteLine();
}
The output I'm getting
1
3
5
7
9
The output I'm trying to get:
1 3 5 7
9 11 13 15
Declare your printCounter variable BEFORE the loop so that it persists and correctly tracks the number of things you've printed:
public static void Main (string[] args) {
int max = 21;
int printCounter = 0;
for (int counter = 1; counter <= max; counter++)
{
if(counter % 2 != 0 )
{
Console.Write(counter + "\t");
printCounter++;
if (printCounter % 4 == 0)
{
Console.WriteLine();
}
}
}
}
You almost got it… try it like below…
int max = 100;
int printCount = 0;
for (int counter = 1; counter <= max; ++counter) {
if (counter % 2 != 0) {
Console.Write(counter + " ");
if (++printCount % 4 == 0) {
Console.WriteLine("");
}
}
}
Console.ReadKey();
Note: the line…
if (++printCount % 4 == 0) {
is shorthand for ….
printCount++;
if (printCount % 4 == 0) {
You only want to increment printCount when you print a number.

Input string is not in correct format error for C# program

I want to print Ready if CL (count lucky) is greater than CUL(count unlucky). My criteria is N is some number and array A is upto N. and the contents of array are checked whether individual content is even/odd. If even CL++, or else CUL++
When I tried to enter input in the format
5
1 2 3 4 5
the error is "input string is not in correct format".
I can get the output if the format of the input is
5
1
2
3
4
5
What should be changed to get the output while using earlier format?
Code:
class Program
{
static void Main(string[] args)
{
int N = int.Parse(Console.ReadLine());
if (N <= 100)
{
int[] A = new int[N];
int cL = 0; int CUL = 0;
int j;
for (j = 0; j < N; j++)
{
A[j] = Convert.ToInt32(Console.ReadLine());
if (A[j] % 2 != 0)
{
CUL++;
}
else
{
cL++;
}
}
if (cL > CUL)
{
Console.WriteLine("READY FOR BATTLE");
}
else
{
Console.WriteLine("NOT READY");
}
}
Console.ReadKey();
}
}
When input is in form of "1 2 3 4 5" (a string) you have to split it into items and parse each item into integer:
int N = int.Parse(Console.ReadLine());
String line = Console.ReadLine();
int[] A = line
.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(item => int.Parse(item))
.ToArray();
// given N differs from actual one
if (N != A.Length) {
// Throw an exception or re-assign N
N = A.Length;
}
// A as well as N are obtained
for (j = 0; j < N; j++)
if A[j] % 2 != 0
CUL++;
else
cL++;
if (cL > CUL)
Console.WriteLine("READY FOR BATTLE");
else
Console.WriteLine("NOT READY");

Please help in simple pattern program in c#

I want to print the following pattern:-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
But I am getting the following output:-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Here is the Code:
static void Main(string[] args)
{
int spacelimit = 13, num = 1, n = 5;
for(int i = 1; i<=n; i++)
{
for (int space = spacelimit; space >= i; space--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write("{0,3:D} ",num++);
}
spacelimit = spacelimit - 3;
Console.WriteLine();
}
Console.ReadKey();
}
What I am doing wrong with the spaces? I am unable to do it.
This will do the trick
int spacelimit = 13, num = 1, n = 5;
for(int i = 1; i <= n; i++)
{
for(int space = spacelimit; space >= i; space--)
{
Console.Write(" ");
}
for(int k = 1; k <= i; k++)
{
Console.Write("{0,2:D} ", num++);
}
spacelimit = spacelimit - 2;
Console.WriteLine();
}
Console.ReadKey();
I have just changed 3 to 2 i.e. spacelimit - 2 and {0,2:D}
Yes changing spacelimit also solves the issue with trailing spaces but this solution worked as expected ... please have a look on the image.
If we make space>= i-3 in for loop, as shown below, it works fine. Please check. Thanks.
int spacelimit = 13, num = 1, n = 5;
for (int i = 1; i <= n; i++)
{
for (int space = spacelimit; space >= i - 3; space--) // HERE, I MADE i-3
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write("{0,3:D} ", num++);
}
spacelimit = spacelimit - 3;
Console.WriteLine();
}
Console.ReadKey();
Set the initial value of spacelimit to 16.

Printing number sequence in C# with less loops

I am looking for a output below with the input n and with number of loops less than (n*(n+1))/2 ,
Example N = 4,
1
2 3
4 5 6
7 8 9 10
Number of loops should be less than 10.
Is this possible???
There's also a solution with only one loop.
Print numbers in order, followed by a space, and if the last number was triangular, then print a newline. Keep track of how many newlines you have, and that's it.
Here's the code:
public static void PrintPyramid(int n)
{
var i = 0;
while (n > 0)
{
Console.Write(++i);
if (IsTriangularNumber(i))
{
Console.Write(Environment.NewLine);
n--;
}
else
{
Console.Write(" ");
}
}
}
public static bool IsTriangularNumber(int i)
{
var n = (int)Math.Sqrt(i*2);
return n*(n + 1) / 2 == i;
}
And here's how it works: http://ideone.com/Mx7Cel
For faster triangular number tests, see the answers to this question.
By cheating it is easy:
public static void PrintPyramid(int n)
{
int i = 1;
int row = 1;
int maxNumberInRow = 1;
int cycles = 0;
while (row <= n)
{
cycles++;
if (i == maxNumberInRow)
{
Console.Write(i);
Console.Write(" ");
i++;
}
else
{
Console.Write(i);
Console.Write(" ");
i++;
Console.Write(i);
Console.Write(" ");
i++;
}
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
}
}
Console.WriteLine();
Console.WriteLine("Cycles: {0}", cycles);
}
I did a little loop unrolling, doing up to two numbers in the same cycle. For n == 4, it is 6 full cycles.
Note that if we want to play the semantic game, a partial loop unrolling is enough:
public static void PrintPyramid3(int n)
{
if (n >= 1)
{
Console.Write("1");
Console.Write(" ");
Console.WriteLine();
}
int i = 2;
int row = 2;
int maxNumberInRow = 3;
int cycles = 0;
while (row <= n)
{
cycles++;
Console.Write(i);
i++;
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
Console.WriteLine("Cycles: {0}", cycles);
}
The first row is "outside" the loop, so for n == 4, only 9 cycles are necessary.
Based on this code, it is easy to partially loop unroll the first x cases and do the remaining cases in a loop.
Ok... I was kidding... It is possible to do it in a totally loopless way...
public static void PrintPyramid(int n)
{
PrintPyramidRecursive(n, 1, 1, 1);
}
private static void PrintPyramidRecursive(int n, int i = 1, int row = 1, int maxNumberInRow = 1)
{
Console.Write(i);
Console.Write(" ");
i++;
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
if (row > n)
{
return;
}
}
PrintPyramidRecursive(n, i, row, maxNumberInRow);
}
You only need to use recursion! :-) :-) :-)
This one is a little more devious: no (apparent) cycles and no recursion:
public static void PrintPyramid5(int n)
{
int i = 1;
int row = 1;
int maxNumberInRow = 1;
ManualResetEvent mre = new ManualResetEvent(false);
Timer t = null;
TimerCallback tc = x =>
{
Console.Write(i);
Console.Write(" ");
i++;
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
if (row > n)
{
t.Dispose();
mre.Set();
}
}
};
t = new Timer(tc, null, 0, 1);
mre.WaitOne();
}
Simply put, the printing method is called by a Timer :-) So the loop is in the operating system. The printing method (tc) will clearly be called 10 times for n == 4.
You could pretend that string.Join() and Enumerable.Range() don't do any looping internally, and do it like this:
int n = 4;
for (int i = 1, j = 1; i <= n; ++i, j += i-1)
Console.WriteLine(string.Join(" ", Enumerable.Range(j, i).Select(x => x.ToString("00"))));
The for loop therefore only loops once per line rather than once per output number. But it's a cheat, because string.Join() and Enumerable.Range() do loop internally.
As per xanatos's suggestion, here's a version with no explicit loops at all:
Console.WriteLine(
string.Join("\n", Enumerable.Range(1, n).Select(i =>
string.Join(" ", Enumerable.Range((i*(i-1))/2+1, i).Select(x =>
x.ToString("00"))))));
This is a curiosity only, of course. ;)
Finally, here's a variant of xanatos's recursive solution:
private static string Triangular(int max, int row, int rowEnd, int number)
{
if (row == max)
return "";
else if (number <= rowEnd)
return number.ToString("00") + " " + Triangular(max, row, rowEnd, number + 1);
else
return "\n" + Triangular(max, row + 1, rowEnd + row + 1, number);
}
Which you'd use like this:
Console.WriteLine(Triangular(n, 1, 1, 1));
here i did your homework
public static void PrintPyramid(int n)
{
int t = 1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write(t);
t++;
}
Console.WriteLine();
}
}

Categories

Resources