Get matching index for a number in array - c#

I'm new to programming and I've got confused on how to display the index number of a value in an array. I want to be able to type a random number and if the number I have entered is in the array, then it should tell me what the position (index) of the number is within the array.
For example if I enter the number 6, and 6 is in my array and it's index is 4, then the output should be "That number exists, it is positioned at 4 in the array". I've tried to do this but my code is the reverse of this, for example if I type in 6, then it looks for index 6 and outputs the number corresponding to index 6.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace searcharray
{
class Program
{
static void Main(string[] args)
{
int n = 10;
Random r = new Random();
int[] a;
a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = r.Next(1, 100);
for (int i = 1; i <= n; i++)
Console.WriteLine(" a [" + i + "] = " + a[i]);
Console.ReadLine();
Console.WriteLine("Enter a number: ");
int b = Convert.ToInt32(Console.ReadLine());
if (a.Contains(b))
{
Console.WriteLine("That number exists and the position of the number is: " + a[b]);
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
Console.WriteLine();
Console.ReadLine();
}
}
}

You can use Array.IndexOf(gives you the index of given value in Array) instead of a[b] like this:
if (a.Contains(b))
{
Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}

You need to use Array.IndexOf() like below:
Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));

Array.IndexOf returns -1 if the item dont exists in the array
var itemIndex = Array.IndexOf(a, b);
if (itemIndex != -1)
{
Console.WriteLine("That number exists and the position of the number is: " + itemIndex);
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}

Related

Write a program that determines whether two or more consecutive numbers are equal

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");
}

Sum up all numbers between two numbers

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();
}

C# Lottery Compare Results

I'm new to C# we have an activity to create a lottery game.
1 matching number won $10
2 matching number won $100
3 matching number not in order $1,000
3 matching number in order won $10,000
I'm having issues with my code even there are 2 matching or 3 matching number it always display $10. Any help would be appreciated.
Below are the source code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LotteryGame
{
class Program
{
static void Main(string[] args)
{
// Matching numbers awards
int rNumMatchOne = 10;
int rNumMatchTwo = 100;
int rNumMatchThree = 1000;
int rNumMatchFour = 10000;
// Generate random numbers
Random randomNum = new Random();
// Integers Declaration
int rNum1;
int rNum2;
int rNum3;
int rNumIput;
int guessNum;
// Arrays Declartion
int[] guessNumMatch = new int[3];
int[] guessNumSort = new int[3];
int[] guessInput = new int[3];
// Restrict inputs between 1 and 4 only
rNum1 = randomNum.Next(1, 5);
rNum2 = randomNum.Next(1, 5);
rNum3 = randomNum.Next(1, 5);
Console.Write("C# Lottery Game\n\n");
Array.Sort(guessNumSort); // sort random numbers
// Guess number input loop
for (rNumIput = 0; rNumIput < 3; rNumIput++)
{
Console.Write("Guess Number " + (rNumIput + 1) + ": ");
guessNum = Convert.ToInt32(Console.ReadLine());
// Invalid input between 1 and 4 program will loop back and enter correct number
while (guessNum < 1 || guessNum > 4)
{
Console.WriteLine("\n");
Console.WriteLine("Invalid Number. Please enter number between 1 and 4. \n");
Console.Write("Guess Number " + (rNumIput + 1) + ": ");
guessNum = Convert.ToInt32(Console.ReadLine());
}
guessNumMatch[rNumIput] = guessNum;
guessNumSort[rNumIput] = guessNum;
}
Array.Sort(guessNumSort);
// Display random numbers and entered numbers
Console.WriteLine();
Console.WriteLine("Generated random numbers are : " + rNum1 + " | " + rNum2 + " | " + rNum3);
Console.WriteLine("Numbers you entered are : " + guessNumMatch[0] + " | " + guessNumMatch[1] + " | " + guessNumMatch[2]);
// Matching 1 number
if (guessNumMatch[0] == rNum1 || guessNumMatch[1] == rNum2 || guessNumMatch[2] == rNum3)
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchOne);
}
// Matching 2 numbers
else if ((guessNumMatch[0] == rNum1 && guessNumMatch[1] == rNum2) || (guessNumMatch[1] == rNum2 && guessNumMatch[2] == rNum3))
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchTwo);
}
// Matching 3 numbers not in order
else if (guessNumSort[0] == guessInput[0] && guessNumSort[1] == guessInput[1] && guessNumSort[2] == guessInput[2])
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchThree);
}
// Matching 3 numbers exact order
else if (guessNumMatch[0] == rNum1 && guessNumMatch[1] == rNum2 && guessNumMatch[2] == rNum3)
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchFour);
}
else // No matching numbers
{
Console.WriteLine("\n");
Console.WriteLine("SORRY, NO MATCHING NUMBERS FOUND! ");
}
Console.WriteLine("\n");
Console.WriteLine("PRESS ANY KEY TO EXIT PROGRAM ");
Console.ReadKey();
}
}
}
Invert the order of your if statements. Check first if 3 numbers are matched in order, then 3 then 2 then 1 and last no match.
Otherwise the first if statement hits true even when there is more than 1 match.
Your first if statement will evaluate to true if at least one of the numbers is correct. For example, if the user guess the 2nd and 3rd number correctly, guessNumMatch[1] == rNum2 will evaluate to true. if(false || true || true) evaluates to true so the statement gets executed. The other if statements will be skipped.
One solution (as Attersson beat me to) is to invert your if statements - check if all 3 are true, then if 2 are true, etc.

How find average of numbers(by input) and also count numbers

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.

Ask user for starting and stopping point within the array?

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();

Categories

Resources