C# - Separate integers/strings with division and remainder - c#

I have a homework that I just can't figure out how to do. I'm not sure if the teacher wrote it wrong(he is a bad typer) or if there is a way to accomplish the task.
I work in Visual C# 2010 Express - Console Application
My task is to:
Read a four digit integer, such as 5893, from the keyboard and display the digits separated from one another by a tab each. Use both integer division and modulus operator % to pick off each digit. If the user enters 4567, the output looks like:
4567
4 5 6 7
Sure I know how to separate the numbers by using \t as well as reading the input and displaying it to the user. But how am I supposed to 'pick off' each digit with division and the remainder operators? Maybe he means something else, but not sure.
And another question...
How do I make sure that what the user types in is a number and not a letter?
Do I have to use Char.IsLetter, because I couldn't figure out how to use it on a parsed string.
Example:
string number1;
int x;
Console.Write("Please enter a number to calculate: ");
number1 = Console.ReadLine();
x = Int32.Parse(number1);
What method am I supposed to use and where do i put it in? Because now i only get an error and the application shuts down if I try to enter e letter.

The first question is really more about maths than programming. You know what the division and modulus operators do. Think about how you could use them to get the last (least significant) digit. Once you've done that you can apply a similar technique for the 2nd digit (tens) and then the same for hundreds and thousands and so on.
You've already found Char.IsLetter, but there is also Char.IsDigit, which does what you want more directly. You can do this check for one character and what you have is a string of characters. Have a look at a foreach loop.

System.Int32.TryParse() might be a better choice when converting the String.

Yes, your assignment makes sense. Say you have an integer x = 4567. To pick out the digit at position A you would use:
result = (int)((x / (A * 10)) % 10);
The first part of this (x / (A * 10)) "shifts" x to the right. So a value of A = 1 would divide 4567 by 10 which results in 456.7. You then use the modulo operator "%" to pick out the unit part of that number. Finally you convert to an int to remove the fractional part.

Ok, I won't give the whole solution (after all, this is homework ;)).
This code would check if there's four characters in input:
string input;
do
{
input = Console.ReadLine();
if (input.Length != 4)
Console.WriteLine("You have to enter FOUR digits");
} while (input.Length != 4);
This could be one way of checking the digits:
bool isOk = true;
foreach (char c in input.ToArray())
{
if (!Char.IsDigit(c))
{
Console.WriteLine("You have to enter four DIGITS");
isOk = false;
break;
}
}
This approach doesn't deal with math but you could do that just as well:
int num = int.Parse(input);
int tensOfThousands = num / 10000;
int thousands = (num - tensOfThousands) / 1000;
int lastDigit = num % 10;
//the rest of the digits are up to you ;)

For everybody new to C#, the solution can be simpler.
// Variables
int number = 1234;
int remainder;
string s = "";
while (number > 0) {
remainder = number % 10;
s = remainder + "\n" + s;
number /= 10;
}
Console.Write (s);

Related

C# trying to fill up a binary number to 4 digit blocks

