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();
Related
Write a program that determines whether, in a sequence of N numbers entered by the user, if two or more consecutive numbers are equal. Print out, if any, the position of the first elements of the sequence of equal numbers.
This is what i got so far but it isn't working for some reason. What am I doing wrong?
using System;
public class Exercises
{
static void Main()
{
Console.WriteLine("Insert the length of the sequence of numbers:");
int n = Convert.ToInt32(Console.ReadLine());
List<int> seq = new List<int>();
int equalSeqStart = -1;
for (int i = 0; i < n; i++)
{
Console.WriteLine("Insert the number in position" + (i + 1) + ":");
seq.Add(i);
if ((seq[i] == seq[i - 1]) && (equalSeqStart == -1))
{
equalSeqStart = i - 1;
}
}
if (equalSeqStart != -1)
{
Console.WriteLine("The sequence of equal numbers starts at" + (equalSeqStart));
}
else
{
Console.WriteLine("There is no sequence of equal numbers");
}
}
}
All you have to do is to compare prior item with current one; you have no need in collections:
static void Main() {
Console.WriteLine("Insert the length of the sequence of numbers:");
//TODO: int.TryParse is a better choice
int n = int.Parse(Console.ReadLine());
int equalSeqStart = -1;
for (int i = 0, prior = 0; i < n; ++i) {
Console.WriteLine($"Insert the number in position {i + 1}:");
//TODO: int.TryParse is a better choice
int current = int.Parse(Console.ReadLine());
if (i > 0 && equalSeqStart < 0 && current == prior)
equalSeqStart = i;
prior = current;
}
if (equalSeqStart != -1)
Console.WriteLine($"The sequence of equal numbers starts at {equalSeqStart}");
else
Console.WriteLine("There is no sequence of equal numbers");
}
I've created a program that adds all input values from the user and prints the sum if the user entered 0 or greater than 101. Here's my code:
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
I'm trying to figure how to accepts numbers alternately. For example, Input values are: 4, 7, 8, 3, 6, 1. If the user input two consecutive odd or even number the system will not accept two consecutive odd or even or it will display the sum of all inputted numbers.
Taking the recomendation of Andrew an Peter you can add the list to save your previous inputs and do some checks to the current and prev data to do the logic.
the code that implements this is the following:
//save input list
List<int> inputNumbers = new List<int>();
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
//My Recomendation ==============================
//save previus input numbers
inputNumbers.Add(n);
//Check is there are previous input number
if(inputNumbers.Count>1){
//New control vars
Boolean previousNumberIsOdd= false,currentNumberIsOdd= false;
foreach (int item in inputNumbers)
{
Console.Write(item+",");
}
//check if previus number is odd
if((inputNumbers[inputNumbers.Count-2])%2 == 0){
previousNumberIsOdd = true;
}
//Check if current number is odd
if(n%2==0){
currentNumberIsOdd = true;
}
Console.WriteLine("Control vars:" + previousNumberIsOdd +"/"+currentNumberIsOdd);
//Check diferent scenarios and do the logic
//previous and current number are odds
if(previousNumberIsOdd && currentNumberIsOdd){
//break while and write the result
break;
}
//previous and current number are evens
if(!previousNumberIsOdd && !currentNumberIsOdd){
//break while and write the result
break;
}
}
//if there aren't numbers to break the cycle then do the original logic
//End of my recomendation =====================
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
}
You can do many optimizations to this code but a put it like that to be very clear in the logic.
By using two flag you can achieve the result.
int n, sum = 0;
bool previous = false, current;
bool init = true;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
current = n % 2 == 0;
if( current == previous && !init)
break;
previous = current;
init = false;
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
Output
I have been trying to make a program that you input a number and i keeps asking for numbers untill their sum has reached the number and displays how many numbers it took. the problem i'm facing is that if the last number makes it over the input number it still counts it while it should stop.
static void Main(string[] args)
{
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = 0;`
while (sum < sumLimit)
{
int number = Convert.ToInt32(Console.ReadLine());
sum += number;
count++;
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
}
Here's one option to fix it, depending on your expected result you can let the count start at -1 or 0:
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = -1;
int number = 0;
while (sum + number < sumLimit)
{
sum += number;
count++;
number = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
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 just barely understood how to use if statement and "for loop." In addition right now I have to do this
Sort the integer elements within the array from lowest (element 0) to highest (element 4). Do not use the preexisting Array.Sort method; code your own.
This is a homework problem and I don't even know where to start. Can somebody walk me through this?
class Program
{
static void Main(string[] args)
{
int i;
double power = 0, sum = 0;
int[] mArray = new int[5];
Console.WriteLine("Please Enter Number Between 10 and 50 \nMake sure all of your Number entered correctly \notherwise you will need to enter everything again ");
for (i = 0; i < mArray.Length; i++)
{
Console.WriteLine("Please enter your Number.");
mArray[i] = Convert.ToInt32(Console.ReadLine());
if (mArray[i] >= 50 || mArray[i] <= 10)
{
i--;
Console.WriteLine("Please enter numbers only between 10 and 50.");
}
}
for (i = 0; i < mArray.Length; i++)
{
sum = sum + (mArray[i]);
}
double mean = sum / mArray.Length;
for (i = 0; i < mArray.Length; i++)
{
power += Math.Pow((mArray[i] - mean), 2);
}
double rMean = power / (mArray.Length - 1);
Console.WriteLine("Mean {0}", mean);
Console.WriteLine("Variance {0}", rMean);
Console.WriteLine("Here is sorted numbers");
Console.ReadKey();
}
}
There are many sorting algorithms you can try like Insertion Sort
Selection Sort,
Bubble Sort,
Shell Sort,
Merge Sort,
Heap Sort,
Quick Sort,
And many Others.