Skip to main content

Exercise Overview

This exercise demonstrates how to work with Lists in Dart using functions. You’ll learn to:
  • Create and populate lists with user input
  • Pass lists to functions
  • Iterate through lists and display their contents

Problem Statement

Create a program that:
1

Create an empty list

Initialize an empty list of integers
2

Get user input

Use a function to ask the user for 10 integer values and add them to the list
3

Display the list

Use another function to print each element of the list

Solution Approach

Function 1: Getting User Input

This function receives a list, populates it with 10 user-provided integers, and returns the modified list:
import 'dart:io';

List<int> pedirNumeros(List<int> numeros){
  for (var i = 0; i < 10; i++) {
    print('Introducir un Valor Entero:');
    numeros.add(int.parse(stdin.readLineSync()!));
  }
  return numeros;
}
When you pass a list to a function in Dart, you’re passing a reference to the list. This means modifications inside the function affect the original list.

Function 2: Displaying the List

This function iterates through the list and prints each value:
void imprimirLista(List<int> numeros){
  for (var numero in numeros) {
    print('El Valor es: $numero');
  }
}
The for-in loop is perfect for iterating through all elements in a collection when you don’t need the index.

Main Function

The main function coordinates the program flow:
void main() {
  List<int> numeros = [];
  pedirNumeros(numeros);
  imprimirLista(numeros);
}

Complete Program

/* Hacer un programa que empleando funciones cree una lista de números enteros y la cargue con 10 valores enteros dados por el usuario.
Ya con la lista cargada imprima cada uno de los elementos de dicha lista.*/

import 'dart:io';

List<int> pedirNumeros(List<int> numeros){
  for (var i = 0; i < 10; i++) {
    print('Introducir un Valor Entero:');
    numeros.add(int.parse(stdin.readLineSync()!));
  }
  return numeros;
}

void imprimirLista(List<int> numeros){
  for (var numero in numeros) {
    print('El Valor es: $numero');
  }
}

void main() {
  List<int> numeros = [];
  pedirNumeros(numeros);
  imprimirLista(numeros);
}

Key Concepts

List Declaration

List<int> numeros = [] creates an empty list of integers

Adding Elements

Use .add() method to append elements to a list

For-In Loop

for (var item in list) iterates through each element

Type Safety

List<int> ensures only integers can be added to the list

List Operations Explained

In Dart, lists are reference types. When you pass a list to a function and modify it, the changes affect the original list. Returning the list is optional but makes the function’s behavior more explicit and allows for method chaining.
// Both work the same way
pedirNumeros(numeros);
// or
numeros = pedirNumeros(numeros);
Regular for loop:
for (var i = 0; i < numeros.length; i++) {
  print(numeros[i]);
}
Use when you need the index.For-in loop:
for (var numero in numeros) {
  print(numero);
}
Use when you only need the values.
Add error handling to make the program more robust:
List<int> pedirNumeros(List<int> numeros){
  for (var i = 0; i < 10; i++) {
    print('Introducir un Valor Entero:');
    try {
      numeros.add(int.parse(stdin.readLineSync()!));
    } catch (e) {
      print('Error: Introduce un número válido');
      i--; // Retry this iteration
    }
  }
  return numeros;
}

Enhanced Version

Here’s an enhanced version with additional features:
import 'dart:io';

List<int> pedirNumeros(List<int> numeros, int cantidad){
  for (var i = 0; i < cantidad; i++) {
    print('Introducir valor ${i + 1} de $cantidad:');
    numeros.add(int.parse(stdin.readLineSync()!));
  }
  return numeros;
}

void imprimirLista(List<int> numeros){
  print('\n=== Lista de Números ===');
  for (var i = 0; i < numeros.length; i++) {
    print('Posición $i: ${numeros[i]}');
  }
  print('\nTotal de elementos: ${numeros.length}');
}

void main() {
  List<int> numeros = [];
  pedirNumeros(numeros, 10);
  imprimirLista(numeros);
}

Practice Challenges

Challenge 1

Modify the program to also calculate and display the sum and average of all numbers entered.

Challenge 2

Add a function to find and display the maximum and minimum values in the list.

Challenge 3

Create a function to sort the list in ascending order before printing.

Challenge 4

Add a function to remove duplicate values from the list.

Build docs developers (and LLMs) love