Wroclaw University of Technology    Faculty of Electronics    Electronic and Computer Engineering  (ECE)

"Introduction To Programming"
ECEA 00002  LABORATORY   '2016

Time :  Tuesday 11:15-14:00,  14:15-16:55,  17:05-19:40
Place :  Laboratory 127L / C-3
Instructor :  Marek Piasecki
Tutor.hrs :  Thursday 13:00-15:00,  room: 321/C-3

Assessment of Students' Solutions:

Laboratory Tasks:  0102 , 03 , 04 , 05 , 06 , 07 ,
09 , 10 , 11 , 12 , 13

Lab.01  -  Introduction, Simple console programs
Overview of the program and the organization of the laboratory classes. Workplace training in health and safety. Writing algorithms using flowcharts language.
Setting up development environment (e.g. Windows / Falcon C++ / Visual Studio or Linux/Emacs/gcc). An example of a console program using simple variables, assignment statements, and console input output operations. Editing, compiling, running and debugging the program. Guidelines for the use of integrated office packages for creating the technical documentation and reports on the implementation of laboratory tasks.

Laboratory tasks:
  1. Draw the flowcharts (block diagrams) of simple algorithms processing a sequence of three numbers (entered from the keyboard) and display on the screen:
    - the largest of these three numbers
    - the middle value (median)
    - the sorted sequence of these three numbers, in ascending or descending order
    - information whether at least two of these numbers have the same value.
    Consider cases where all numbers are different or that there may be a repetition

  2. Write a program that displays on screen the form of your "business card"
    ie. first/last name, address, phone, e-mail, etc.

  3. Extend program (a) in this way, that all personal data are read from keyboard,
    at the program startup.

  4. Write a program that reads 2 or 3 real numbers from the keyboard
    and then calculates some arithmetic expresions like:
    their sum, product, square root, exponent, etc.

Lab.02  -  Data types, math expressions, I/O streams, flow control: if/else
Representation of standard data types in C. Appropriate selection of the data type for variables. Data representation constraints. The dialogue with the user using standard printf and scanf functions. Formatting data (construction of format strings containing different control sequences). Calculating mathematical and boolean expressions in C/C++.
        Exercises with the creation of example programs illustrating the use of basic C/C++ constructs and concepts: assignment, conditional branching (if, if-else), selection (switch, case, break, default). Nesting branching instructions.

Laboratory tasks:
  1. Write the format string for printf statement, which displays a real variable in the form:
    - rounded to the third decimal place,
    - only the integer part,
    - in scientific notation (exponential),
    - as an hour, in the form of exactly two digits (as in watches,
      with a leading zero if necessary)

  2. Write a program that calculates mathematical expressions defining:
    - surface area and circumference of a circle of radius R,
    - the Cartesian distance between two geometric points, whose coordinates
       are defined by four real numbers (x1, y1) and (x2, y2).

  3. Write a program which classifies the height of people.
    The program should ask about the height of a man in centimeters
      and then displays one of the texts:  Low < 150cm < Average < 180cm < High

  4. Write a program that reads three numbers, from the keyboard,
    and then displays the smallest of them, on the screen.

  5. Write a program that loads the lengths of the three sections (edges)
    and checks whether it is possible to build a triangle of these edges.

  6. Write a program that reads two calendar dates from the keyboard
    (each date encoded by three integers: day, month, year)
    and checks whether the first date is earlier than the second.

Lab.03  -  Flow control: Loops, switch
The concept of iterations. The role and selection of the control variables for the loop. Loop breaking constructs (while, do-while, for). The equivalence of the loop.

Laboratory tasks:
  1. Write a program drawing horizontal line on the screen (with dashes)
    i.e. ---------------------------
    The length of this line (number of characters) should be loaded from the keyboard.

    *Try to write different version of the same program, using different loop types.
  2. Write a program that reads the characters from the keyboard,
    until you press a key 'k'.
    During this reading loop, the program should count the number of pressed characters and finally displays information:
    - How many characters have been pressed (before pressing 'k')
    - How many of these characters were capital letters.
  3. (f) Write a program classifying buttons pressed on the keyboard,
    and displays one of labels:
    - lowercase
    - capital letter
    - digit
    - ENTER
    - ESC
    - Left Arrow
    - Right arrow
    - F1 function key
    - Another key
    to retrieve the key code use function getch() from the library <conio.h>.

    Implement "branching" by the switch statement
    and (or?) nesting of several if/else statements.
  4. (g) Write a program that displays a "Christmas tree" on screen.
    The height of tree should be specified by the number loaded from keyboard.

  5. (c) Write a program, with a loop reading numbers from the keyboard,
  6. which finishes the loop when:
    - The sum of these numbers exceeds 100,
    - The number of reported negative numbers exceed 10,
    - Two following numbers will have the same value (e.g.  3, 4, 2, 5, 5 )

