To complete the exercises in this lesson, we require a review of the arrays and lists we learned earlier in this course. This knowledge will equip us with the tools to effectively solve the following exercises: calculating squares of numbers in a list and summing even numbers in an array, reinforcing our understanding of the foreach loops through practical application.

Exercise 1: Square numbers with the foreach loop

Problem statement

Write a foreach loop that outputs the squares of the numbers from a list of integers.
For this exercise, we are primarily focusing on the following:

  • The foreach loop: To iterate over integers in a collection

  • Collection handling: Managing arrays or lists in C#

  • Arithmetic operations: Calculating the square of numbers

  • Control structures: Employing loops for task repetition

Sample input

Input is a collection of integers, for example, [1,3,5].

Expected output

For [1,3,5], the expected output is [1,9,25]. Similarly, if the input is [4,89,54,98,29], the output would be [16,7921,2916,9604,841].

Get hands-on with 1400+ tech skills courses.