when I enter 1 for n
and 1111 for lines
the sum must be 1+1+1+1=4 but the output is 1.
THIS IS THE QUESTION...
you will get a (n) then (n) lines as an input, In each line there are some numbers (we don’t know how many they are) and you must print (n) lines, In the i-th line print the sum of numbers in the i-th line.
using System;
namespace prom2
{
class Program
{
static void Main(string[] args)
{
int lines=0, sum = 0;
Console.Write("Enter a number of lines ");
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n&n>0&1000>n; i++)
{
Console.WriteLine("Enter line " + i + " numbers");
lines = int.Parse(Console.ReadLine());
lines = lines / 10;
sum += lines % 10;
Console.WriteLine("sum is " + sum);
}
}
}
}
Try this:
static void Main(string[] args)
{
int input;
bool times = true;
List<int> numbers = new List<int>();
while (times)
{
Console.Clear();
Console.WriteLine("Enter number: ");
var num = int.TryParse(Console.ReadLine(), out input);//tryparse will output a bool into num and set input to a int
if (num)
{
numbers.Add(input);//only integers will be added to list
}
Console.Clear();
Console.WriteLine("Another? Y or N");//ask if they want to sum more numbers
var yesno = Console.ReadLine();//get answer from user
if (yesno.ToUpper().Trim() != "Y")//if N or anything else
{
//assume no
times = false;
}
Console.Clear();
}
var sum = numbers.Sum();
Console.WriteLine("Sum : " + sum.ToString());
Console.ReadLine();//just to pause screen
}
Because Console.ReadLine returns a string, and it's possible to treat a string as if it's an array of chars (where char represents a single character), you can have a method like this to calculate the sum of all the digits in a single line:
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
Please note this method contains no validation - ideally you should validate that line is purely numeric, otherwise int.Parse will throw an exception, although the same is true of the code you provided too.
If you want to work with multiple lines of console input, just call this method from within another loop which solicits / works through those lines of console input.
Edit
My answer doesn't answer all of your question, it only answers the part which asks how to calculate the sum of the digits in a numeric string, and it does work, to the extent that it correctly does what it says on the tin.
Here's all the code I wrote to validate the answer before posting the original answer (I wrote it as a xUnit unit test rather than a console application, but that doesn't change the fact that the code I shared works):
using System;
using Xunit;
namespace StackOverflow71442136SumDigits
{
public class UnitTest1
{
[Theory]
[InlineData("1", 1)]
[InlineData("12", 3)]
[InlineData("23", 5)]
[InlineData("1234", 10)]
[InlineData("123456789", 45)]
public void Test1(string line, int expectedSum)
{
var actualSum = this.SumTheDigits(line);
Assert.Equal(expectedSum, actualSum);
}
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
}
}
You might want to read How do I ask and answer homework questions?
Related
I am not sure how to tackle this problem. I tried putting the do while loop in the method GetUserInput and then putting the for loop in the do while loop. It doesn't reset the question it just takes the number and adds it the numbers before it. Its a supposed to be a calculator program.
//This propgram will be used to make a calculator for the class project.
//The numbers are stored as floats as well as the result. Then displayed on console.
//V1 adds a do-while loop that repeats as long as the user wants.
//V2 adds a if and else logic for when the user input a character other than a number the program will close.
//V3 added a for-loop to increase the amount of numbers that can be considered in the calculation. It makes an array
//V4 added methods to get user input and sum the numbers
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello Ulises Sanchez");
//Define 3 floating point numbers to capture the 2 inputs and the result
//floats are used to capture a broader range of numbers
float[] userInput = new float[10];
//stores the number of inputs the user requests
int numberOfUserInputs;
//define strings to store data read and also user prompts
string inputString;
string doMorefunctions = "Add More Numbers Together - y = yes - anything else for no";
//variable to test the condition to continue with calculations
bool moreActions;
do
{
Console.Clear();
numberOfUserInputs = GetuserInput(userInput);
//adds the numbers together
Summation(userInput, numberOfUserInputs);
//reset moreAction
moreActions = false;
Console.WriteLine(doMorefunctions);
inputString = Console.ReadLine();
if (inputString == "y" || inputString == "Y")
moreActions = true;
} while (moreActions);
}
//Gets the number of user inputs and stores each in the userInput array
static int GetuserInput(float[] inputArray)
{
int numberOfInputs;
string userInputPrompt = "How many numbers do you want to enter?";
//string continueMessage = "Hit any key to continue";
string errorMessage = "Invalid Input";
string inputString;
bool TryAgain;
Array.Clear(inputArray, 0, 10);
//Gets number of inputs from user
Console.Write(userInputPrompt);
inputString = Console.ReadLine();
numberOfInputs = int.Parse(inputString);
//Get inputs
for (int i = 0; i < numberOfInputs; i++)
{
Console.Write("Enter variable number {0}: ", i + 1);
inputString = Console.ReadLine();
if (Single.TryParse(inputString, out float result))
{
//if input is valid convert to float
inputArray[i] = float.Parse(inputString);
}
else
{
TryAgain = false;
Console.WriteLine(errorMessage);
inputString = Console.ReadLine();
if (inputString == "y" || inputString == "Y") TryAgain = true;
//if input is not valid input exit program
//Console.WriteLine(continueMessage);
//Console.ReadLine();
//System.Environment.Exit(1);
}
}
return numberOfInputs;
}
//takes the user input and performs a summation calculation
static void Summation(float[] inputArray, int numberOfInputs)
{
float summationResult = 0.0f;
for (int i = 0; i < numberOfInputs; i++)
{
summationResult += inputArray[i];
}
//display result to the screen
Console.WriteLine("Summation = {0}", summationResult);
}
}
We have this concept of "don't repeat yourself" (DRY) so we look for ways to make code that repeats itself not do so. Every one of your methods repeats the print/ReadLine process for asking a question
Let's have a method that asks the user for a string:
public string Ask(string q){
Console.WriteLine(q);
return Console.ReadLine();
}
Now we can say:
string name = Ask("what is your name? ");
Suppose blank input is invalid, let's use a loop to repeat the question:
public string Ask(string q){
string a = "";
while(string.IsNullOrEmpty(a)){
Console.WriteLine(q);
a = Console.ReadLine();
}
return a;
}
If the user gives no answer, they are stuck in the loop and the question is repeated until they give a valid answer
Now let's reuse this to ask for an int:
public int AskInt(string q){
return int.Parse(Ask(q));
}
Here we reuse Ask within AskInt so we don't do the print/read thing again and we leverage the "cannot renter blank" validation we already write
This however explodes if the user enters non ints
So let's use int.TryParse and keep looping while they enter garbage that doesn't parse;
public int AskInt(string q){
bool success = false;
into a=0;
while(!success){
success = int.TryParse(Ask(q), out a);
}
return a;
}
The user can only get to the last line if they enter an int
If you also want to add range validation, for example, you can put an int min, int max into your method parameters and inside the loop do success = success && a <= && a >= min
int guess = AskInt("enter a number between 1 and 10: ", 1, 10);
The idea is to write one method that does one thing really well I.e. "ask the user for a string" and then reuse that when we write the next method that does one thing well, so we end up with two methods that do two things well. Giving the methods a sensible name allows us to package up that bit of logic they do into a few words and make out code read like a book. It doesn't need as many comments then
//ask the user what their next guess is
int guess = AskInt("enter a number between 1 and 10: ", 1, 10);
This comment isn't needed; we can easily deduce the same just by reading the code.
This question already has answers here:
Evaluating string "3*(4+2)" yield int 18 [duplicate]
(13 answers)
Closed 3 years ago.
I created a console application that will take user input of any number and + or - operator for now, and returns the result.
for example user can input 1+2+3+4, and result should be 10.
My problem is that I cannot figure out how to get the last number to be summed into the total result.
that mean in my code only 1+2+3 will be calculated while 4 will be ignored.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace SimpleCalculator
{
public class Program
{
public static void Main()
{
int result = 0;
int number;
string numberString = "";
Console.WriteLine("Enter numbers followed by operation eg. x+y-z");
while (true)
{
string userInput = UserInput();
//Loop into each element of the input string
for (int i = 0; i < userInput.Length; i++)
{
if((IsNumber(userInput[i])))
{
numberString += userInput[i];
}
else if (!IsNumber(userInput[i]))
{
number = Int32.Parse(numberString);
numberString = "";
result = PerformCalculation(result, number, userInput[i]);
}
}
number = Int32.Parse(numberString);
result += number;
Console.WriteLine($"{userInput}={result}");
}
}
// check if input is number or operator
static bool IsNumber(char input)
{
if (char.IsDigit(input)){return true;}
else{return false;}
}
static string UserInput()
{
string User_input = Console.ReadLine();
return User_input;
}
static int PerformCalculation(int sum, int num, char op)
{
switch (op)
{
case '+': return sum + num;
case '-': return sum - num;
default: throw new ArgumentException("Uknown operator");
}
}
}
}
You have already figured out that you are not adding the last number and lets do some thinking to figure out why.
The number will only be added when you call PerformCalculation and whats the condition that this will be called? else if (!IsNumber(userInput[i]))
If you look at your input do you see a non number at the end of the string? if not then PerformCalculation wont get called.
How do you fix that? Before you return the result check if numberString is empty, if not then do the final calculation before returning the result.
Since this is a homework problem i will leave the rest as an exercise.
I'm trying to calculate the number of digit before the floating points. for example
input: 123.4
expected output: 3
my actual output: 5
I'm sure there is something wrong with the digit.equals(".") since the program does not break out of the loop.
this is my code:
public class Program
{
public static void Main()
{
Console.WriteLine(HowManyDigit(123.4));
}
public static Int32 HowManyDigit(Double number)
{
string x = number.ToString();
var counter = 0;
for (int i = 0; i < x.Length; i++)
{
var digit = x[i];
//Console.WriteLine(counter);
if (digit.Equals("."))
{
break;
}
else
{
counter++;
}
}
return counter;
}
}
The reason your code does not work breaks down to this logic:
var digit = x[i];
if (digit.Equals("."))
{
break;
}
The char digit will never be equal to the string "."
If you change your code to:
//Note that I use a char, indicated by ''
if (x[i].Equals('.'))
{
break;
}
Or simply:
if (x[i] == '.')
{
break;
}
Either of those two methods will give you a drastically different result from your current code.
That being said, this method is not really the best way of doing what you want. You can simply use IndexOf() to get the exact number you want:
public static int HowManyDigit(double number)
{
return number.ToString().IndexOf('.');
}
Fiddle here
Just compute the logarithm of base 10 and then convert to integer with floor.
n = Math.Floor(Math.Log10(x))+1;
Try this x.IndexOf('.') this will be your answer
Replace this:
if (digit.Equals("."))
With this:
if (digit.Equals('.'))
Now your output should be 3.
Here is a LINQ solution:
double number = 123.4;
var result = number.ToString().TakeWhile(x => char.IsDigit(x)).Count();
Two problems with my code:
1- I'm getting weird syntax errors with Console.Writeline in Main(), and I think I have a missing right curly brace '}'
2- I can't seem to figure out my first method after Main(). It's just supposed to be a simple void method to write the elements of an array, but Visual Studio seems to think it's either a class or namespace from the errors.
Can anyone spot where I screwed up?
public static void Main(string[] args)
{
//static array for winning[6], empty for player[6], empty for matching[6]
int [] winning = new int [6] {2, 4, 6, 9, 1, 3};
int [] player = new int [6];
int [] matching = new int [6];
int inValue;
//Input loop
Console.WriteLine("Please enter six lotto numbers, between 1 and 9");
for (int i = 0; i < player.Length; i++)
{
inValue = Console.Read();
if (inValue < 1 || inValue > 9) //Validate for int 1-9
{
Console.WriteLine("Please enter a whole number between 1 and 9");
}
winning[i] = inValue;
}
//Output
Console.WriteLine("The winning numbers were:");
DisplayArray(int[] winning);
Console.WriteLine("Your numbers were:");
DisplayArrayContents(int[] player);
Console.WriteLine("You had " + MatchCount() + " matches.");
Console.WriteLine("Your matching numbers are:")
DisplayArrayContents(int[] matching);
Console.Read();
}
//Empty method to display arrays
static void DisplayArray(params int[] args)
{
for (int i = 0; i < args.Length; i++)
{
Console.Write({0} + "\t", array[i]);
}
Console.Write("\n");
}
Edit: Thanks everyone! I forgot to rename some variables and methods in there, but the main problem was a missing ; and unnecessary data types as arguments in Main().
A couple of things to clean up your syntax errors:
1-To display values in your array "args" (this is passed in as a parameter to DisplayArray in your method signature), change "array[i]" to "args[i]".
static void DisplayArray(params int[] args)
{
for (int i = 0; i < args.Length; i++)
{
Console.Write("{0}\t", args[i]);
}
Console.Write("\n");
}
2-When calling DisplayArray, you just need to pass in the instance of the array you want to operate on in the method, so change the calls from:
DisplayArray(int[] winning);
DisplayArrayContents(int[] player);
to:
DisplayArray(winning);
DisplayArrayContents(player);
Good luck!
UPDATE
Here is a working prototype:
class Program
{
static void DisplayArray(params int[] args)
{
for (int i = 0; i < args.Length; i++)
{
Console.Write("{0}\t", args[i]);
}
Console.Write("\n");
}
static void Main(string[] args)
{
//static array for winning[6], empty for player[6], empty for matching[6]
int [] winning = new int [6] {2, 4, 6, 9, 1, 3};
string[] tmp = new string[6];
int [] player = new int [6];
int [] matching = new int [6];
string line;
int inValue;
bool valid;
//Input loop
do
{
Console.WriteLine("Please enter six lotto numbers between 1 and 9, separated by spaces: ");
valid = true;
line = Console.ReadLine();
tmp = line.Split(' '); //split on space
for (int i = 0; i < tmp.Length; i++)
{
int.TryParse(tmp[i], out inValue);
if (inValue < 1 || inValue > 9) //Validate for int 1-9
{
Console.WriteLine("{0} must be a whole number between 1 and 9", tmp[i]);
valid = false;
}
player[i] = inValue;
}
}
while (!valid);
//Output
Console.WriteLine("The winning numbers were:");
DisplayArray(winning);
Console.WriteLine("Your numbers were:");
DisplayArray(player);
//Console.WriteLine("You had " + MatchCount() + " matches.");
//Console.WriteLine("Your matching numbers are:")
//DisplayArrayContents(matching);
//Console.Read();
string retVal = "";
while(retVal != "exit")
{
Console.WriteLine("Type 'exit' to end the program: ");
retVal = Console.ReadLine();
if (retVal == "exit")
Environment.Exit(0);
}
}
}
//Empty method to display arrays
static void DisplayArray(params int[] args)
This should be static void DisplayArray(int[] array), as you're passing in arrays anyhow and there's no need for the performance hit of varargs (that's what you do when you declare the parameter as params int[] args.
Console.Write({0} + "\t", array[i]);
You don't concatenate format strings together like this. You can just use:
Console.Write("{0}\t", array[i]);
Also, array is not defined inside DisplayArray() of your implementation. You've named your parameter args
DisplayArrayContents(int[] matching);
You don't have a DisplayArrayContents method, and you don't need to specify the type of what you're passing in again. The compiler can guarantee type safety at the point of calling, so you would just pass it in by name,
DisplayArray(matching);
Missing a semi-colon here:
Console.WriteLine("Your matching numbers are:")
In your input loop, you are writing the player input to the winning array, which means that they would end up always picking the winning numbers, by virtue of that they just put them in.
You're likely wanting player[i] = inValue;
inValue = Console.Read()
This does not do what you're likely expecting. Try a program with just:
var inValue = Console.Read();
Console.WriteLine(inValue);
and at the console, input 1. You'll get an output different that 1, because Console.Read() return char values.
A combination of Console.ReadLine(), Int32.Parse() and perhaps String.Split() will get you where you need to go.
You should not pass a type along with the parameter when you call a method. So for example DisplayArray(int[] winning); should be just DisplayArray(winning); Fix all those errors and you should be fine.
I am new to C# and was doing this program as an exercise. I have managed to get my program to print the reversed number of the input given by the user, but when I move onto checking whether it is a palindrome or not, it does not calculate the answer correctly. It always prints 'not a palindrome'.
After some error checking, I realized that the reason why it was doing this is because the last number that gets stored in newnum is just the last digit after being reversed and not the entire number. How can I rectify this??
My Code
int i, remainder = 0, newnum = 0;
Console.WriteLine("Enter a Number: ");
int uinput = Convert.ToInt32((Console.ReadLine()));
for (i = uinput; i > 0; i = (i / 10))
{
remainder = i % 10;
Console.Write(remainder);
newnum = remainder;
}
if (newnum == uinput)
{
Console.WriteLine("The Number {0} is a palindrome", uinput);
}
else
{
Console.WriteLine("Number is not a palidrome");
}
Console.WriteLine(uinput);
Console.WriteLine(newnum);
Console.ReadKey();
}
I also looked online at another code example, but the thing I don't understand in that is why num is being converted to boolean type in the while loop? Is that just to keep the loop running?
The Code reffered to above
int num, rem, sum = 0, temp;
//clrscr();
Console.WriteLine("\n >>>> To Find a Number is Palindrome or not <<<< ");
Console.Write("\n Enter a number: ");
num = Convert.ToInt32(Console.ReadLine());
temp = num;
while (Convert.ToBoolean(num))
{
rem = num % 10; //for getting remainder by dividing with 10
num = num / 10; //for getting quotient by dividing with 10
sum = sum * 10 + rem; /*multiplying the sum with 10 and adding
remainder*/
}
Console.WriteLine("\n The Reversed Number is: {0} \n", sum);
if (temp == sum) //checking whether the reversed number is equal to entered number
{
Console.WriteLine("\n Number is Palindrome \n\n");
}
else
{
Console.WriteLine("\n Number is not a palindrome \n\n");
}
Console.ReadLine();
Any sort of help is much appreciated!! Thank You :)
I'm not sure what you're asking, since the second snippet of code you found online should fix your issue.
Your code works, if you just change the line
newnum = remainder;
to
newnum = (newnum*10) + remainder;
The issue in your case is not the condition you used in the for loop, it's just that you're overwriting newnum with the remainder every time, so newnum is only storing the last reminder that was calculated in the loop, "forgetting" all the others it had calculated before.
To reverse the number, every time you enter the loop, you should add the last remainder you've found to the right of newnum, which is effectively equivalent to multiplying everything by 10 and adding remainder.
Try to follow it step by step with pen and paper (or with a debugger).
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i<sNum.Length; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
I think that will do it... Untested!!
As dognose (and Eren) correctly assert you only need to go halfway through
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i < sNum.Length/2; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
You will also need to decide what happend to negative numbers.. ie is -121 a plaindome? This method will say that it isn't...
Easiest way:
public static Boolean isPalindrom(Int32 number){
char[] n1 = number.ToString().ToCharArray();
char[] n2 = number.ToString().ToCharArray();
Array.Reverse(n2);
String s1 = new String(n1);
String s2 = new String(n2);
return (s1 == s2);
}
https://dotnetfiddle.net/HQduT5
you could also use Integers for s1 and s2 and return (s1-s2 == 0)
You have many ways of accomplish this exercise.
A. You can leave the input as string and loop it over, every iteration to check if the value of index 'i' and value of index 'len-i-1' are equals, if not false, otherwise return at the end of the loop true. (the loop should run till i < len/2)
B. You can create a new string and insert the text from end to start and then compare if the original string and result string are equals.
C. there are much more ways without using the string solutions, just with calculation..
int x;
cin<<x; //input the number
int ar[];
int i=0;
temp2=0;
while(x/10 != 0)
{
int temp=x%10;
ar[i]=temp;
x=x/10;
i++;
}
for(int j=0, j<i,j++)
{
temp2=temp2*10+ar[j];
}
if(temp2==x){cout<<"palindrome"}
else {"not palindrome"}
ok here is the logic:
we first input the number x(it can be of any length)..Next we split the number into array..the condition to do this is tha we check for the qoutient to decide whether the number is fully split..next we take the array and rejoin it and check with the input number..
Use the following code:
public boolean isPalindrom(Integer number)
{
return number.Equals(int.Parse(String.Join("", String.Join("", number.ToString().ToCharArray().Reverse().ToArray()))));
}