Lab.04  -  Iteration
Continuation of exercises with programs illustrating the use of loops.
The idea of iterative algorithm: counting, summing, searching the maximum and minimum, calculation of the mathematical series, etc.

Laboratory tasks:
  1. Write a program to find the sum of all natural numbers in a given range [m,n]
    which are divisible by number k. The values of all three parameters m, n, k,
    should be read from the keyboard at the beginning of the program.

  2. Write a program that loads several numbers from the keyboard,
    asking in the meantime, the question "Do you want to finish: Y / N?"
    At the end of the loop, program should display calculated values of:
    the arithmetic average, maximum, minimum of given numbers.
  3. Write a program using iterative loop to calculate (numerically) the series:
    1/x + 1/x 2 + 1/x3 + 1/x4 +  . . .  + 1/xn

  4. Write a program to enter a natural number from keyboard
    and then print first and last digit of entered number.

  5. Write a program to enter any number from user and find the reverse of given number using for loop (example:   1234   4321)

  6. Write a program to convert ASCII representation of Decimal number
    (loaded from the keyboard using a loop calling the function getchar() )
    and print its representation in Binary number system
    (example:   13   00001101 )
  7. Write a program to enter any number and check whether the number is prime number or not.

Lab.05  -  Arrays
Exercises with the creation of programs that illustrate the use of the array data representation. Processing arrays using a loop. Basic array processing algorithms (filling, comparing items, search, move, delete, add items).

Laboratory tasks:
  1. Write a program that allows for storing N real numbers, loaded from keyboard,
    in the array composed of N cells  (where N is a user defined constant).
    During reading, the program should display user prompts in the form:
        Tab[1] = 12.0
        Tab[2] = -1.0
        Tab[3] =  .......
    Before termination, the program should display the array content in reverse order
    (starting from the last element and ending with the first).

  2. Expand the program from task (a) with a set of operations implementing
    simple statistical calculations of array data:
      - the sum of the the elements
      - Mean (average value) and Mean Squared Error (population variance)
      - extreme values (minimum, maximum).

  3. Write a program that fills N-elemental array with random integers in range [-10,10]
    and then checks:
      - if these numbers are arranged in ascending or descending order,
      - if the array have a symmetric content,
        (the first element equals to the last, the second equals one before last, etc.)
      - whether there is at least one repeated value.
  4. Write a program to count total number of negative and positive numbers in an array
  5. Write a program to count total number of duplicate elements in an array
  6. Write a program to print all unique elements in an array
  7. Write a program to find the second largest element in an array
  8. Write a program to count frequency of each element of an array
  9. Write a program that will load and analyze the sequence of letters entered from keyboard, until the user press the ESC key.
    After ESC, the program should display on the screen a histogram
    of the number of occurrences of each letter from alphabet:
    For example:
       A   17| #################
       B    2| ##
       C    1| #
       D    0|
       E    5| #####
          . . .
       Z    3| ###

    Hint: use array of 26 counters and transpose ASCII codes to indexes of elements (counters) in the array.
Lab.06  -  Functions (1)
Structured and procedural programming. Sub-division of tasks into functions, the concept of program menu. Visibility range and overriding the identifiers. Exercises with creating user-defined functions. Parameterless functions. Local variables. Passing parameters through global variables. The functions with explicit argument list. Passing arguments by value, reference and address.

