C #: How to identify the first digit of each number in a vector to count how many numbers start the same?

3

Good day.

I have this problem, I guess it's simple but I have not been able to solve it and I have one day in that, I have a program that accepts 10 numbers and enters them in a vector, but I need to know how many of these 10 start with the number 3 , when I do the code I know all three there are, if for example "33" is entered it says that two numbers start at 3, I have done it using string and int with the same result. If you could help me, Thank you.

using System;

public class Example{

    public static void Main(){
        Console.Clear();

        Console.WriteLine("Programa que acepta 10 numeros y muestra cuantos de estos empiezan con 3.");
        Console.WriteLine();

        int[] n1 = new int [10];
        int cont = 0;

        for(int x = 0; x < 10; x++){

            Console.Write("Digite el {0} numero: ",x+1);
            int.TryParse(Console.ReadLine(), out n1[10]);

            int z = n1[x]%10;


            if(z == 3){

                cont++;

            }

        }
        Console.Write(cont);

        Console.ReadKey();
    }


}

With string

class programa22{

    public static void Main(){
        Console.Clear();

        Console.WriteLine("Programa que acepta 10 numeros y muestra cuantos de estos empiezan con 3.");
        Console.WriteLine();

        string[] n1 = new string[10];
        int cont = 0;

        for(int x = 0; x < 10; x++){

            Console.Write("Digite el {0} numero: ",x+1);
            n1[x] = Console.ReadLine();

            char delimiter = '3';
            string[] substrings = n1[x].Split(delimiter);

            foreach (var substring in substrings)
            cont++;

        }
        Console.WriteLine();
        cont = cont - 10;
        Console.Write("La cantidad de numeros que empiezan con 3 es "+cont);

     Console.ReadKey();
    }
}
    
asked by Brandon 20.03.2018 в 01:00
source

4 answers

1

Taking the first example you put, you should adapt the code as follows

mainly you had an error in

int.TryParse(Console.ReadLine(), out n1[10]);

where you were assigning the value in the index 10 of your array and not in the position corresponding to the for cycle (you should use the variable x )

int.TryParse(Console.ReadLine(), out n1[x]);

your code of the main, should be like this

Console.Clear();

Console.WriteLine("Programa que acepta 10 numeros y muestra cuantos de estos empiezan con 3.");
Console.WriteLine();

int[] n1 = new int[10];
int cont = 0;

for (int x = 0; x < 10; x++)
{
    Console.Write("Digite el {0} numero: ", x + 1);
    int.TryParse(Console.ReadLine(), out n1[x]);

    var numberAsString = Convert.ToString(n1[x]);

    if (numberAsString == "3" || numberAsString.Substring(0, 1) == "3")
        cont++;
}

Console.Write(cont);
Console.ReadKey();

You must convert your entered integer to string and then check if said variable == "3" or if it starts with "3", this is possible thanks to the Substring function that allows you to take the first value of your string (0.1)

    
answered by 20.03.2018 / 02:18
source
2

I would use this function ..

private bool empiezaConTres(int numero)
    {
        int i = Math.Abs(numero);
        while (i >= 10)
            i /= 10;

        return (i == 3);
    }

Then the inquiry as follows

empiezaConTres(33); //responde True
empiezaConTres(43); // responde False

In your case

if(empiezaConTres(n1[x]){cont++;}
//Si retorna verdadero, aumentas el 
    
answered by 20.03.2018 в 15:14
1

Well I also encourage you to present another solution using string s.

using System;

namespace Numeros
{
    class Programa
    {
        public static void Main(string[] args)
        {
            Console.Clear();   
            Console.WriteLine("Programa que acepta 10 números y muestra cuantos de estos empiezan con 3.");
            Console.WriteLine();

            var numeros = new int [10];
            int cont = 0;
            string str = "";

            for (int i = 0; i < 10; i++)
            {
                do{
                    Console.Write("Digite el {0} numero:\t", i + 1);
                    str = Console.ReadLine();

                    if (!Int32.TryParse(str, out numeros[i])) {
                        Console.WriteLine("ERROR. Solo puede ingresar números.");
                    }                   

                } while (!Int32.TryParse(str, out numeros[i]));             

                var cadena = numeros[i].ToString();

                if (cadena.Length > 1) {
                    cadena = cadena.Remove(1);                                      
                }                           
                if (cadena == "3") {
                    cont++;
                }
            }
            Console.WriteLine("La cantidad de números que empiezan con 3 es:\t{0}", cont);
            Console.ReadKey(true);
        }       
    }
}

To begin with I made some small changes regarding the name of the variables. Instead of n1 I have set numeros and as a variable to traverse the elements of the array I have set the classic i .

Secondly, as I see that you are using the TryParse method, it is good to take advantage of the fact that it returns a boolean, to validate that each element of the array that is entered is effectively a number. It is worth noting that in this case, to avoid a do-while within a for loop, it would be best to refactor the validation of each element entered in its own method (I'll leave that as a task).

Once the number has been validated, we proceed to convert it to a chain. Then we analyze if the length of the string is greater than 1. In such case, we proceed to use the method Remove , removing each character of the array from position 1 to the end. Next, we verify if the obtained string (that has length 1) is equal to "3" .

Here it is good to point out that we first verify if the length of the chain is greater than 1. This is because the method Remove throws an exception of type ArgumentOutOfRangeException if the position from where we started does not exist.

Finally, it is good to point out that the verification of those numbers that start at 3 should be refactorized in a proper method, as, for example, it is done in another one of the answers.

    
answered by 20.03.2018 в 15:56
1

I will contribute my granite with LinQ

using System;
using System.Collections.Generic;
using System.Linq;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int[] n1 = new int [10];

            //Relleno los numeros rapido, tu haz a tu manera
            Random ran = new Random();
            for(int i = 0; i < n1.Length; i++)
                n1[i] = ran.Next(100);


            //Que queremos buscar
            string strPattern = "3";

            //Aqui hacemos la cuenta
            int nCount = n1.Where(x=>x.ToString().Substring(0,1) == strPattern).Count();


            //Comprobacion
            n1.ToList().ForEach(x=>Console.WriteLine(x));
            Console.WriteLine(string.Format("Se han encontrado {0} repeticiones",nCount));
        }
    }
}

I leave a link to try it

Example

    
answered by 22.03.2018 в 17:54