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");
}
}
}
CodePudding user response:
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");
}