Laboratory tasks:
  1. Write a program combining in one file, selected programs (tasks solutions) created during previous laboratories. In the simplest version, all previous functions
                 int main()
    could be converted to  parameterless sub-functions, eg.
         void DisplayMyBusinessCard( void )
         void ClassifyPeopleHeight( void )
         void ClassifyPressedKeys( void )
         void PrintChristmasTree( void )
       . . .  etc.
    New function main in program (6a) can sequentially call all above sub-functions.
    ( Hint: to connect the code of existing programs, you can use commands operating on a editor's clipboard : Cut / Copy / Paste ).
  2. Expand the program (a) by adding the "Menu", which allows to control the sequence of executed/called functions and exit the program. Sample menu may have options:
              1. Display my business card
              2. Classify the height of person
              3. Print Christmas Tree
              4. Exit
        Select the number of operation: ... ?
  3. Advanced students,
    may write a more difficult version of MENU
    where the choice of options
    will be made by moving the options highlight,
    by the use of the ARROW keys
    and the selection by pressing the ENTER key
    (As options in your programming IDE)

    or the menu with "moving arrow":


        1. Display my business card
    --> 2. Classify the height   
        3. Print Christmas Tree
        4. Exit
    Move the arrow and press Enter

    HINT: set text
    console color , move cursor: gotoxy
  4. Write a C++ function (with parameter), to check whether a given number is even or odd. The function should return boolean value.

  5. Write a program in to swap two numbers/variables using your own function SWAP.
  6. Write program with functions SUM, MAX, MIN which calculate the sum/max/min of all elements from array given as a parameter.
  7. Write a program to print all natural numbers between 1 to n, using recursion.
  8. Write a program to find the power n of any number xn using recursion.
  9. Write a program to find sum of all digits of a given number using recursion.

Lab.07  -  Functions (2) and array algorithms
Dynamically allocated arrays (array with a counter of used items). Selected algorithms for processing arrays: linear and binary search, bubble sort and insertion sort. Parameterization of algorithms. Appropriate selection of the method for passing input/output parameters between the functions.

Laboratory tasks:
  1. Write a function to search for an element from given array T, by "Linear Search"
  2. Write a function to search for an element from given array T, by "Binary Search"

  3. Write a function to sort the array by "Bubble Sort"
  4. Write a function to sort the array by "Selection Sort"
  5. Write a function to sort the array by "Insertion Sort"
  6. Write a function to sort the array by "Quick Sort"

  7. Write a program that implements a queue of numbers using array.
    The program should have three auxilary functions which helps to manipulate the queue:
    bool  push( float queue[], int& size , float value);
    float pop( float queue[], int& size );
    bool  isEmpty( float queue[], int size );

  8. Write a function which enable controlled keyboard input:
      - restricting the maximum number of input characters,
      - checking whether the characters belong to a given set of ASCII codes,
      - allowing setting the initial value of the entered/edited text
    Example prototype of such function:
       bool editText( int  x, int y,
                      char text[],

                      int  max_length,
    char allowed_characters[],
                      char initial_value[] );
Lab.08  -  Text processing - Strings
Text processing functions. Code analysis of the standard functions from <string.h> library. User-defined functions for character string processing.

Laboratory tasks:
  1. Write a function to find the length of a C string (represented as an array of char)
  2. Write a C function to copy one string to another string (equivalent of strcpy)
  3. Write a C function to compare two strings (equivalent of strcmp )
  4. Write a C function to concatenate two strings (equivalent of strcat )
  5. Write a function to convert lowercase string to uppercase (equivalent of strupr )
  6. Write a C program to find the first occurrence of a character in a given string (equivalent  of strchr)
  7. Write a function to remove first occurrence of a character from string.
  8. Write a functionto replace first/last occurrence of a character within another string.
  9. Write a function to find first occurrence of a word in a given string.
  10. Write a function to remove all occurrences of a word in the given string.
  11. Write a function to replace all occurrences of a word with the given pattern.

  12. Write a function to trim leading white spaces from the begining of the given string.
  13. Write a function to trim trailing white space from the tail of the given string.
  14. Write a function to remove all extra blank spaces from a given string.

  15. Write the super function for advanced formating of "Names", which:
    - tream leading spaces,
    - tream trailing spaces
    - remove extra blank spaces
    - change first letters of words to uppercase
    - change following letters of words to lowercase
Lab.09  -  Strings, Pointers, Dynamic memory allocation
Exercises with accessing the variables (the memory) through pointers.
Continuation of exercises with the creation of programs illustrating the processing of textual data, represented as an array of characters.
Dynamic allocation and reallocation of one-dimensional arrays on cheap.
Debugging and testing the correctness of the programs.

Laboratory tasks:
  1. Write the program illustrating the use of pointers as an alternative access method
    to the variables created by the compiler (ie. global or local variables.)
    The programm should display the real addresses of all defined variables, and later try to modify the value of one of them, by using the address of others
    See the example from slides of Lecture number 8 / page 3)

  2. Write a program performing simple calculations on the dynamic array of numbers,
    which size can be modified by the user at run-time.
    The program should have the menu allowing for:
    - Displaying the current content of the array,
    - Adding new numbers, to the end of the table (with reallocation to new size)
    - The removal of any element inside the array (and the release of unused memory).

    Hint: use the example code from Dynamic Memory tutorial as an starting point,
    to your own program implementing dynamically allocated array
Lab.10  -  Structures
Implementing simple in-memory database using representation in the form of an array of structures (or array of pointers to dynamic structures). Implementing the functionalities of: adding, updating, deleting, searching the database elements.

