Solutions possibles aux exercices de la semaine 3
// 1. Saisir des nombres
static void ex1()
{
int[] nombres = new int[2];
for (int i = 0; i < nombres.Length; i++)
{
Console.Write("Entrez le nombre " + (i + 1) + " : ");
int.TryParse(Console.ReadLine(), out nombres[i]);
}
for (int i = 0; i < nombres.Length; i++)
{
Console.WriteLine(nombres[i]);
}
}
// 2. Plus grand nombre
static void ex2()
{
int[] nombres = [12, 45, 23];
int plusGrand = nombres[0];
for (int i = 1; i < nombres.Length; i++)
{
if (nombres[i] > plusGrand)
{
plusGrand = nombres[i];
}
}
Console.WriteLine("Le plus grand nombre est : " + plusGrand);
}
// 3. Compter les nombres pairs
static void ex3()
{
int[] nombres = [14, 7, 22, 9];
int nombrePairs = 0;
for (int i = 0; i < nombres.Length; i++)
{
if (nombres[i] % 2 == 0)
{
nombrePairs++;
}
}
Console.WriteLine("Nombre de nombres pairs : " + nombrePairs);
}
// 4. Recherche dans un tableau
static void ex4()
{
int[] nombres = [4, 18, 7, 25, 10, 3, 14, 21, 8, 16];
int nombreRecherche;
int position = 0;
bool trouve = false;
Console.Write("Entrez un nombre à rechercher : ");
int.TryParse(Console.ReadLine(), out nombreRecherche);
while (position < nombres.Length && !trouve)
{
if (nombres[position] == nombreRecherche)
{
trouve = true;
}
position++;
}
if (trouve)
{
Console.WriteLine("Le nombre est présent dans le tableau.");
}
else
{
Console.WriteLine("Le nombre n'est pas présent dans le tableau.");
}
}
// 4b. Recherche dans un tableau avec break
static void ex4b()
{
int[] nombres = [4, 18, 7, 25, 10, 3, 14, 21, 8, 16];
int nombreRecherche;
int position = 0;
bool trouve = false;
Console.Write("Entrez un nombre à rechercher : ");
int.TryParse(Console.ReadLine(), out nombreRecherche);
while (position < nombres.Length)
{
if (nombres[position] == nombreRecherche)
{
trouve = true;
break;
}
position++;
}
if (trouve)
{
Console.WriteLine("Le nombre est présent dans le tableau.");
}
else
{
Console.WriteLine("Le nombre n'est pas présent dans le tableau.");
}
}
// 4c. Recherche dans un tableau avec break sans variable "trouve"
static void ex4c()
{
int[] nombres = [4, 18, 7, 25, 10, 3, 14, 21, 8, 16];
int nombreRecherche;
int position = 0;
Console.Write("Entrez un nombre à rechercher : ");
int.TryParse(Console.ReadLine(), out nombreRecherche);
while (position < nombres.Length)
{
if (nombres[position] == nombreRecherche)
{
break;
}
position++;
}
if (position == nombres.Length)
{
Console.WriteLine("Le nombre n'est pas présent dans le tableau.");
}
else
{
Console.WriteLine("Le nombre est présent dans le tableau.");
}
}