Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So we have to have code that swaps the integers in a two-digit number, such as "43" being "34". The user inputs a random two digit number and that number must be swapped.
I am not sure how to separate or mess with the two digit number that the user inputs into the console, so I have not had much luck in doing this.
static void Main(string[] args)
{
Console.WriteLine("Please enter a two-digit integer");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
Console.ReadKey();
}
You can also just reverse the string before you parse it:
string input = string.Concat(Console.ReadLine().Reverse());
// If the user entered "34", 'input' will equal "43"
You can try modulo arithmetics:
number = number % 10 * 10 + number / 10;
you could do:
Console.WriteLine("Enter a No. to reverse");
int Number = int.Parse(Console.ReadLine());
int Reverse = 0;
while(Number>0)
{
int remainder = Number % 10;
Reverse = (Reverse * 10) + remainder;
Number = Number / 10;
}
Console.WriteLine("Reverse No. is {0}",Reverse);
Console.ReadLine();
this will give you 34 if you entered 43.
You can checkout this https://www.c-sharpcorner.com/blogs/reverse-a-number-and-string-in-c-sharp1 for more info.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm doing a counting program and i need to multiple all digits of x number by it self.
for example: number 123456789;
1*2*3*4*5*6*7*8*9=362,880
A good solution is provided in the comments, but it isn't very easy to follow if you are trying to figure out what you are actually doing. The following code is a bit more verbose, but shows you what is actually happening each step of the way:
using System;
class MainClass {
public static void Main () {
int myNumber = 123456789; //store original number
int newNumber = (int)Math.Abs(myNumber); //changes the number to positive if it is negative to prevent string formatting errors.
int product = 1; //store product start point
string myString = newNumber.ToString(); //convert number to string
foreach(char number in myString){ //loop through string
string numberString = number.ToString(); //convert chars to strings to ensure proper output
int oneDigit = Convert.ToInt32(numberString); //convert strings to integers
product = product*oneDigit; //multiply each integer by the product and set that as the new product
}
if(myNumber < 0){product = -product;}
//if the number is negative, the result will be negative, since it is a negative followed by a bunch of positives.
//If you want your result to reflect that, add the above line to account for negative numbers.
Console.WriteLine(product); //display product
}
}
Output>>> 362880 //The output that was printed.
So we start by converting our number into a string so we can iterate through it. Then we have a foreach loop that goes through each character in the string, converts it into an integer, and multiplies it by the product of the previous numbers. Each time a new multiplication is performed, the product is updated, until, when you reach the end of the number, you have the product of all digits. This is a good project to become familiar with looping. I would recommend playing around with variations of it such as multiplying each number by the original number, multiplying together only multiples of 3, only multiplying numbers less than 5, or only multiplying the first 5 numbers to get a better handle on what's happening in a loop.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to make some sort of mastermind game in the console where the computer generates a 3 digit code and you have to guess it. The computers also tells you which digit you get right after you take a guess. How would i best do this? I don't know a way to "chop up" input so that i can make the computer check it against the digit it has.
example:
computer generates random code: 123
you guess: 321
computer : -*- (the star indicates which digit you got right)
I have an idea about how i'd indicate what digits are right or not, but i don't know how to separate the input into parts
Convert the computer generated random number into a string. The user input is given as string anyway.
The string type has an indexer allowing you to access single characters
string s = "abc";
char a = s[0];
char b = s[1];
char c = s[2];
for (int i = 0; i < s.Length; i++) {
Console.WriteLine($"s[{i}] = '{s[i]}'");
}
You write char literals as
char ch = 'x';
using single quotes.
Example:
string userInput = Console.ReadLine();
int code = SomehowGenerateRandomCode();
string codeString = code.ToString();
// Let's assume that both numbers have 3 digits.
for (int i = 0; i < 3; i++) {
if(userInput[i] == codeString[i]) {
// digits are equal
} else {
// digits are different
}
}
To split an int to its digits you can convert to string an split like:
int i = 123;
string myInt = i.ToString();
List<int> digits =new List<int>();
foreach (char c in myInt)
{
digits.Add(int.Parse(c.ToString());
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i solved an assignment question on my own but i seems not to be able to print an else statement successfully even though the code works.
The questions is below,
Create a program that prompts the user for the first number. Show on the screen which number was chosen and if the
Number is greater than 10 then show your predecessors until you reach number 10.
My solution is below,
Console.WriteLine("Enter interger please: ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine();
for (int num3 = num; 10 <= num3; num3-- )
{
if (num > 10)
{
Console.WriteLine(num3);
}
else
{
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
}
Well it's normal that in doesn't enter the else statement. You're doing if (num > 10) and num is the value entered by the user which never changes during the process. So if num = 15 you're always doing is 15 > 10.
Then only moment the else statement is gonna print is if the number entered is 10.
And the moment num is smaller than 10, you'll never get in the for loop so the number will never be smaller than 0 inside the loop so that line won't make sense even if it's played
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
Cause like i said if this line is printed that means the value in num was 10 which is not less than zero.
You could change it for something like this
if(num < 10)
{
Console.WriteLine("It's smaller than 10");
}
for(int num3 = num; 10 <= num3; num3--)
{
Console.WriteLine(num3);
}
You're decrementing "num3" on the for loop, but you're validating if "num" is greater than 10 which, by entering the loop in the first place, will always be true.
Change to:
if (num3 > 10)
{
Console.WriteLine(num3);
}
Are you able to provide the question?
The code you have written seems a little meaningless.
Firstly, the for loop will only run if you enter an integer >= 10
Rewriting your code:
Console.WriteLine("Please enter a positive integer: ");
var args = Console.ReadLine();
if (int.TryParse(args, out int num))
{
if (num < 0)
Console.WriteLine('Must enter a positive integer!');
for (var i = num; i >= 10; i-- )
{
//this only runs if the integer entered is >= 10
if (num > 10)
{
Console.WriteLine(i);
}
}
}
else
{
Console.WriteLine("A non-integer was entered!");
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a homework assignment and I am stuck on a certain part of the question.
How do I loop numbers regarding the readline statement.
In other words, suppose I have two numbers that I want to input. Instead of typing out the readline statement twice, how do I get a loop that would allow me to type the readline statement once?
have two numbers that I want to input. Instead of typing out the readline statement twice, how do I get a loop that would allow me to type the readline statement once
Well, if you want two numbers, then you're going to need two variables (or an array), so I assume you're trying to change this:
int firstNumber;
int secondNumber;
firstNumber = int.Parse(Console.ReadLine());
secondNumber = int.Parse(Console.ReadLine());
into something like this:
int[] myNumbers = new int[2];
for(int i = 0; i < 2; i++)
{
myNumbers[i] = int.Parse(Console.ReadLine());
}
but think about this:
Will the prompt be the same for both numbers? Or will the prompt change between inputs
Is it easier to assess the variables independently versus a part of the array/list?
Will having the numbers in a structure benefit other parts of my app (looping to get a sum, etc.)
I think a loop as fine so long as you don't end up with logic inside the lop that changes depending on which number you're using:
int[] myNumbers = new int[2];
for(int i = 0; i < 2; i++)
{
if i == 0 // bad
string prompt = "Enter the first number";
else
string prompt = "Enter the second number";
Console.WriteLine(prompt);
myNumbers[i] = int.Parse(Console.ReadLine());
}
int[] myInputs = new int[2];
for(int i=0; i < 2; ++i)
{
myInputs[i] = Int32.Parse(Console.ReadLine());
}
After this, myInputs[0] is the first value, and myInputs[1] is the second value.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Im writing a program that asks the console for x numbers from the console. If they pick the number 4, then 4 different numbers should be stored. Then the program must store all these inputed numbers in an array, and then add the numbers together and print it out in the console.
So, i tried to do:
Console.WriteLine("Write out a number: ");
int[] x = int[].Parse(Console.ReadLine());
and apparently you cant read in array elements from the console on that way, so do I need to store them inside an variabel and then add them to an new array?
Console.Writeline("Enter the number of numbers to add: ");
//Yes, I know you should actually do validation here
var numOfNumbersToAdd = int.Parse(Console.Readline());
int value;
int[] arrayValues = new int[numOfNumbersToAdd];
for(int i = 0; i < numOfNumbersToAdd; i++)
{
Console.Writeline("Please enter a value: ");
//Primed read
var isValidValue = int.TryParse(Console.Readline(), out value);
while(!isValidValue) //Loop until you get a value
{
Console.WriteLine("Invalid value, please try again: "); //Tell the user why they are entering a value again...
isValidValue = int.TryParse(Console.Readline(), out value);
}
arrayValues[i] = value; //store the value in the array
}
//I would much rather do this with LINQ and Lists, but the question asked for arrays.
var sum = 0;
foreach(var v in arrayValues)
{
sum += v;
}
Console.Writeline("Sum {0}", sum);