Laboratory tasks:
  1. Write a function Stats which analyse the content of an array received as an argument, calculate basic statistics (avg, min, max) and return calculated results in the form of struct:

       struct StatResults {

           double avg, min, max;

    StatResults Stats( double array[ ], int array_size );

  2. Select the "subject" of your individual database implementation.
    It could be the catalog of books in your private library, or an offer list of cars in second-hand car dealership, or a student's budget ie. catalog of monthly expenses, etc.
      - define the structure type, which allows to store the data of a single element
         of selected database instance,
       . implement functions which enable to input (read from keyboard), update and
         output (display on the screen) the content of one database element
         (the structure should be passed or returned as an argument)

  3. Define the N-elements array (pseudo-dynamic or dynamicaly allocated, with with an additional counter that indicates the size/amount of entered data) of structures defined in task (b). Write the program implementing following functionalities of database:
      - function that reads a new elements to this array,
      - function that displays the content of all database (all elements of array),
      - function that modify / updates the content of selected database element,
      - function that delete / remove the selected element from database,
      - function that that allows filtering / searching the database to display
        only elements matching the given criteria.
    For example: display the list of second-hand cars in database, but only "Fiat" brand, not older than 2000 year, with vehicle mileage less then 150 thousand kilometers.
Lab.11  -  Files
Exercises with data storage in external memory using file streams. Text and binary representation of numerical data. Error detection during file stream input / output operations. Controlling the location of the file position indicator. Basic algorithms for sequential processing of text and raw binary files. Export/import of numeric and text data in the format accepted by popular office spreadsheet environments (for example Excel).

Laboratory tasks:
  1. Write a program which open the text file containing this program source code
    (eg. "lab11A.cpp") and display its content (C language instructions) on the screen.

    Try to implement these operation using three different reading functions,
    which utilise three different ways of "portioning" the data:
      - single characters / using the function:  fgetc( file )
      - words or commands / using the function:  fscanf( file, "%s", ... )
      - lines / using the function: fgets(text_array, array_size, file)

  2. Write a program which:
      - defines the array of N double numbers,
      - later, fill the array with the sequence of predefined (or random) values,
      - and finally, store the array content in the external text (or binary) file.

  3. Write a program which reads the numbers from external file "numbers.txt",
    and calculate basic statistics: sum, average, maximum and minimum
    for this sequence of loaded numbers.

  4. Use standard Notepad editor to prepare an example input text data file "students.txt", containing the list of students data in format:
          Surname   Name     Album
          Kowalski  Jan      123789
          Nowak     Tomasz   334455
                   .   .   .
    Write a program, which reads (import) the student data from "students.txt" file and display the data on the screen, in separate columns with titles.
  5. Extend the functionalities of database program from previous laboratory task "10C", adding archiving operations, which store the whole database content in the external memory (in the form of binary or text file).

Lab.12  -  Complex data structures
Completing the overdue / not elaborated parts of laboratories number 10 and 11:
      Lab 10.c - options to display / update / filter the content of database (array of struct)
      Lab 11.e - option to store the database in external disk file,
                     - option to load the database content from the external disk file.

The structural decomposition of large programs and complex data representation. Discussion and practice the representation of simple in-memory database (using an array of structures). User defined data type, enumeration. Encoding data using the dictionary.

Lab.13  -  Dynamic data structures
  1. Write a program performing example calculations on the dynamically allocated array of numbers (the size of array should be dynamicaly adopted - reallocated - to the number of elements stored in the array).

    The program should have a menu allowing for:
       Create a new array (with the size specified by user)
          and initiate its content with data loaded from keyboard
       Option for adding the sequence of new numbers to the end of the array
          (with reservation the new location for these new numbers)
       Option for removing of designated element of the array
          (and reallocating the array to release unused memory)
       Option for calulating simple statistics (sum, average, maximum, minimum)
          for the sequence of numbers stored in this dynamic array.

  2. Extend the functionality of final "Database" program, created during lab 10/11/12,
    with additional option to store the database content
    in the form of dynamically alocated array of structures
    (or dynamical array of pointers to dynamical structures).

User-defined implementation of selected dynamic data structure: the linked list, queue, priority queue or a tree. Exercises with creating programs using recursion.

Lab.14  -  Automation of office suites
Utilizing standard business office suites. Exercises with advanced formatting techniques of technical documents and performing engineering calculations using spreadsheets. Automation of work by programming new functions and macros.
Lab.15  -  Repetition / Final Assessment
Repetition and additional assessment for students who have absences or overdue tasks