I am a beginner in C# programming and trying to code a method that ask the user to give a start and an end integer number, then sum up all numbers from the start to the end and in case the given start number is greater than the end number, swap the values so that the start number becomes the end number and the end number gets the value of the start number.
This what I have done so far but I'm not getting the right answer when running the app:
private void SumNumbers()
{
int startNumber, endNumber;
Console.WriteLine("\nplease enter a start number: ");
startNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nplease enter an end number: ");
endNumber = Convert.ToInt32(Console.ReadLine());
int result = 0;
for (int i=0; i<=startNumber; i=i+1)
{
result = result + i;
Console.WriteLine(i);
}
Console.ReadLine();
Console.WriteLine("The sum of Numbers between " + startNumber + " and " + endNumber + " is: " + result.ToString());
Console.ReadLine();
}
I'm getting this result: The sum of Numbers between 12 and 23 is: 78 when the result actually need to 210.
for (int i=0;i<=startNumber;i=i+1)
You are iterating from 0 to startNumber, when really you want to iterate like startNumber to endNumber.
Try
for (int i = startNumber; i <= endNumber; i = i+1)
Below is the working example.
I also added some logic to handle the checking of the input (whether it is correct or no) so the application doesn't break. This way the user experience is much better.
Here is the live working example: code
private void SumNumbers()
{
int startNumber, endNumber;
Console.WriteLine("\nplease enter a start number: ");
do
{
var input1 = Console.ReadLine();
if (Regex.IsMatch(input1, #"^\d+$"))
{
startNumber = Convert.ToInt32(input1); break;
}
else
{
Console.WriteLine("Input provided is invalid. Please enter a correct number: ");
}
} while (true);
Console.WriteLine("\nplease enter an end number: ");
do
{
var input2 = Console.ReadLine();
if (Regex.IsMatch(input2, #"^\d+$"))
{
endNumber = Convert.ToInt32(input2); break;
}
else
{
Console.WriteLine("Input provided is invalid. Please enter a correct number: ");
}
} while (true);
int min = Math.Min(startNumber, endNumber);
int max = Math.Max(startNumber, endNumber);
int result = 0;
for (int i = min; i <= max; i++)
{
result = result + i;
Console.WriteLine(i);
}
Console.WriteLine("The sum of Numbers between " + min + " and " + max + " is: " + result.ToString());
Console.ReadLine();
}
Related
The problem I have is that when I enter an element from the array, the user input resets to the start of the loop, for example when i user input the third element from the array, the user input question two more times to continue to the next user input question, how can I fix this? everybody know what I can adjust here.
worked loop image with 1st element entered
looping error
while (true)
{
String[] bgtype = { "cheeseburger","tlc", "bbq" };
int[] bgtypeprice = { 15, 25, 10 };
int max = bgtype.Length;
String[] product = new string[max];
String[] type = new string[max];
int[] qty = new int[max];
int[] disc = new int[max];
Console.WriteLine("");
for (int i = 0; i < max; i++)
{
Console.Write("What PRODUCT would you like to buy ?: "); ;
product[i] = Console.ReadLine();
if (product[i].Equals("burger", StringComparison.CurrentCultureIgnoreCase))
{
{
Console.Write("What TYPE of product would you like to buy?: ");
type[i] = Console.ReadLine();
if (bgtype[i].Contains(type[i]))
{
Console.Write("Enter your discount % (5% for adults & 7% for minors): ");
disc[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("How many will you buy? ");
qty[i] = Convert.ToInt32(Console.ReadLine());
float total = bgtypeprice[i]; total *= qty[i];
Console.WriteLine("Total cost of " + type[i] + " " + product[i] + " is: " + qty[i] + " pieces x P" + bgtypeprice[i] + "= P" + total);
float totaldisc = 0; totaldisc = (total * disc[i]) / 100;
Console.WriteLine("Total amount of discount: P " + totaldisc);
float totalamt = 0; totalamt = total - totaldisc;
Console.WriteLine("Total cost of order: P " + totalamt);
Console.WriteLine("-------------------ORDER CONFIRMATION-------------------");
}}}}}
if (bgtype[i].Contains(type[i])) should be changed to if (bgtype.Contains(type[i]))
Array.Contains, verifies if an item is contained within an Array, not an Array value. By asking if bgtype[i] contains type[i], you are asking if cheesburger contains tlc, which it doesn't, hence why it starts from the beginning. By verifying if bgtype contains type[i], you are asking if ["cheesburger", "tlc", "bbq"] contains tlc, which it does. I hope this was clear enough.
I have this code where I input a name, and then an integer. The application will then repeat the name entered according to the integer specified. The issue i'm having is, I only want the user to be able to repeat the name a max of 10 times and and min of 1. Here is what i have thus far.
Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();
Console.Write("Enter the number of times you wish for me to repeat your name, " + Name );
int number = Int32.Parse(Console.ReadLine());
for (int i = 0; i < number; i++)
Console.WriteLine(""+ Name);
Console.ReadKey();
EDIT: If someone sees an easier way of doing what I have, I would be happy to suggestions!
You need to filter and validate if the input number is minimum of 1, and maximum of 10, before printing the names. You can do this:
Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();
Console.Write("Enter the number of times you wish for me to repeat your name, " + Name);
int number = 0;
do
{
Int32.TryParse(Console.ReadLine(), out number);
if (number > 10 || number < 1)
Console.WriteLine("Please input numbers between 1 to 10");
} while (number > 10 || number < 1);
for (int i = 0; i < number; i++)
Console.WriteLine("" + Name);
Console.ReadKey();
I am doing a do-while loop here. Unless the while loop is satisfied, it will continuously verify if the number is on the range specified or else it will exit and it will print the names.
static void Main(string[] args)
{
Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();
Console.Write("Enter the number of times you wish for me to repeat your name");
var input = Console.ReadLine();
int number = -1;
while (!int.TryParse(input, out number)) {
Console.WriteLine("Incorrect Value");
Console.Write("Enter the number of times you wish for me to repeat your name");
input = Console.ReadLine();
}
for (int i = 0; i < number; i++)
{
Console.WriteLine("" + Name);
if (i == 9)
{
Console.WriteLine("End Program");
break;
}
}
Console.ReadKey();
}
You could wrap the ReadLine() in a while statement
Example being
int number = -1;
while(number < 1 || number > 10)
{
//Input code
}
//for loop goes under here
I mean how to count and sum input numbers until receive "end".
thanks !
And also how to find out input is number or letter in c#?
class Program
{
static void Main(string[] args)
{
int n = 0;
int sum = 0;
string inp;
do
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num= Convert.ToInt16(inp);
sum = sum + num;
n++;
} while (too == "end");
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
}
}
I would suggest you use a normal while loop and also add validation to check to integer input.
For the while loop you want to loop until the input is not equal to "end":
while(inp != "end")
For the validation, you can use int.TryParse method:
int num = 0;
if (int.TryParse(inp, out num)) { }
Here is a modified example of your code:
int n = 0;
int sum = 0;
string inp = null;
while(inp != "end")
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num = 0;
if (int.TryParse(inp, out num))
{
sum = sum + num;
n++;
}
}
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
// A list to hold all of the numbers entered
List<int> numbers = new List<int>();
// Will hold the inputted string
string input;
// This needs to be outside the loop so it's written once
Console.Write("Numbers: " + Environment.NewLine);
// Keep going until we say otherwise
while (true)
{
// Get the input
input = Console.ReadLine();
// Will hold the outcome of parsing the input
int number = -1;
// Check to see if input was a valid number
bool success = int.TryParse(input, out number);
// If it was a valid number then remember it
// If ANY invalid or textual input is detected then stop
if (success)
numbers.Add(number);
else
break;
}
// Write the count and average
Console.WriteLine("Count:" + numbers.Count);
Console.WriteLine("Average:" + numbers.Average());
Console.ReadLine();
Input:
Numbers:
1
2
3
4
5
Output:
Count: 5
Average: 3
The only thing here a little different to what you specified is ANY invalid or textual entry causes it to finish, not just typing the word "end", although that obviously works too.
I'm trying to get a factorial to be displayed as for example (factorial of 5 is 5*4*3*2*1)
I'm using a method for the factorial, but it doesn't accept the line Console.Write(i + " x "); in my code.
Any help would be great.
here is my code.
//this method asks the user to enter a number and returns the factorial of that number
static double Factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have entered an invalid option");
Console.WriteLine("Please enter a number");
number_str = Console.ReadLine();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
}
Console.Write(i + " x ");
Console.Clear();
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
factorial = 1;
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
Thank you!
The problem is that your for loop isn't using braces, so the scope is just one line.
Try adding braces appropriately:
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i.ToString() + " x ");
}
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
Without the braces, the i variable only exists on the next statement (factorial = factorial * i;), and no longer exists in scope by the time you call Console.Write.
You will likely also want to remove the call to Console.Clear immediately following this Write, or you will not see it.
here's a solution to consider
public static void Main()
{
Console.WriteLine("Please enter number");
int input;
while (!int.TryParse(Console.ReadLine(), out input) || input <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
}
Console.Write("Factorial of " + input + " is : ");
int output = 1;
for (int i = input; i > 0; i--)
{
Console.Write((i == input) ? i.ToString() : "*" + i);
output *= i;
}
Console.Write(" = " +output);
Console.ReadLine();
}
int.TryParse() will be beneficial for you, so the program doesn't crash if the user inputs a non-integer
also, you may want something besides an integer. Factorials get very large very fast - anything over 16 will return a wrong result.
In C# how do i ask user for starting and stopping point within the array?
Below is my code so far:
class Program
{
static void Main(string[] args)
{
double[] num = { 10, 20, 30, 40, 50 };
double n = num.Length;
Console.Write("Elements of, arrary are:" + Environment.NewLine);
for (int i = 0; i < n; i++)
{
Console.WriteLine(num[i]);
}
double sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + num[i];
}
Console.WriteLine("The sum of elements:" + sum);
Console.ReadKey();
}
}
You'll take the sum of the elements between starting and stopping point, as I guess. Take two inputs from the user and assign them to starting and ending points to the for-loop. Such as:
int startingPoint = Convert.ToInt32(Console.ReadLine());
int endingPoint = Convert.ToInt32(Console.ReadLine());
for(int i = startingPoint; i <= endingPoint; i++)
{
//take sum etc.
}
Don't forget to inform the user about the element values in the array and what input value they are entering at that moment.
Another important thing here is to control the inputs. They should be numeric and between 0-n, starting point should be smaller than ending point.
For numeric control you can write like follows:
if (int.TryParse(n, out startingPoint))
{
// operate here
}
else
{
Console.WriteLine("That's why I don't trust you, enter a numeric value please.");
}
startingPoint should be between 0-n and cannot be n. To control it:
if (startingPoint >= 0 && startingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between 0 and " + n + ".");
}
After taking startingPoint successfully, you should control if endingPoint. It should be between startingPoint-n. After controlling for being numeric you can write as follows:
if (endingPoint >= startingPoint && endingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between " + startingPoint + " and " + n + ".");
}
I don't know what can I explain more for this question. Please let me know for further problems.
If you want to prompt the user for the start and end indexes:
Console.WriteLine("Please enter start index");
string startIndexAsString = Console.ReadLine();
int startIndex = int.Parse(startIndexAsString);
Console.WriteLine("Please enter end index");
string endIndexAsString = Console.ReadLine();
int endIndex = int.Parse(endIndexAsString);
var sum = num.Skip(startIndex).Take(endIndex - startIndex + 1).Sum();