Below codes run perfectly fine. But how to I print converted number in left to right manner. For example if I input 898989, it will give me the output DB7AD. How do I print
DB7AD to
D
B
7
A
D
Codes:
public static void Main()
{
int decimalNumber, quotient;
int i = 1, j, num = 0;
char [] hexadecimalNumber = new char[100];
char temp;
Console.WriteLine("Decimal to HexaDecimal conversion using Ascii code.\n");
Console.WriteLine("Input DECIMAL NUMBER(S) you want to convert to HEXADECIMAL(S):\t\n");
Console.Write("Decimal Numbers : \t");
decimalNumber = int.Parse(Console.ReadLine());
quotient = decimalNumber;
while (quotient != 0)
{
num = quotient % 16;
if (num < 10)
num = num + 48;
else
num = num + 55;
temp = Convert.ToChar(num);
hexadecimalNumber[i++] = temp;
quotient = quotient / 16;
}
Console.Write("HexaDecimal Numbers : \t");
for (j = i - 1; j > 0; j--)
Console.Write(hexadecimalNumber[j]);
Console.WriteLine();
Console.Read();
}
Since you are printing your number character-by-character, you need to modify this loop
for (j = i - 1; j > 0; j--) {
Console.Write(hexadecimalNumber[j]);
}
in such a way as to print zero tabs before the first digit, one tab before the second digit, two tabs before the third digit, and so on. You can do it by making a string tabs variable, and adding a "\t" to it after each iteration:
string tabs = "";
for (j = i - 1; j > 0; j--) {
Console.WriteLine(tabs + hexadecimalNumber[j]);
tabs += "\t";
}
Demo on ideone.
Related
Is there an algorithm for calculating a factorial without using System.Numerics library? We receive an int number and we need to return factorial of this number as string(if n = 30, we should return "265252859812191058636308480000000", if n = 70, we should return "11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000" ect. Numbers are very big)
I tried to find out, did anyone already write an article about that, but I didn't find anything.
It suffices to implement multiplication of a large number as a string by a small integer.
Illustration: 12! = 11! x 12 is obtained by multiplying every digit by 12 and summing (with shifts):
39916800
36
108
108
12
72
96
0
0
---------
479001600
A lazy solution. It is possible to evaluate the factorial with just BigNum addition, replacing the multiplications by successive additions. (For n!, we will perform 1+2+3+...n-1 additions. This is acceptable for moderate n.)
The computation uses two pre-allocated string (arrays of char), which are initially filled with null bytes (Writeline skips them). When adding from right to left, we stop when we meet a null.
int n = 20;
// Factorial and temporary string; 100! fits in 158 digits
const int N = 158;
char[] f = new char[N], t = new char[N];
f[N - 1] = '1'; // 1!
// Product up to n by successive additions
for (int i = 2; i <= n; i++)
{
// t= f
f.CopyTo(t, 0);
for (int j = 0; j < i - 1; j++)
{
// f+= t, repeated i-1 times
int c = 0; // Carry
for (int k = N - 1; k >= 0; k--)
{
if (t[k] == 0 && c == 0) break; // Significant part exhausted
int d = Math.Max(0, t[k] - '0') + Math.Max(0, f[k] - '0') + c;
c= d / 10; d = d % 10; f[k] = (char)(d + '0'); // Next carry/digit
}
}
Console.WriteLine(f);
}
Output:
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
6227020800
87178291200
1307674368000
20922789888000
355687428096000
6402373705728000
121645100408832000
2432902008176640000
static string FindFactorial(int n)
{
int[] result = new int[500000];
result[0] = 1;
int resultSize = 1;
for (int x = 2; x <= n; x++)
resultSize = Multiply(x, result, resultSize);
string factorial = "";
for (int i = resultSize - 1; i >= 0; i--)
factorial += result[i].ToString();
return factorial;
}
static int Multiply(int x, int[] result, int resultSize)
{
int carry = 0;
for (int i = 0; i < resultSize; i++)
{
int product = result[i] * x + carry;
result[i] = product % 10;
carry = product / 10;
}
while (carry != 0)
{
result[resultSize] = carry % 10;
carry /= 10;
resultSize++;
}
return resultSize;
}
This will work
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.
can you help me to create a logic for magic square metric. In given example, I have created a code for generate Magic Square for odd numbers like 3x3, 5x5, 7x7 metric and double even numbers like 4×4 , 8×8 but unable to found a proper solution for create single even value magic square metric like 6x6, 10x10 etc.
In current implementation anyone can enter a number (n) in input and it will create a nxn magic square metric. But not working fine with single even numbers
class Program
{
public static void Main(string [] args )
{
Console.WriteLine("Please enter a number:");
int n1 = int.Parse(Console.ReadLine());
// int[,] matrix = new int[n1, n1];
if (n1 <= 0)
{
Negativ();
}
else if (n1 == 2)
{
Zwei();
}
else if ((n1 != 2) && !(n1 < 0) && (n1 % 2 != 0))
{
Odd (n1 );
}
else if ((n1 != 2) && !(n1 < 0) && ((n1 - 2) % 4 == 0))
{//singl Even
SingleEven(n1);
}
else if ((n1 != 2) && !(n1 < 0) && (n1 % 4 == 0))
{
DoubleEven (n1);
}
}
private static void Negativ(){
Console.WriteLine("Sorry, the number must be positive and greater than 3 ");
Console.ReadLine();
}
public static void Zwei(){
Console.WriteLine("Sorry,there is no magic square of 2x2 and the number must be and greater than 3 ");
Console.ReadLine();
}
public static void Odd ( int n)// odd method
{
int[,] magicSquareOdd = new int[n, n];
int i;
int j;
// Initialize position for 1
i = n / 2;
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 (magicSquareOdd[i, j] != 0)
{
j -= 2;
i++;
continue;
}
else
{
//set number
magicSquareOdd[i, j] = num++;
//1st condition
j++; i--;
}
}
// print magic square
Console.WriteLine("The Magic Square for " + n + " is : ");
Console.ReadLine();
for ( i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
Console.Write(" " + magicSquareOdd[i, j] + " ");
Console.WriteLine();
Console.ReadLine();
}
Console.WriteLine(" The sum of each row or column is : " + n * (n * n + 1) / 2 + "");
Console.ReadLine();
}
public static void SingleEven(int n )
{
// int n = magic .Length ;
int[,] magicSquareSingleEven = new int[n, n];
int halfN = n / 2;
int k = (n - 2) / 4;
int temp;
int[] swapcol = new int[n];
int index = 0;
int[,] minimagic = new int[halfN, halfN];
*Odd(minimagic) ;* // here is the problem
for (int i = 0; i < halfN; i++)
for (int j = 0; j < halfN; j++)
{
magicSquareSingleEven[i, j] = minimagic[i, j];
magicSquareSingleEven[i+ halfN , j+halfN ] = minimagic[i, j]+ halfN *halfN ;
magicSquareSingleEven[i, j + halfN] = minimagic[i, j] +2* halfN * halfN;
magicSquareSingleEven[i + halfN, j] = minimagic[i, j] +3* halfN * halfN;
}
for (int i =1; i< k ;i ++)
swapcol [index ++]=i ;
for (int i = n-k+2; i <= n ; i++)
swapcol[index++] = i;
for (int i =1; i<=halfN ;i ++)
for (int j = 1; j<= index ; j ++)
{
temp = magicSquareSingleEven[i - 1, swapcol[j - 1] - 1];
magicSquareSingleEven[i-1,swapcol[j-1]-1]=magicSquareSingleEven[i +halfN-1,swapcol[j-1]-1];
magicSquareSingleEven[i+halfN-1,swapcol[j-1]-1]=temp;
}
//swaping noses
temp=magicSquareSingleEven[k,0];
magicSquareSingleEven[k,0]=magicSquareSingleEven[k+halfN,0];
magicSquareSingleEven[k+halfN,0]=temp;
temp=magicSquareSingleEven[k+halfN,k];
magicSquareSingleEven[k+halfN,k]=magicSquareSingleEven[k,k];
magicSquareSingleEven[k,k]=temp;}
//end of swaping
// print magic square
Console.WriteLine("The Magic Square for " + n + " is : ");
Console.ReadLine();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write(" " + magicSquareSingleEven[i, j] + " ");
Console.WriteLine();
Console.ReadLine();
}
Console.WriteLine(" The sum of each row or column is : " + n * (n * n + 1) / 2 + "");
Console.ReadLine();
}
I wrote this code to order any set of numbers from biggest to smallest, but for whatever reason, the output always has a zero at the end. My question is, where did it come from? (new to coding)
Console.WriteLine("Please enter set of numbers");
int input = Convert.ToInt16(Console.ReadLine());
int counter= 1;
int temp1;
int temp2;
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
for (int x = 0; x <= input; x++)
{
for (int i = 1; i <=input; i++)
{
if (array[i - 1] <= array[i])
{
temp1 = array[i - 1];
temp2 = array[i];
array[i - 1] = temp2;
array[i] = temp1;
}
}
}
Console.WriteLine();
for (int i = 0; i<=input; i++)
{
Console.Write(array[i] + " ");
}
Console.ReadLine();
You're inconsistent between whether you're trying to handle input + 1 or input elements. For example:
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
You're creating an array with input + 1 elements, but only populating input of them.
In general, it's much more common to use exclusive upper boundaries for loops. For example:
int[] array = new int[input];
for (int i = 0; i < input; i++)
{
// No need for the counter variable at all
Console.WriteLine("Please enter entry number " + (i + 1));
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
}
I am trying to achieve the following:
User enters 100 numbers and then the numbers are printed in 3 columns.
This is what I have so far, it works but it does not print the last value of the array.
What am I doing wrong?
static void Main(string[] args)
{
int digit = 0;
const int LIMIT = 100;
int[] row = new int[LIMIT];
for (int i = 0; i < row.Length; i++)
{
Console.WriteLine("Geef getal nummer " + (i + 1) + " in: ");
digit = int.Parse(Console.ReadLine());
row[i] = digit;
}
for (int i = 0; i < row.Length - 2; i+=3)
{
Console.WriteLine(row[i] + "\t" + row[i + 1] + "\t" + row[i + 2]);
}
}
Use this print instead
for (int i = 0; i < row.Length; i++)
{
Console.Write(row[i] + "\t");
if (i % 3 == 2)
Console.WriteLine();
}
Your issue is that you don't simply use Console.Write, and try to write your lines in one shot.
In fact, it would be even cleaner to use a StringBuilder here.
Replace
for (int i = 0; i < row.Length - 2; i+=3)
{
Console.WriteLine(row[i] + "\t" + row[i + 1] + "\t" + row[i + 2]);
}
by
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < row.Length; i++)
{
count++;
if (count == 3)
{
sb.AppendLine(row[i])
count = 0;
}
else
sb.Append(row[i]).Append('\t');
}
Console.WriteLine(sb.ToString());
I think it's pretty explicit, but if you need clarifications, feel free to ask. Of course, the use of count here is pretty scholar, a real program could use % operator, like shown in other answers.
You have wrong condition in for loop. If you don't mind LINQ, you can use the following:
foreach (string s in row.Select((n, i) => new { n, i })
.GroupBy(p => p.i / 3)
.Select(g => string.Join("\t", g.Select(p => p.n))))
Console.WriteLine(s);
If you're not ok with LINQ, you can do this:
int colIndex = 0;
foreach (int n in row)
{
Console.Write(n);
if (colIndex == 2)
Console.WriteLine();
else
Console.Write('\t');
colIndex = (colIndex + 1) % 3;
}
jonavo is correct.
after 96+3 = 99
and you have done row.length-2, change it to row. length+2.
and in print dont print if the i+1 or I+2 >= max
It doesn't print it because 100 is not evenly divisible by 3 and your for-loop increases the variable by 3 on each iteration, so the last element wil be skipped.
Maybe this after the loop:
int rest = row.Length % 3;
if(rest > 0)
Console.WriteLine(row[row.Length - rest] + "\t" + row.ElementAtOrDefault(row.Length - rest + 1));
Its because of your index.
Your running index i goes from
0, 3, 6, 9, ... 96, 99
So this would output the array positions:
0,1,2 3,4,5 6,7,8 9,10,11 ... 96,97,98 99,100,101 (index out of bounds)
row.Length equals 100, so your loop-condition (i < row.Length - 2) is correct, but even better would be (i < row.Length - 3).
So your problem is how to print the last number... You see, you have 3 columns for 100 digits. This makes 33 rows and than there is one digit left.
Maybe you just add some Console.WriteLine(row[row.Length-1]); beneeth your loop.
Looks like you've got a lot of options at your disposal. Here's an approach using nested loops:
int numCols = 3;
for (int i = 0; i < row.Length; i += numCols)
{
for (int j = i; j < i + numCols && j < row.Length; j++)
{
Console.Write(row[j] + "\t");
}
Console.WriteLine();
}
Try this code.
Using this loop you can also change the number of rows/columns without code changes. Also, using the temporary buffer you output to the console an entire row at a time.
static void Main(string[] args)
{
int digit = 0;
const int LIMIT = 10;
const int COLS = 3;
int[] row = new int[LIMIT];
for (int i = 0; i < row.Length; i++)
{
Console.WriteLine("Geef getal nummer " + (i + 1) + " in: ");
// Re-try until user insert a valid integer.
while (!int.TryParse(Console.ReadLine(), out digit))
Console.WriteLine("Wrong format: please insert an integer number:");
row[i] = digit;
}
PrintArray(row, COLS);
// Wait to see console output.
Console.ReadKey();
}
/// <summary>
/// Print an array on console formatted in a number of columns.
/// </summary>
/// <param name="array">Input Array</param>
/// <param name="columns">Number of columns</param>
/// <returns>True on success, otherwise false.</returns>
static bool PrintArray(int[] array, int columns)
{
if (array == null || columns <= 0)
return false;
if (array.Length == 0)
return true;
// Build a buffer of columns elements.
string buffer = array[0].ToString();
for (int i = 1; i < array.Length; ++i)
{
if (i % columns == 0)
{
Console.WriteLine(buffer);
buffer = array[i].ToString();
}
else
buffer += "\t" + array[i].ToString();
}
// Print the remaining elements
if (array.Length % columns != 0)
Console.WriteLine(buffer);
return true;
}
Just for completeness
Note that int.Parse(Console.ReadLine()) can throw an Exception if unexpected characters are typed. It's better to use int.TryParse() as documented here. This method don't throw an exception but return a boolean that report a successful conversion.
while (!int.TryParse(Console.ReadLine(), out digit))
Console.WriteLine("Wrong format: please insert an integer number:");
This code tell the user that the typed string can't be interpreted as an integer and prompt again until a successful conversion is done.