I have a base-n-converter and I wanted it to output all values in 4 digit blocks (1111 -> 1111, 101 -> 0101, 110101 -> 00110101). For this, I made this piece in vscode to try and make it work.
using System;
namespace Test
{
using static intUtilities;
class Program
{
static void Main(string[] args)
{
string number = "";
int[] wholenumbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(;;)
{
Console.WriteLine("enter binary number");
number = Console.ReadLine();
Console.WriteLine("is number length divisible by 4? " + Contains(wholenumbers, number.Length/4f));
Console.WriteLine(number.Length/4f);
while(!Contains(wholenumbers, number.Length/4f))
{
number = "0" + number;
}
Console.WriteLine(number);
Console.ReadLine();
}
}
}
public class intUtilities
{
public static bool Contains(int[] array, float number)
{
foreach(int i in array)
{
if(i == number)
{
return true;
}
else {return false;}
}
return false;
}
}
}
For inputting 111, I am expecting an output of 0111, which does happen, but if I input 111111, I am expecting 00111111, but there is no output. When executing the while loop, it should catch the moment when numbers.Length / 4 is "2" (which is when therre would be 8 digits) and break the loop, but for some reason, it doesnt and keeps on adding zeros to the string. It even reads out numbers.Length / 4 as "2" at some point but doesnt break the loop. The code only seems to work for a target size of 4 digits, where numbers.Length / 4 would be "1". Is there a way to correct that? Or even an easier workaround?
There are a number of "interesting" issues with this code, but to answer your immediate question, you need to remove the else {return false;} line. This prevents you from searching over every element in the wholeNumbers array - or more specifically, you only query the first element in the wholeNumbers array (which is the value 1) which is why the code only works correctly for the first 4-bit block of binary digits.
In the spirit of your approach, a possible implementation is:
void Main()
{
string number = "";
Console.WriteLine("enter binary number");
number = Console.ReadLine();
while (number.Length % 4 != 0)
{
number = "0" + number;
}
Console.WriteLine(number);
}
The original question ('why doesn't this work') is answered by Phillip Ngan.
Just fyi the correct result can be gotten in a simple calculation without a loop:
void Main
{
Console.WriteLine("enter binary number");
string number = Console.ReadLine();
int padLength = (4 - (number.Length % 4)) % 4;
number = "000".Substring(0, padLength)+number;
Console.WriteLine(number);
}
edit: Just noticed this is simply a variant for the solution proposed by John Glenn.
Or even an easier workaround?
Relying on the usual "round an integer up to the nearest N" of "integer, divide by N, add one and times by N" we can use this to pad the left of the binary string out to the next "multiple of 4" up from the current length
var x= "01111";
var y = x.PadLeft(((x.Length/4)+1)*4, '0');
y is "00001111";
If you don't like all the parentheses you can use precedence to the same effect
.PadLeft(x.Length/4*4+4, '0');
Hopefully most future readers of the code will remember their high school maths lessons 😀
You can use the modulus function to determine the remainder of one number (the string length) divided by another number (4). The entire effect can be shortened to this:
// find how many characters don't fit into a block of four
int leftovers = numbers.Length % 4;
// determine how many numbers to pad
int padding =
(4 - leftovers) // this is the number of characters we have to add to get an even group of 4
% 4; // this will ensure that if leftovers is 0, then instead of padding 4 characters we don't pad any
// pad the string
string displayMe = numbers.PadLeft(numbers.Length + padding, '0');

How can I get the last two digits of any 3+ digit integer?

I'm trying to get the last two digits of an int that is a minimum of 3 digits long. Here is my (rather sloppy) attempt:
char[] number = num.ToString().ToCharArray();
int firstnum;
int secondnum;
string strLastTwoDigits = "";
int intLastTwoDigits;
firstnum = number[number.ToString().Length - 1];
secondnum = number[number.ToString().Length - 2];
strLastTwoDigits = (firstnum.ToString() + secondnum.ToString());
intLastTwoDigits = int.Parse(strLastTwoDigits);
The num variable is the number I'm trying to get the last two digits of. I'm trying to turn them into strings and use the string functions to do it, probably not the way it's done. The logic to check whether it's 3 digits or more isn't included, I don't need help with that, just getting those last two digits.
Any ideas?
Do you need those two numbers as a String? Or do you plan to convert them back to a number.
Because if you want to have a number at the end, just use the modulo- operator %.
You can find an example on how to use it here: https://www.dotnetperls.com/modulo
Edit: to state the obvious: last2 = number % 100;
Just perform a modulo operation.
var intLastTwoDigits = num % 100;
You can use the modulo of that number, it should be something like
int lastTwoDigits = num % 100;
This function will divide num / 100and gives you the rest as integer.
If you need the last to digits as int, you could just use modulo:
int lasttwo = num % 100;
the modulo operator (%) will return you the remainder of the division of one integer is by another - in this case your number divided by 100 - the remainder will always be the last two digits
If you want to use strings for that, string.Substring method will help you
var numString = num.ToString();
var strLastTwoDigits = numString.Substring(numString.Length - 2, 2);
var intLastTwoDigits = int.Parse(strLastTwoDigits);
Another (and more simpler option) is to use remainder % operator for that
int intLastTwoDigits = num % 100;
You get a remainder of division into 100, because you need the 2 last digits

Request for explanation of for-loop logic as it is applied in this C# armstrong number checker

Homework alert! I am trying to build a console app to determine whether a given integer is an Armstrong number. I found a working solution online, but after spending far too much time analyzing it, I still don't understand the logic well enough to reproduce it on my own... The two pain points I've identified are 1) I do not understand exactly how the Parse method is acting upon the integer that the user inputs, and 2) the logic sequence of the for loop is not self-evident (see code and my logic description below):
int number, remainder, sum = 0;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
for (int i = number; i > 0; i = i / 10)
{
remainder = i % 10;
sum = sum + remainder * remainder * remainder;
}
if (sum == number)
{
Console.Write("Entered Number is an Armstrong Number");
}
else
Console.Write("Entered Number is not an Armstrong Number");
Console.ReadLine();
This is how my understanding of the for loop logic breaks down:
The integer is passed into the for loop and assigned to int i
//e.g. i = 153//
If the value of i is greater than 0, then re-assign the value of i to i/10 //e.g. 153/10 == 15r3 //
Assign the remainder value of i/10 to int remainder //e.g. remainder = 3//
Compute the sum as sum + remainder * remainder * remainder //e.g. sum = 0 + 3 * 3 * 3//
if the sum is equal to the number, then print "Entered number is Armstrong number" //e.g. however, 27 !== 153//
What am I missing here?
Since this is self-admitted homework, I'm not going to give you a complete answer, but pointers instead.
Make number a string variable. You can then use your for loop to go through each character in the string and perform the math on them.
Use math.pow to create your sum, not sum = sum + remainder * remainder * remainder, since this makes the assumption that you are always using a 3-digit number. (hint: int N = number.Length()
Helper links:
math.pow
Armstrong Numbers

How can you separate a string of numbers to single digits using division and the modulo operator?

Lets say someone enter a four digit number 1234 in the console. How can you separate this number in to 1 2 3 4 using only division and the modulo operator?
public static void MathProblem()
{
Console.WriteLine("Type a four digit number:");
//Ex input: 1234
string inputNumber = Console.ReadLine();
// I'm guessing you first need to parse the
// string as an int in some way?
// And then assign it to some variable
// Now, for seperating the digits to be: 1 2 3 4,
// you can (and must) use both division (/), and the remainder (%).
// The first one will be simple, just dividing value with 1000, but
// how about the others? (Remember, % also need to be used at least
// once)
Console.Write("{0},{1},{2},{3}", value/1000, ?, ?, ?;
}
Any guidelines for making this possible for any given four digit input?
Since this seems like a homework problem, I'll simply explain the method in a few steps rather than giving you the code. Having parsed the input as an integer,
A number modulo 10 allows you to obtain its last digit.
Dividing (integer division) the number by 10 removes the last digit.
Repeat while the number is greater than 0.
int num = int.Parse(inputNumber);
Console.Write(string.Format("{0},{1},{2},{3}", (num/1000) % 100, (num/100) % 10, (num/10) % 10, num % 10));
OR
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
Console.Write("{0},{1},{2},{3}", listOfInts[3], listOfInts[2], listOfInts[1], listOfInts[0]);
No need to do this by division or modulo operators. Use LINQ. You can get an integer array using LINQ as below:
string inputNumber= "1234"
var intList = inputNumber.Select(digit => int.Parse(digit.ToString()));
Then, you can simply use it as you want like this:
Console.Write("{0},{1},{2},{3}", intList[0]/1000, intList[1], intList[2], intList[3]);
Or simply the way you wanted it using Division and Modulo Operator:
public int[] ParseIntString(int number)
{
List<int> digits= new List<int>();
while(number> 0)
{
digits.Add(number% 10);
number= number/ 10;
}
digits.Reverse();
return digits.ToArray();
}
I hope this helps you
int[] values;
Seperate(inputNumber, out values);
Console.Write("{0},{1},{2},{3}", values[0] / 1000, values[1], values[2], values[3]);
Console.ReadKey();
}
public static void Seperate(string numbers, out int[] values)
{
values = new int[numbers.Length];
for (int x = 0; x <= numbers.Length - 1; x++)
{
values[x] = int.Parse(numbers[x].ToString());
}
}
I just started a course in coding and had this as homework as well. I did it in excel first because I thought it was easier than running code over and over and it's more a math problem than a coding one.
Say the number is 4352.
The first digit is easy, it's the integer of the number / 1000 = 4.
Then you simply multilpy by 1000 to get 4000. Remove that and you get 352. The integer of that / 100 is 3.
Then you times that by 100 to get 300 and remove that and you get 52, the integer of that / 10 is 5. Multiply that by 10 and remove that and you're left with 2.
Just read that you must use % so I suggest getting the last number as a modular of 10

Finding the number of places after the decimal point of a Double

I have a Double value:
double a = 4.5565;
What is the easiest way to calculate the number of digits after the decimal point (4 in this case).
I know that I can convert to string and do a split and take the length. But is there an easier way?
There's no easy way, especially since the number of digits mathematically speaking might be far more than displayed. For example, 4.5565 is actually stored as 4.556499999999999772626324556767940521240234375 (thanks to harold for calculating that). You're very unlikely to find a useful solution to this problem.
EDIT
You could come up with some algorithm that works like this: if, as you calculate the decimal representation, you find a certain number of 9s (or zeros) in succession, you round up (or down) to the last place before the series of 9s (or zeros) began. I suspect that you would find more trouble down that road than you would anticipate.
var precision = 0;
var x = 1.345678901m;
while (x*(decimal)Math.Pow(10,precision) !=
Math.Round(x*(decimal)Math.Pow(10,precision)))
precision++;
precision will be equal to the number of significant digits of the decimal value (setting x to 1.23456000 will result in a precision of 5 even though 8 digits were originally specified in the literal). This executes in time proportional to the number of decimal places. It counts the number of fractional digits ONLY; you can count the number of places to the left of the decimal point by taking the integer part of Math.Log10(x). It works best with decimals as they have better value precision so there is less rounding error.
Write a function
int CountDigitsAfterDecimal(double value)
{
bool start = false;
int count = 0;
foreach (var s in value.ToString())
{
if (s == '.')
{
start = true;
}
else if (start)
{
count++;
}
}
return count;
}
I think this might be a solution:
private static int getDecimalCount(double val)
{
int i=0;
while (Math.Round(val, i) != val)
i++;
return i;
}
double val9 = 4.5565d; int count9 = getDecimalCount(val9);//result: 4
Sorry for the duplication -> https://stackoverflow.com/a/35238462/1266873
base on james answer bat much clearer:
int num = dValue.ToString().Length - (((int)dValue).ToString().Length + 1);
num is the exact number of digits after the decimal point.
without including 0 like this(25.520000)
in this case, you will get num= 2
I Think String solution is best : ((a-(int)a)+"").length-2
I'll perhaps use this code if I needed,
myDoubleNumber.ToString("R").Split('.')[1].Length
"R" here is Round Trip Format Specifier
We need to check for the index bounds first of course.
Another solution would be to use some string functions:
private int GetSignificantDecimalPlaces(decimal number, bool trimTrailingZeros = true)
{
var stemp = Convert.ToString(number);
if (stemp.IndexOf(Application.CurrentCulture.NumberFormat.NumberDecimalSeparator) < 0)
return 0;
if (trimTrailingZeros)
stemp = stemp.TrimEnd('0');
return stemp.Length - 1 - stemp.IndexOf(Application.CurrentCulture.NumberFormat.NumberDecimalSeparator);
}
Remember to use System.Windows.Forms to get access to Application.CurrentCulture

Categories

Resources