C# | Usando el bucle foreach en arreglos

El lenguaje C# proporciona varias técnicas para leer una colección de elementos. Uno de los cuales es bucle foreach . El bucle foreach proporciona una forma sencilla y limpia de iterar a través de los elementos de una colección o una array de elementos. Una cosa que debemos saber es que antes de usar el bucle foreach debemos declarar la array o las colecciones en el programa. Porque el bucle foreach solo puede iterar cualquier array o colección que se haya declarado previamente. No podemos imprimir una secuencia de números o caracteres usando un bucle foreach como un bucle for, vea a continuación:

for(i = 0; i <= 10; i++)
// we cannot use foreach loop in this way to print 1 to 10
// to print 1 to 10 using foreach loop we need to declare 
// an array or a collection of size 10 and a variable that 
// can hold 1 to 10 integer

Sintaxis del bucle foreach:

foreach (Data_Type variable_name in Collection_or_array_Object_name)
 {
   //body of foreach loop
 }
// here "in" is a keyword

Aquí Data_Type es un tipo de datos de la variable y variable_name es la variable que iterará la condición del ciclo (por ejemplo, for(int i=0; i<10;i++), aquí i es equivalente a variable_name). La palabra clave in utilizada en el ciclo foreach para iterar sobre el elemento iterable (que aquí es la array o las colecciones). La palabra clave in selecciona un elemento del elemento iterable o la array o colección en cada iteración y lo almacena en la variable (aquí variable_name).

Ejemplo 1: a continuación se muestra la implementación del bucle «for» y «foreach» utilizando arrays

// C# program to show the use of
// "for" loop and "foreach" loop
using System;
  
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // initialize the array
        char[] arr = {'G', 'e', 'e', 'k', 's', 
                        'f', 'o', 'r', 'G', 'e', 
                                 'e', 'k', 's'};
          
  
        Console.Write("Array printing using for loop = ");
  
        // simple "for" loop
        for (int i = 0; i < arr.Length; i++)
        {
            Console.Write(arr[i]);
        }
  
        Console.WriteLine();
  
        Console.Write("Array printing using foreach loop = ");
  
        // "foreach" loop
        // "ch" is the variable
        // of type "char"
        // "arr" is the array 
        // which is going to iterates
        foreach(char ch in arr)
        {
            Console.Write(ch);
        }
    }
}
Producción:

Array printing using for loop = GeeksforGeeks
Array printing using foreach loop = GeeksforGeeks

Ejemplo 2: Recorrido de una array usando el bucle «foreach»

// C# program to traverse an 
// array using "foreach" loop
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        char[] s = {'1', '4', '3', '1',
                    '4', '3', '1', '4',
                                  '3'};
        int m = 0, n = 0, p = 0;
  
        // here variable "g" is "char" type
        //'g' iterates through array "s"
        // and search for the numbers 
        // according to below conditions
        foreach(char g in s)
        {
            if (g == '1')
                m++;
            else if (g == '4')
                n++;
            else
                p++;
        }
        Console.WriteLine("Number of '1' = {0}", m);
        Console.WriteLine("Number of '4' = {0}", n);
        Console.WriteLine("Number of '3' = {0}", p);
    }
}
Producción:

Number of '1' = 3
Number of '4' = 3
Number of '3' = 3

Nota: En cualquier lugar dentro del alcance del bucle foreach, podemos salir del bucle usando la palabra clave break y también podemos ir a la siguiente iteración del bucle usando la palabra clave continue .

Ejemplo: usar la palabra clave «continuar» y «romper» en el bucle foreach

// C# program to demonstrate the use 
// of continue and break statement
// in foreach loop
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // initialize the array
        int[] arr = {1, 3, 7, 5, 8,
                      6, 4, 2, 12};
  
        Console.WriteLine("Using continue:");
          
        foreach(int i in arr)
        {
            if (i == 7)
                continue;
            // here the control skips the next
            // line if the "i" value is 7
  
            // this line executed because 
            // of the "if" condition
            Console.Write(i + " ");
  
        }
  
        Console.WriteLine();
        Console.WriteLine("Using break:");
          
        foreach(int i in arr)
        {
              
            if(i == 7)
            // here if i become 7 then it will 
            // skip all the further looping 
            // statements
                break;
            Console.Write(i +" ");
        }
    }
}

Producción:

Using continue:
1 3 5 8 6 4 2 12 
Using break:
1 3 

Publicación traducida automáticamente

Artículo escrito por SoumikMondal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *