How can I remove the last digit in an int (C#)?
I would like to use in c# console, user put 9 digit number and I remove the last digit of number
how should I choose some digit from above for example 1234456782 and i choose 2-4-6-8?
You should try to divide it by 10:
int number = 123456789;
int newNumber= number/10;
Console.WriteLine("new number: {0}", newNumber);
int i = 123456789
int newVal = i/10;
1.
string num = input.ToString();
if (num.Length > 1)
{
num = num.Remove(num.Length - 1, 1);
}
2.
num = num[1] + num[4] + num[6] + num[8];
num -= num % 10;
int num = 123456;
int numMinusUnitsDigit = 10 * (num / 10);
Console.WriteLine("number without Units digit: {0}", numMinusUnitsDigit );
Related
find numbers in an input range that are evenly divisible by 3. Only =, ++, -- operators can be used.
I've tried to get the remainder using shift operators and other loops but I always require a -= or something similar.
Console.Clear();
int n,
d,
count = 1;
// get the ending number
n = getNumber();
// get the divisor
d = 3;// getDivisor();
Console.WriteLine();
Console.WriteLine(String.Format("Below are all the numbers that are evenly divisible by {0} from 1 up to {1}", d, n));
Console.WriteLine();
// loop through
while (count <= n)
{
// if no remainder then write number
if(count % d == 0)
Console.Write(string.Format("{0} ", count));
count++;
}
Console.WriteLine();
Console.WriteLine();
Console.Write("Press any key to try again. Press escape to cancel");
Expected results:
Enter the ending number: 15
Below are all the numbers that are evenly divisible by 3 from 1 up to 15
3, 6, 9, 12, 15
If the == operator is permitted for the assignment, you can have something like
int remainder = 0; // assumes we always count up from 1 to n, we will increment before test
Inside the loop replace the existing if with
remainder++;
if (remainder == 3) {
Console.Write(string.Format("{0} ", count));
remainder = 0;
}
[EDIT: Typo in code corrected]
Think about the underlying maths:
2 x 3 = 3 + 3
3 x 3 = 3 + 3 + 3
4 * 3 = 3 + 3 + 3 + 3
...and so on.
Also, to be evenly divisible by 3 means that the number multiplying 3 must be even.. So...
public bool EvenlyDivisibleBy3(int aNumber)
{
int even = 2;
int currentMultiple = 0;
while (currentMultiple < aNumber)
{
int xTimes = 0;
for (int x = 1; x <= even; x++)
{
((xTimes++)++)++; // add three to xTimes
}
currentMultiple = xTimes;
(even++)++: // next even number
}
return currentMultiple == aNumber;
}
So my homework is I have to take two numbers from the user then I have to write out the odd numbers in that interval.But the code under doesn't work. It writes out "TrueFalseTrueFalse".
int szam;
int szam2=0;
int szam3=0;
int szam4=0;
Console.Write("Please give a number:");
szam = Convert.ToInt32(Console.ReadLine());
Console.Write("Please give another number:");
szam2 = Convert.ToInt32(Console.ReadLine());
if (szam>szam2)
{
for (szam3=szam, szam4 = szam2; szam4 < szam3; szam4++)
{
Console.Write(szam2 % 2==1);
}
}
else
{
for (szam3 = szam, szam4 = szam2; szam3 < szam4; szam3++)
{
Console.Write(szam3 % 2 ==1);
}
}
So if the two numbers would be 0 and 10, the program has to write out 1, 3, 5, 7, and 9
I would be careful when naming your variables yes its a small piece of code but it gets confusing to people trying to read it.
Based on the requirement, I would guess you want all the odd numbers given a certain range.
const string comma = ",";
static void Main(string[] args)
{
int start = getNumber();
int end = getNumber();
if(start > end)
{
int placeHolder = end;
end = start;
start = placeHolder;
}
string delimiter = string.Empty;
for(int i = start; i < end; i++)
{
if(i % 2 == 1)
{
Console.Write(string.Concat(delimiter,i.ToString()));
delimiter = comma;
}
}
Console.ReadLine();//otherwise you wont see the result
}
static int getNumber()
{
Console.Write("Please enter a number:");
string placeHolder = Console.ReadLine();
int toReturn = -1;
if (int.TryParse(placeHolder, out toReturn))
return toReturn;
return getNumber();
}
as Juharr mentioned in the comments, you need to check the result to print the actual number.
Width Linq you can write:
int szam = 20;
int szam2= 30;
var odds = Enumerable.Range(szam2 > szam ? szam : szam2, Math.Abs(szam-szam2))
.Where(x=>x % 2 != 0);
outputs:
21
23
25
27
29
// so we create a range from low to high (Enumerable.Range(..)
// take only the odd values (x % 2 != 0)
simply wrap it in string.Join to make a single string:
string text = String.Join(",",Enumerable.Range(szam2 > szam ? szam :
szam2,Math.Abs(szam-szam2))
.Where(x=>x % 2 != 0));
I wrote a code to find the sum of the digits and the reverse of a number-
static void Main(string[] args)
{
int number, sum = 0;
Console.WriteLine("Enter a number:");
number = int.Parse(Console.ReadLine());
while (number!= 0)
{
int m = number % 10;
number = number / 10;
sum = sum + m;
}
Console.WriteLine("Sum of digits of the number:" + sum);
Console.ReadLine();
int reverse = 0;
while (number!= 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
Console.WriteLine("Reversed Number is:" + reverse);
Console.ReadLine();
}
but, the output for reversed number comes as 0. I checked my code, and I am not sure what is wrong with it.
You modify number as you sum the digits so when you try to go through the second loop, number is already at 0. Save off the input and reset number before the second loop:
Console.WriteLine("Enter a number:");
int input = int.Parse(Console.ReadLine());
number = input;
while (number!= 0)
{
// ...
}
Console.WriteLine("Sum of digits of the number:" + sum);
number = input; // reset number back to original input
// ...
There's also a possible solution to the problem using LINQ:
int number = 1234567890;
int sumOfDigits = number.ToString().Select(c => int.Parse(c.ToString())).Sum();
int reversedNumber = int.Parse(new string(number.ToString().Reverse().ToArray()));
Console.WriteLine($"sum of digits: {sumOfDigits}");
Console.WriteLine($"reversed number: {reversedNumber}");
I have to write a "encryption" program for my C# intro class. I'm encountering 2 problems:
When a negative is entered or it calculates a negative during the decryption process, it crashes. - it returns and unhandled exception error: System.FormatException: Input string was not in a correct format.
The decryption should be the reverse of the encryption without using the original variable. How do you reverse a remainder calculation?
I know it's part of the do while loop that's the issue, I'm just not sure how to continue to prompt for a value if a negative is entered and if encountered during the decryption calculation to keep it from crashing. Any guidance would be much appreciated. Thanks for taking a look at it!
public class MainClass
{
public static void Main(string[] args)
{
int num = 0;
int dnum = 0;
do
{
Console.Write("Please enter a non-negative integer to encrypt: ");
num = Convert.ToInt32(Console.ReadLine());
string numstr = Convert.ToString(num);
string num1 = Convert.ToString(numstr.Substring(0, 1));
string num2 = Convert.ToString(numstr.Substring(1, 1));
string num3 = Convert.ToString(numstr.Substring(2, 1));
string num4 = Convert.ToString(numstr.Substring(3, 1));
int enum1 = ((Convert.ToInt32(num1) + 7) % 10);
int enum2 = ((Convert.ToInt32(num2) + 7) % 10);
int enum3 = ((Convert.ToInt32(num3) + 7) % 10);
int enum4 = ((Convert.ToInt32(num4) + 7) % 10);
Console.WriteLine("Encrypted Integer: {0:D4}", (1000 * enum3 + 100 * enum4 + 10 * enum1 + enum2));
Console.Write("Please enter a non-negative integer to decrypt: ");
dnum = Convert.ToInt32(Console.ReadLine());
string dnumstr = Convert.ToString(dnum);
string num1d = Convert.ToString(dnumstr.Substring(0, 1));
string num2d = Convert.ToString(dnumstr.Substring(1, 1));
string num3d = Convert.ToString(dnumstr.Substring(2, 1));
string num4d = Convert.ToString(dnumstr.Substring(3, 1));
int dnum1 = ((Convert.ToInt32(num1d) - 7) * 10);
int dnum2 = ((Convert.ToInt32(num2d) - 7) * 10);
int dnum3 = ((Convert.ToInt32(num3d) - 7) * 10);
int dnum4 = ((Convert.ToInt32(num4d) - 7) * 10);
Console.WriteLine("Decrypted Integer: {0:D4}", (1000 * dnum1 + 100 * dnum2 + 10 * dnum3 + dnum4));
} while (num > 0);
} // end Main
}// end class
The policy is, do not proceed until user enters a 'correct' input. Here is code sample, note that I use numstr[0] - an index to get the first char instead of numstr.Substring(0, 1) so the code looks cleaner.
int num = 0;
bool isValid = false;
do
{
Console.Write("Please enter 4 digits to encrypt: ");
string numstr = Console.ReadLine();
if (numstr.Length == 4)
{
isValid = Char.IsDigit(numstr[0]) && Char.IsDigit(numstr[1])
&& Char.IsDigit(numstr[2]) && Char.IsDigit(numstr[3]);
}
if (isValid)
num = Convert.ToInt32(input);
}
while (!isValid);
As for your 2nd question, you can't use multiplication to reverse a remainder calculation ((d+7)%10), you should again use remainder operator (d+10-7)%10, the additional 10 is added to keep it from getting negative result.
There is another bug in your decryption process, you can turn to your debugger for help.
I would like to split a two digit int into 2 one digit ints! For example:
20 = 2 and 0
15 = 1 and 5
8 = 0 and 8
That's easy: use % to get the mod of the number, and / for the integer division (i.e. division where the fractional part is discarded).
Your numbers are in the decimal system (i.e. the base is 10) so you divide and mod by 10, like this:
int a = 20 / 10; // 2
int b = 20 % 10; // 0
To print a number digit-by-digit, least significant digit first, you can use this loop:
int a = 12345;
while (a != 0) {
lastDigit = a % 10;
Console.WriteLine(lastDigit);
a /= 10;
}
int i = 45; // or anything you want
int firstDigit = i / 10;
int secondDigit = i % 10;
It's quite simple really.
You can do this for 3-digit numbers using a Modulos and Division operations as well, but I'll let you figure that out by yourself. ;)
Yeah , easy.
int m =2123;
int n=m;
while (n != 0) {
y=n%10; //variable holds each digit out of the number m.
Console.WriteLine(y);
n /= 10;
}
int input = 15;
int first = 0;
int second = Math.DivRem(input, 10, out first);
If you have a array of integers then you can very well use LINQ, else just use any of the below answers.
int num = 86;
int digit1 = num / 10;
int digit2 = num % 10;
Do your numbers have only two digits?