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.
Related
i have idea "find primes between 1 and n".
Algorithms based on residual division.
i use 2 array pr and nt.
[pr is saved primes. nt is saved counter number.]
ex.
begin with 3
3 is primes => pr0 = 3 and nt0 = 2.
primes >3 is odd.
when i = 5 nt0 = nt0-1 = 1 => 5 is prime.
And pr1 = 5, nt1 =pr1 -1 = 4.
when i = 7 :
nt0 = nt0 -1 = 0, => 7 is prime.
and pr2 = 7, nt2 = 6.
when i = 9
nt0 < 0 => 9 is not prime. nt0 = pr0 -1 = 2, nt1 = 3, nt2 = 5.
....
using System;
namespace primes
{ // program for find primes between 1 and n.
class Program
{ public static void Main()
{
int[] pr = new int[100], ct = new int[100];
ct[0] = 2;
pr[0] = 3;// 3 is primes => n[0] is 3 .
int n = 1; // n is number of primes.
for (int i = 5; i < 111; i += 2)
{
for (int l = 0; l < n; l++)
{ if (ct[l] >= 0)
{
ct[l]-- ;
//Console.Write("{0} ", ct[l]);
}
else
{
ct[l] = pr[l] - 1 ;
// Console.Write("{0} ", ct[l]);
for (int a = l + 1; a < n; a++)
{
ct[a]--;
// Console.Write("{0} ", ct[a]);
}
// Console.WriteLine();
goto resume; // when ct <0 jump to resume
}
}
// Console.WriteLine();
pr[n] = i;
ct[n] = i ;
// Console.Write("{0} ", ct[n]);
n++;
resume : ;
}
for (int m = 0; m < n; m++)
{
Console.Write(" {0}", pr[m]);
}
Console.ReadKey();
}
}
}
i want to print primes 3,5,7,11, 13...
but i when i run: 3 5 7 9 13 15 17 23 29 37 39 63 65 71 89.
i dont understand.
Can you help me?
i was wrong when used
if (ct[l] >= 0)
{
ct[l]-- ;
//Console.Write("{0} ", ct[l]);
}
else {
.... goto resume ;
}
"when ct[l] < 0 and ct[k]<0(k>l) => ct[l] = pr[l] -1.
But ct[k] = ct[k] -1."
if(v != 0)
{ v = 0;// =>i is not prime and v = 0.
}
else {
pr[n] = i;// =>i is prime
ct[n] = i-1 ;
n++;
thanks all.
i finished my program.
This is my code :
using System;
namespace primes
{ // program for find primes between 1 and n.
class Program
{ public static void Main()
{
int[] pr = new int[100], ct = new int[100];
ct[0] = 2;
pr[0] = 3;// 3 is primes => n[0] is 3 .
int n = 1;
int v = 0;
for (int i = 5; i < 111; i += 2)
{
for (int l = 0; l < n; l++)
{ if (ct[l] == 0)
{
ct[l] = pr[l] - 1;
v++;
}
else
{
ct[l]--;
}
}
if(v != 0)
{ v = 0;
}
else {
pr[n] = i;
ct[n] = i-1 ;
n++;
}
}
for (int m = 0; m < n; m++)
{
Console.Write(" {0}", pr[m]);
}
Console.ReadKey();
}
}
}
I've been bugged with this idea for a while.
Accepting an array with spaces is not straight forward in c#. How do we accept a 2d array, whose size is given by the user? I tried this, but something isn't right. Help is much appreciated. Thank You.
Input:
4
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
Where the first line specifies the value of 'n' in 'n x n'
Well, the code i tried was this. This might look stupid for a few of you :
string input;
string[] inputArray;
int[] inputInt;
int MxM = Convert.ToInt32(Console.ReadLine()); //MxM = First Line=n
int[,] array = new int[MxM, MxM];
for (int i = 0; i < MxM; i++)
{
for (int j = 0; j < MxM; j++)
{
input = Console.ReadLine();
inputArray = input.Split(' ');
inputInt = new int[MxM];
for (int k = 0; k < MxM; k++)
{
inputInt[k] = int.Parse(inputArray[k]);
array[i, j] = inputInt[k];
}
}
}
Hopefully, the answer for this will also be the answer to output a matrix. Thank You
Either:
for (int i = 0; i < MxM; i++)
for (int j = 0; j < MxM; j++)
array[i, j] = Convert.ToInt32(Console.ReadLine());
or:
for (int i = 0; i < MxM; i++)
{
inputArray = Console.ReadLine().Split(' ');
for (int j = 0; j < MxM; j++)
array[i, j] = Convert.ToInt32(inputArray[j]);
}
which, of course, could fail if you don't enter in the right format.
If I am understanding what you want correctly:
You would like to take an input N, in your example 4, with that - create a 4 x 4 array. Then for each index in the first dimension, ask the user for input equating to N number of integers separated by spaces. Read that input and place it into the array at the proper 2d-index. So with 4 as the first input, the user will be prompted something like:
Please input 4 integers(separated by spaces):
The user would type in, for example:
Please input 4 integers(separated by spaces): 1 2 3 4
And hit enter. Again the user is prompted:
Please input 4 integers(separated by spaces): 1 2 3 4
Please input 4 integers(separated by spaces):
And so on until:
Please input 4 integers(separated by spaces): 1 2 3 4
Please input 4 integers(separated by spaces): 2 3 4 5
Please input 4 integers(separated by spaces): 3 4 5 6
Please input 4 integers(separated by spaces): 4 5 6 7
You could probably use something like the following in this case:
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("Please enter the size of the matrix:");
if (!int.TryParse(Console.ReadLine(), out size))
{
Console.WriteLine("The value provided for the size was not a proper integer value.");
Console.WriteLine("Press ESC to quit...");
while (Console.ReadKey().Key != ConsoleKey.Escape) { }
return;
}
int[,] matrix = new int[size, size];
for (int i = 0; i < size; ++i)
{
bool complete = false;
while (!complete)
{
Console.WriteLine(string.Format("[{0}] - Please input {1} integers(separated by spaces):", i, size));
string[] input = Console.ReadLine().Split(' ');
if (input.Count() != size)
{
Console.WriteLine("The input was invalid, try again...");
continue;
}
for (int j = 0; j < size; ++j)
{
if (!int.TryParse(input[j], out matrix[i, j]))
{
complete = false;
Console.WriteLine("The input was invalid, try again...");
break;
}
complete = true;
}
}
}
Console.WriteLine("Output: \n");
WriteMatrix(matrix, size);
Console.ReadKey();
}
private static void WriteMatrix(int[,] matrix, int size)
{
string output = string.Empty;
for(int i = 0; i < size; ++i)
{
string line = string.Empty;
for (int j = 0; j < size; ++j)
line += string.Format("{0} ", matrix[i, j]);
output += string.Format("{0}\n", line.Trim());
}
Console.WriteLine(output);
}
}
The code above should be mostly safe against the user typing invalid values, but you could probably spend some time to clean it up or enhance it some more. The basic idea is there.
You can try to use code like this:
Console.ReadLine().Split().Select(str => Convert.ToInt32(str)).ToArray()
to get an int array out of the line.
I think you understood the idea.
public static int[,] MatrixConstructor()
{
int N = Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[N, N];
for (int i = 0; i < N; i++)
{
String[] line = Console.ReadLine().Split(' ');
for (int j = 0; j < N; j++)
{
matrix[i,j] = Convert.ToInt32(line[j]);
}
}
return matrix;
}
This conforms to your input.
Hi i am new to programming and i currently have this code:
namespace Patterns
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 4; i++)//'rows'
{
for (int h = 1; h <= 9 - (i*2)+1; h++)
{
Console.Write("#");
}
Console.WriteLine("\n" );
}
}
}
}
This produces this output:
########
######
####
##
the number of hashes is correct as i am going from 8, 6, 4, 2 but i need to add an extra space every time i go onto a new line. How do i make it so the output is as follows?
########
######
####
##
Thanks,
Umer
From your code you could modify it to do the following in the inner for loop:
for (int j = 0; j < i - 1; j++) {
Console.Write(" ");
}
for (int h = 1; h <= 9 - (i*2)+1; h++) {
Console.Write("#");
}
Console.WriteLine("\n" );
As a note you should probably use StringBuilder to do this as I believe it is quite inefficient to constantly call Console.WriteLine.
The code could be modified further:
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < i - 1; j++) {
sb.append(" ");
}
for (int h = 1; h <= 9 - (i*2)+1; h++) {
sb.append("#");
}
sb.append("\n" );
}
Console.WriteLine(sb.toString());
Introduce variables, start your rows at 0 and repeat the string for each row number.
This can also be applied to the string printing the hashes:
static void Main(string[] args)
{
int rows = 4;
int columns = 9;
for (int i = 0; i < rows; i++)
{
// Print a string with `i` spaces.
Console.Write(new String(' ', i));
int hashes = columns - ((i + 1) * 2) + 1;
Console.Write(new String('#', hashes));
Console.WriteLine();
}
}
Basically, just add space in front of your hash characters.
######## Row 1 (i=1), 0 Space
###### Row 2 (i=2), 1 Space
#### Row 3 (i=3), 2 Spaces
## Row 4 (i=4), 3 Spaces
In this case, you need "i-1" spaces for each rows. (Actually, it's (8 - charater count) / 2) and character count was 9 - (i*2) + 1, so ( 8 - 9 + i * 2 - 1 ) / 2 = (i * 2 - 2) / 2 = i - 1 )
So just make loop to add spaces before print hash chracters.
namespace Patterns
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 4; i++)//'rows'
{
for (int j = 0; j < i -1; j++) {
Console.Write(" ");
}
for (int h = 1; h <= 9 - (i*2)+1; h++)
{
Console.Write("#");
}
Console.WriteLine("\n" );
}
}
}
}
You could do something like this:
for (int i = 1; i <= 4; i++)//'rows'
{
for (int h = 1; h <= 9 - (i*2)+1; h++)
{
Console.Write("#");
}
Console.WriteLine("\n" );
for (int y = i; y > 0; y--)
{
Console.Write(" ");
}
}
I have a nested for loop in which 'j' represents the line number and 'i' represents the multiples of 3 below 1000.
I want it to display the line number then the multiple. For example:
1 3
2 6
3 9
4 12
...
333 999
right through to multiple 999
but it just dosent display the right line numbers and the multiples keep looping until the line numbers reach 999
Console.BufferHeight = 4000;
for (int j = 1; j < 1000; j++)
{
for (int i = 3; i < 1000; i++)
{
Console.WriteLine(j + " " + i);
}
}
Console.ReadLine();
for (int i = 1, j = 3; j < 1000; i++, j += 3)
{
Console.WriteLine(string.Format("{0} - {1}", i.ToString(), j.ToString()));
}
It will print starting at
1 - 3
2 - 6
up to
332 - 996
333 - 999
Do you really need nested loops for this problem? A single should be enough, if I understand your right.
Console.BufferHeight = 4000;
for (int j = 1; j < 1000; j++)
{
Console.WriteLine(j + " " + (j * 3));
}
Console.ReadLine();
You don't need nested loop for that. You can just use following code.
Console.BufferHeight = 4000;
for (int j = 1; j < 1000; j++)
{
Console.WriteLine(j + " " + j*3);
}
Console.ReadLine();
Are you just trying to do something like this, or did I miss the point entirely?
for (int i = 1; i < 1000; i++)
{
Console.WriteLine(string.Format("{0}: {1}", i, (i * 3)));
}
Well, you're looping from i = 3 to i = 999 inside of a loop from j = 1 to j = 999. This will result in 995,004 lines being written tot he console.
You want something like this:
for( int i = 1; i <= 1000; ++i )
{
Console.WriteLine( "{0} {1}", i, i * 3 );
}
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();
}
}