At the end of this lesson, you will be able to:
understand and use a list
With a pencil and paper, answer the following questions:
Write the code for a function called calc_sum in Python that accepts a list of decimal numbers called list_of_num. It then returns the sum of all the numbers in the list. Use a for each loop. If the list is empty, return -1. Hint: Use the len(list_of_num) function to determine the number of elements in the list.
Do the above in C++ but for arrays. The name of your funciton will be CalcSum. It will accept an ARRAY called arrayOfNum. Use a for each loop to calculate the sum. Hint: Use the sizeof(arrayOfNum) function to determine the size of the array.
2D arrays
from the online book Computer Based Problem Solving by Patrick Coxall, read:
Arrays and Lists are containers that hold the SAME TYPE of elements, BUT there is 1 main difference:
Lists are DYNAMIC. They can grow and shrink in size.
Arrays are FIXED in size. Once created, they cannot grow or shrink.
Nothing has changed since we have been using lists this entire unit. (There are no arrays in Python.)
Create a program called “Lists” that asks the user repeatedly to enter a mark between 0 and 100.
The program uses a loop to enter each mark into a list of integers.
When the user enters -1, the loop stops.
It then calls a function called “calc_average()” in Python and “calcAverage()” in C++ that accepts a list of integers and returns the average of all the marks entered.
Do NOT use a hard-coded number (i.e. 10) to calculate the average.
In Python, use:
len(list_of_marks)
In C++, use:
listOfMarks.size()
To declare a list, use the following:
In Python:
list_of_marks[]
In C++:
#include <list>
std::list<int> listOfMarks;
Display the average in main().
Since your data is random, it is not possible to create test cases in advance.
Instead, insert 3 test cases of your program output. Then mathematically check to make sure your output is correct.
Ensure the main() function catches any "bad" user input so that only "valid" input is passed to the function.
Note: The top-down design should be for the entire program. There should be a flowchart for each function.
complete the Daily Assignment section in Hãpara Workspace for this day
if Hãpara is not working, make a copy of this document
move it to your IMH-ICS folder for this course
in groups of 2, do the following on the board for today's daily assignment:
Top-Down Design
Flow Chart
Pseudocode
Test Cases
complete the Daily Assignment section in Hãpara Workspace for this day
if Hãpara is not working, make a copy of this document
move it to your IMH-ICS folder for this course
recreate the same program in C++
you cannot reference a list in C++ using [ ]. Therefore, you have 2 options:
Use a For..Each Loop to print each element separated by spaces.
Use an iterator to iterate over the list and correctly format the output.