Exercises & solutions part 2: Loops
In this section, we will find some basic exercises on loops and lists. All exercises have solutions. Remember that the exercises are for beginners, so the code is not optimized.
Exercise: Print 10 times
Create a program that, given a text, prints it 10 times. For example, given the text Hello world, it should display it ten times.
Exercise: Print odd numbers
Create a program that, given a positive integer, prints all the odd numbers from 1 up to that number. For example, given the number 10, the program will print the numbers 1, 3, 5, 7, 9.
Exercise: Countdown
Create a program that, given a positive integer, prints the countdown from that number to zero. For example, given the number 10, the program will print the numbers 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.
Exercise: Copy and reverse
Create a program that, given a list of numbers, copies the values to another list and reverses them. For example, given the list [1, 2, 3, 4, 5], the program should print:
- The original list is: [1, 2, 3, 4, 5]
- The copy is: [5, 4, 3, 2, 1]
Exercise: Sum of even and odd numbers
Create a program that, given a list of positive integers, prints the sum of the even numbers and the sum of the odd numbers. For example, given the following numbers [3, 2, 3, 4, 5, 6, 1, 7], the sum of even numbers is 12, and the sum of odd numbers is 19.
Exercise: Right triangle
Create a program that, given the height, prints a right triangle like the following:
// Height: 5
*
**
***
****
*****
Exercise: Christmas Tree
Create a program that, given the height, prints a Christmas tree like the following:
// Height: 5
*
***
*****
*******
*********
Exercise: Christmas Tree with numbers
Create a program that, given the height, prints a Christmas tree like the following:
// Height: 5
1
222
33333
4444444
555555555
Exercise: Fibonacci sequence
Create a program that prints the first 'n' Fibonacci numbers. For example, if the value of 'n' is 10, the printed numbers will be: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.