Loops in CSharp With GPT
Sure, here are some examples of loops in C# using lists of integers and strings.
Example 1: Looping through a list of integers
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List
Console.WriteLine("For Loop:");
for (int i = 0; i < numbers.Count; i++)
{
Console.WriteLine(numbers[i]);
}
Console.WriteLine("Foreach Loop:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Console.WriteLine("While Loop:");
int index = 0;
while (index < numbers.Count)
{
Console.WriteLine(numbers[index]);
index++;
}
}
}
Example 2: Looping through a list of strings
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List
Console.WriteLine("For Loop:");
for (int i = 0; i < names.Count; i++)
{
Console.WriteLine(names[i]);
}
Console.WriteLine("Foreach Loop:");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("While Loop:");
int index = 0;
while (index < names.Count)
{
Console.WriteLine(names[index]);
index++;
}
}
}
Example 3: Using LINQ to loop through lists
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List
List
Console.WriteLine("LINQ Loop for Integers:");
numbers.ForEach(number => Console.WriteLine(number));
Console.WriteLine("LINQ Loop for Strings:");
names.ForEach(name => Console.WriteLine(name));
}
}
Example 4: Nested loops with lists of integers and strings
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List
List
Console.WriteLine("Nested Loops:");
foreach (int number in numbers)
{
foreach (string name in names)
{
Console.WriteLine($"Number: {number}, Name: {name}");
}
}
}
}
These examples cover basic and nested loops using lists of integers and strings in C#.
Imported from rifaterdemsahin.com · 2024