Topic outline

  • UNIT1: FUNDAMENTALS OF LAPTOP AND PORTABLE DEVICES

    Key Unit Competency: To be able to identify, use and maintain safely laptops and other portable devices.

    INTRODUCTORY ACTIVITY

    Apply the following scenario:
    You are in computer lab with different devices on table.

    Figure 1.1. Mobile devices

    Answer the following questions:

    1. Name the devices you see on your table

    2. Describe parts of each device.

    3. Describe the common use and functions of these devices


    1.1. PORTABLE DEVICES
         
         Learning Activity 1.1

    1) You are sited in your computer lab, observe well each device and then answer following
         questions:

    a. Describe the portable devices available in lab;

    b. Discuss the similarities and differences between available devices;

    c. Enumerate other portable devices which are not in your lab.

    2) In supermarket A, a laptop costs 350,000 Rwf while in supermarket B, laptop of same
       quality costs 300,000Rwf. Select where you will prefer to buy your laptop and explain
         why.
     1.1.1. Portable devices definition

    A portable device is a device that can easily be carried. It is a small form of a
    computing device that is designed to be held and used in the hands.

    A portable device may also be called a handheld device or mobile device. Portable
    devices are primarily battery powered devices with base computing resources in
    the form of a processor, memory, storage and network access. Portable devices are
    becoming an increasingly important part of personal computing as the capabilities
    of devices like laptops, tablets and smartphones continue to improve.

    11.2. Types of portable devices

              a. Laptops

    A laptop computer is a portable personal computer powered by a battery, or an
    Alternating Current (A.C) cord plugged into an electrical outlet, which is also
    used to charge the battery. Laptops have an attached keyboard and a touchpad,
    trackball, or isometric joystick used for navigation. Sometimes, a wireless mouse
    can also be used on a laptop. A wireless mouse is a computer mouse that needs no
    wires to send signals from the mouse to a computer. Wireless mouse technology
    predominantly uses radio frequencies (RF) to send signals from the mouse to the
    computer. Like other radio technologies, this requires a transmitter and a receiver.
    The mouse transmits radio signals to a receiver, which is itself connected to the
    computer hardware, normally via a wire. This kind of wireless mouse is very reliable,
    and capable of transmitting the mouse’s movements to the receiver from across a
    room. A laptop also has a thin display screen that is attached and can be folded
    flat for transport. Laptop computer is also known as Notebook computer or simply
    Notebook.

    The memory and storage capacity of laptop computer is almost equivalent to the PC
    or desktop computer. It also has the hard disk, DVD/CD optical disk drive, different
    connectors etc.
               b. Smartphones

    A smart phone is a handheld personal computer with a mobile operating system and an
    integrated mobile broadband network connection for voice, SMS, and Internet data
    communication. Most if not all smartphones also support Wireless Fidelity (Wi-Fi). Smartphones are typically pocket-sized, as opposed to tablets, which are much
    larger. A smartphone is a cellular phone that performs most of the functions of a computer.

    A smart phone supports all features of PDA plus mobile phone features

    Smartphone characteristics/features

    • Media players

    • Internet access

    • Global Positioning System(GPS)

    • Wireless Fidelity (Wi-Fi)

    • Camera

    • Sensor

          c. Mobile phones (cell phones)

    A mobile phone or cell phone (is a long-range, electronic device used for mobile
    telecommunications (mobile telephony, text messaging or data transmission) over
    a cellular network. Today, this type of portable device is being dominated by smart
    phone as technology improves.

          
            
                     d. PDAs

    A Personal Digital Assistant (PDA), also known as a palmtop computer, or Personal
    Data Assistant, is a mobile device that functions as a personal information manager.
    Newer PDAs commonly have color screens, audio capabilities and web browsers that
    enable them to be used as mobile phones (smartphones) or portable media players.
    Many PDAs can access the Internet, intranets (communication within LAN) or
    extranets via Wi-Fi, or Wireless Wide Area Networks. Many PDAs employ touch screen
    technology.
                       e. Tablets

    A tablet computer, or simply tablet, is a mobile computer with a large screen,
    circuitry and battery in a single unit with no built in keyboard. Some tablets include
    detachable keyboards have been sold since the mid-1990s. Such tablets include
    iPad, HP Touchpad, Android)
    Tablets are very similar to smartphones. They have an Internet connection via a
    wireless connection including 3G/4G. Applications can be downloaded and installed.
    Sensors including speech recognition.

    Application Activity 1.1.

    6. Describe the difference between PDA and Smartphone

    7. Compare a smart phone and Tablet

    8. According to the comparison between laptop, Smart phone, Cell
        phone, PDA and Tablet, which one is most useful? Explain why.

    1.2 LAPTOP COMPUTER FUNDAMENTALS

         Learning Activity 1.2.

    1) In the computer lab observe laptop computers and make groups and answer the
         following questions:

    a) Discuss common uses of laptop computer in schools and society in general

    b) Describe the external components of a laptop

    c) Describe the internal components of a laptop

    d) Investigate why laptop has Fn key on keyboard while desktop keyboard does not
        have it

    e) With your laptops connected to Internet, search for steps to be followed while
        applying for National ID at www.irembo.gov.rw site

    f ) In the computer lab, identify the following features of a laptop: AC power port,
        ethernet port VGA port, vents, HDMI port, USB ports, camera.

    g) Open a laptop and identify all its internal components 1.2.1. Common uses
        The first laptops were used primarily by business people who needed to access and
        enter data when they were away from the office. The use of laptops was limited due
        to expense, weight, and limited capabilities compared to less expensive desktops.
        
    Some common uses for laptops

    Laptop is used in:
    • Education field (example: Laptops are used by teachers in preparation of
       teaching and learning materials)

    • Medicine field (example: Laptops are used by doctors to keep patient records)

    • Business field (Electronic commerce uses Laptops for example in marketing
      and selling products or good and services.)

    • Accessing online services (example: National ID application at www.irembo.
       gov.rw)

    • Entertainment field (example: Playing games and watching movies while
      traveling)

    • Communication field (example: when you send and receive an email in a
      public place)

    • Security field (example: Laptop can be used to fight against hackers: people
       who access personal information without authorization of the owner. Notice
       that accessing of personal information without permission is punishable crime).
     
    1.2.2. Laptop features

    The most significant feature of a laptop is its compact size. The design of the laptop
    places the keyboard, screen, and internal components into a small portable case.
    Common Characteristics/features of Laptops:

    • Small and portable;

    • An integrated display screen in the lid;

    • An integrated keyboard in the base;

    • They run on AC power or a rechargeable battery;

    • Laptops support hot-swappable drives and peripherals.

    1.2.3. Evolution (History) of laptops

    In 1983, Gavilan SC is the first machine marketed as a “laptop”

    In 1990, Intel introduces 80386SL processor which uses low power; quickly
                 incorporated into many laptops.

    In 1991, Apple PowerBook introduces First laptop Ethernet port. Modem speeds
                 reach 14,400 bits/sec.

    In 1996, First Pentium laptop with USB, first “three spindle” machine, with floppy
                 hard disk, CD-ROM.

    In 1999, Laptop manufacturers use PCI slot to enable Wi-Fi connectivity. Apple
                  brands WiFi as AirPort, incorporates a slot into all of its laptops.

    In 2005, Laptop computers outsell desktops for the first time.

    In 2010, HDMI ports become common on laptops. Apple iPad was introduced.

    The components of a laptop

    Components may be located in different places for different models.

    a. The external components of a laptop

    The Laptop and the desktop computers use the same types of ports so that
    peripherals can be interchangeable. Ports, connections, and drives are located on
    the front, back, and sides of the laptop due to the compact design. There are status
    indicators, ports, slots, connectors, bays, jacks, vents, and a keyhole on the exterior
    of the laptop.

    As port a laptop has an AC power port, an ethernet port, a VGA port a HDMI port, a
    USB port a sound in (microphone) port and a sound out (speaker) port. Beside these
    ports a laptop has a battery latch at its bottom
    On the user view, which is normally visible when a laptop is being used one can see
    the following components:

    1) Web camera               4) Keyboard              7) Left Click button
    2) LCD                            5) Touch pad
    3) Power button                6) Right Click button

    Note:
    • The location of the power button may depend on the mark of the laptop

    • Some laptops may not have an in-buitl CD/DVD disk drive while in other types,
      the CD/DVD disk drive can be located on left or right side. For those with no
      such drive an external drive that can be connected to the laptop through the
      USB port is often used.

    • A desktop monitor can be connected to a laptop. In such cases, using the
      function key can allow one to toggle the screen from the laptop to the desktop
      monitor or view both at the same time.

        b. The internal components of a laptop

    The central circuit board (motherboard) makes up a complex electronic system. A
    motherboard provides the electrical connections by which the other components of
    the system communicate. It includes many components such as Central Processing
    Unit (CPU), Random Access memory (RAM), etc. Laptop motherboards and other
    internal components installation vary by manufacturer and are proprietary.
    Internally and at the top a laptop after removing te cover there is access to the
    motherboard, speakers, cooling fans, wireless card, CMOS battery and audio board
    while under the bottom cover there is access to the hard drive and RAM module but
    this configuration may change from laptop mark to another

       Application Activity 1.2

    1) Suppose that your computer laptop is not connected to Internet. If there is no
         wireless connection,

    a) which of the following cables can be used to have the connection?

    i. VGA (Video Graphic Array) cable;

    ii. Network cable;

    iii. AC Power cable.

    b) Describe the role of the remaining cables.

    2) Choose from a laptop in the computer lab one document in PowerPoint and
        project it by using the Projector of your school.

    3) Connect a desktop monitor to a laptop computer and then do the following:

    i. Display the contents from the laptop to both screens;

    ii. Display the contents from the laptop to only desktop monitor;
        Differentiate HDMI port from USB port.
        Open a laptop and identify all its internal parts

    1.3. Compare and contrast laptop and desktop components

    Both desktop and laptop computers can perform most of the same functions.
    However, these two kinds of computers are built very differently and the parts
    are not interchangeable. Few components can be shared between desktops and
    laptops like the expansion devices that are attached to laptop devices with USB
    ports, parallel ports, and PC Cards.

    Laptop components are proprietary. So you may not be able to use components
    made by one laptop manufacturer to repair a laptop made by another manufacturer.
    Therefore, that technicians may have to obtain certification for each laptop
    manufacturer they support. The following table summarizes the specifications
    between a laptop and desktop computers.
    Expansion devices are attached to laptops and desktops differently. Laptops have
    limited space so the expansion bays on laptops are designed to allow different
    types of drives to fit into the same bay. Drives are hot-swappable and are inserted or
    removed as needed.

    As both desktop and laptop computers are electronic devices, they manage power.
    The optimization of power management can be configured differently through the
    Control Panel feature of the running operating system. This configuration of power
    management can also mark the difference between a laptop and a desktop.

    Application Activity 1.3

    Go through the steps for power option Edit plan. To do this in Windows 10 go
    through these windows: “Control panel”window, “Hardware and Sound”window,
    “Power Options” window, Create a Power Plan and Edit Plan Setting. Then:

    1. Set your laptop so that it can turn off the display:

    i. After 3 minutes when powered by battery

    ii. After 7 minutes when plugged in

    3. Discuss different reasons why there is no need of large cooling devices
        in a computer lab containing laptops.

    4. Discuss the similarities and differences between a laptop and desktop
        expansion components

    5. Open a laptop and a desktop and identify the difference between their
        motherboards

    1.4. SMARTPHONES, PDAs, TABLETS

    Learning Activity 1.4.

    All companies deal with large amount of data. Using different portable devices, users
    can collect and access data from the outside of the organization.

    1. Identify the portable devices other than laptops that are used in your
        school to allow teacher and student to access materials on Internet.

    2. Discuss the common uses and features of those identified devices in
        above question

    The Smartphones, PDAs, tablets are new types of small personal computing devices
    that have been introduced in the mid-1990s and these are referred to as handheld
    computers. This type of computer is named handheld computer because it can fit in
    one hand while you can operate it with the other hand. Because of its reduced size,
    the screen of handheld computer is quite small.

    1.4.1. Common uses and standard services of Smartphones, PDAs and
          tablets

    Like the laptops, these computers are used by mobile employees whose jobs require
    them to move from place to place.

    They are used in different fields like the following:
    • Communication (example: - when you send and receive an email)
     
    −− Voice over Internet Protocol (VoIP) – voice/video calls.

    −− Instant text message ex: chatting using WhatsApp

    −− Streaming music/video content

    −− Communication via social networking applications)

    • Entertainment (example: when you play games and watch movies while
       traveling)

    • Business (Electronic commerce uses these computers for example in marketing
    and selling products or goods and services.)

    • Education field (Smartphones, PDAs and tablets are teaching and learning
       tools. They are used in performing calculations, note taking etc.)

    • Smartphones, PDAs and tablets have storage which can store information like
       contact information (names, addresses, phone numbers, e-mail addresses)

    • Smartphones, PDAs and tablets can remind you of appointments (clock, alarm
        functions)

    1.4.2. Common features of Smartphones, PDAs and tablets

    Smartphones, PDAs, tablets have operating systems which allows them to run
    multiple applications. Their Operating systems have features like contacts, email,
    calendar, appointments, tasks, games, media etc.

    Examples of mobile operating systems:

    a. Apple’s iOS

    b. Android OS

    c. Windows Phone OS

    d. BlackBerry OS

    Apart from the operating system, tablets have in common a wi-fi, capability to have
    their memories expanded, a high resolution display with touch technology and a
    QUERT keyboard

    Application Activity 1.4.

    Using a smartphone or a tablet or IPad do the following:

    1. Download and install one of these applications from Play Store:
        WhatsApp, Google Chrome and Facebook.

    2. Send an email message to one of the classmates and ask him/her to reply.

    3. Search the application called “Polaris Office” in Play Store install it and
        state its function?

    1.4.3. Standards Service of Smartphone, PDA and Tablet

    Some of the services that can be found in smartphones, PDA, and tablets include;

    • Appointment calendar

    • MP3 player

    • Web browser

    • E-mail access, in addition to text messaging

    • Mini-keyboards or onscreen keyboards

    • Bluetooth

    • Character recognition (allowing for handwritten input)

    • Synchronization of information with desktop or laptop computers

    • Voice recording

    • Digital camera

    • Video recording

    • Location tracking through GPS(Global Positioning System)

    • Wi-Fi

    • Microsoft Office (MS) compatible applications (Native with Pocket PC operating
      systems; Palm operating systems may require third-party software)

    1.5. LAPTOP AND PORTABLE DEVICES CLEANING PROCEDURES
     
          Learning Activity 1.5

    Observe the figure below and answer the followed questions

    1. Discuss what would happen if a drink was spilled into the keyboard of a
        laptop.

    2. How can you prevent this laptop to be damaged?

    3. What can you do if the laptop and water are in contact?

    4. What can you consider while choosing cleaning materials and products?

    5. Describe different laptop parts which can be cleaned.

    6. How can you keep waste products after cleaning a laptop?

    As laptops are mobile, they are used in different types of environments. Some
    environments can be hazardous to a laptop. Even eating or drinking around a laptop
    creates a potentially hazardous condition.

    It is important to keep a laptop clean and to ensure that it is being used in the most
    optimal environment possible. Proper routine cleaning is the easiest, least expensive
    way to protect and to extend the life of a laptop.

    It is very important to use the right products, cleaning materials and procedures
    when cleaning a laptop. Always read all warning labels on the cleaning products.

    Before starting to clean any part of a laptop, turn it off, disconnect all attached
    devices, disconnect it from the electrical outlet and remove its battery. To remove
    the battery move the battery lock to the unlocked position, hold the release lever in
    the unlock position and remove the battery.

    To clean laptop keyboards blow compressed air between the keys then slide a soft
    cloth over the laptop keyboard in order to remove the dirt. The cleaning can be
    done using compressed air whereby this air is blown into the laptop through the
    vents. Use tweezers to remove any debris.

    To clean LCD screens slide a soft cloth slightly moistered with water or LCD cleaner
    over the laptop display. A special attention should be taken on using products
    specifically designed for cleaning LCD displays.

    To clean touch pads slide a soft cloth over surface of the touch pad gently with an
    approved cleaner. Never use a wet cloth and use a soft cloth with only approved
    cleaning solution.

    Application Activity1.5

    1. Clean a keyboard and a screen of a laptop in the computer lab.

    2. Discuss different Laptop Keyboard, LCD screen and touchpad Cleaning
        materials, products and Procedures.


    END OF UNIT ASSESSMENT ACTIVITY

    1. Discuss the advantages and disadvantages of each type of computer
        below:

                  Laptop computer

                  Tablet

                 Smartphone

    2. Describe what is used for standalone and networked laptop computer.

    3. Compare smartphone features and cell phone features

    4. Is a Laptop hardware maintenance difficult comparing to a desktop
        computer maintenance? Explain.

    5. Give a clear difference between VGA and HDMI connectors.

    6. Explain how you can take care your laptop.

    7. Exchange a track of music from one device to another. What do you use?
        Are there other.


    Files: 3URLs: 2Assignments: 2Quizzes: 2
  • UNIT2: COMPLEX DATA STRUCTURE AND ALGORITHM


    INTRODUCTORY ACTIVITY

    Read the following scenario and after answer questions:

    In a bank, a Teller has the role of serving the clients. He/she has to organize the
    banknotes of same values together and coins of same values together that he/she has
    to serve to clients. When a client arrives in the bank, he/she chooses a line to join in the
    front of a Teller and the line is formed according to the arrival of clients.

    Mr. KARENZI wants to pay 78450 Rwf as his school fees to the bank and he must
    organize banknotes and coins before deposit money to facilitate the teller to not mix
    the banknotes and coins


    Answer the following questions:

    1. Observe the above figure and describe what you see;

    2. Where a new arrived client will line up?

    3. Using the above figure who is going to be served first by the teller 1 or 2;

    4. Discuss how KARENZI is going to organize bank notes and coins before
         depositing;

    5. Discuss how the teller is going to keep money deposited by Karenzi

    2.1. Introduction to Data Structures

    Data Structure is a way of collecting and organizing data in such a way that we
    can perform operations on these data in an effective way. Data Structures is about
    rendering data elements in terms of some relationship, for better organization and
    storage.

    Example: Library is composed of elements (books) to access a particular book
    requires knowledge of the arrangement of the books.

    2.1.1. Basic types of Data Structures

    Anything that can store data can be called as a data structure, hence Integer,
    Float, Boolean, Char etc., all are data structures. They are known as Primitive Data
    Structures. And we also have some complex Data Structures, which are used to store
    large and connected data and are called non primitive data structure or Abstract
    Data Structure.


    Example: Array, Linked List, Tree, Graph, Stack, Queue etc.
    All these data structures allow us to perform different operations on data. We select
    these data structures based on which type of operation is required.

     2.1.2. Importance of data structures

    The data structures have the following importance for programming:

    • Data structures study how data are stored in a computer so that operations
       can be implemented efficiently

    • Data structures are especially important when there is a large amount of
       information to deal with.

    • Data structures are conceptual and concrete ways to organize data for efficient
       storage and manipulation

    2.1.3. Data Structure Operations

    Beside the simple operations performed on data (unary operators, binary operators and
    precedence operators) seen in Senior Four, the data appearing in our data structures are
    processed by means of other operations. The following are some of the most frequently
    used operations.

    Traversing: Accessing each record exactly once so that certain items in the record may be
                         processed.

    Searching: Finding the location of the record with a given key value or finding
        the locations of all records which satisfy one or more conditions

    • Inserting: Adding a new record to the structure.

    Deleting: Removing a record from the structure.

    Sorting: Arranging the records in some logical order (e.g., in numerical order
       according to some NUMBER key, such as social security number or account number).

    Merging: Combining the records of two different sorted lists into a single sorted list.

    It is important for every Computer Science student to understand the concept of
    Information and how it is organized or how it can be utilized.

    If we arrange some data in appropriate sequence, then it forms a Structure and gives us
    a meaning. This meaning is called information. The basic unit of information in computer
    Science is a bit, binary digit. So we found two things in information: One is Data and the
    other is Structure

    2.2 Array of elements in data structure

    LEARNING ACTIVITY 2.1.

    Study the following table

    Answer the following questions.

    1. Suggest a name for the above table?

    2. How many rows and columns in the above table?

    3. Identify the location of the value 95 in the above table?

    Arrays hold a series of data elements, usually of the same size and data type.
    Individual elements are accessed by their position in the array. The position is given
    by an index, which is also called a subscript. The index usually uses a consecutive
    range of integers, (as opposed to an associative array) but the index can have any
    ordinal set of values

    Some arrays are multi-dimensional, meaning they are indexed by a fixed number of
    integers, for example by a tuple of four integers. Generally, one- and two-dimensional
    arrays are the most common. Most programming languages have a built-in array
    data type.

    In computer programming, a group of homogeneous elements of a specific data
    type is known as an array, one of the simplest data structures.

    2.2.1. Arrays dimensions:

    A dimension of array is a direction in which you can vary the specification of an
    array›s elements. An array can be of one or many dimensions.

    a. One-dimensional array.

    Example: a [3]

    It is an array called a with 3 elements. The elements of the array are logically
    represented by the name of the array with in brackets its index or positions. For the
    one dimensional array a with 3 elements, elements are written like a[0], a[1] and
    a[2]. The indexes start always by 0. Graphically, it is

    b. Multi-dimensional arrays
        Example:

             Two dimensional array ex: a[2][7]as Integer
            Three dimensional array ex: a[3][2][5]as Integer

    2.2.2. Two dimensional array

    A Two dimensional Array is a collection of a fixed number of elements (components)
    of the same type arranged in two dimensions.

    The two dimensional array is also called a matrix or a table. The intersection of a
    column and a row is called a cell. The numbering of rows and columns starts by 0

    Example:
    The array a[3][4] is an array of 3 rows and 4 columns. In matrix representation, it
    looks like the following:
    a[i][j] means that it is an element located at the intersection of row i and column j.
    Each element is identified by its row and column

    2.2.3. Two dimensional array declaration

    The syntax for declaring a two-dimensional array is:
    SET Array name=Array
    of Data type

    Where row size and column size are expressions yielding positive integer values,
    the two expressions row size and column size specify the number of rows and the
    number of columns, respectively, in the array.

    Examples:

    1. SET a=Array[2][7] of Integer

    2. SET b=Array[4][3] of Integer

    Notice that the number of elements =row size*column size

    The examples above defines respectively arrays named a and b with 14 (2*7) elements
    and 12 (4*3) elements. The expression marks [0] [0] will access the first element of
    the matrix marks and marks [1] [6] will access the last row and last column of array a.

    If the array marks if filled with the elements 80, 75, 76, 75, 55, 70, 55, 70, 65, 85, 35
    and 59, we get the following table.

    2.2.4. Two dimensional array initialization

    When a two-dimension array has been declared, it needs to be assigned values for
    its elements. This action of assigning values to array elements is called initialization.
    Two-Dimensional array is initialized by specifying bracketed values for each row. For
    the case of array of integers, the default values of each element is 0 while for others
    the default values for other types is not known.

    For the case of an array of 3 rows and 4 columns, if the name is A and the type of
    elements is integer, the initialization is:

    int A[3][4]={{A[0][0], A[0][1], A[0][2], A[0][3]}, /* initializers for row indexed by 0 */
    {A[1][0], A[1][1], A[1][2], A[1][3]}, /* initializers for row indexed by 1*/
    {A[2][0], A[2][1], A[2][2], A[2][3]} /* initializers for row indexed by 2 */
    };

    The nested braces, which indicate the intended row, are optional. The following
    initialization is equivalent to the previous initialization.

    Int A[3][4]={A[0][0], A[0][1], A[0][2], A[0][3], A[1][0], A[1][1], A[1][2], A[1][3], A[2][0],
    A[2][1], A[2][2], A[2][3]};

    An example of marks for 3 students in 4 courses. The array will look like this:
    If the table is called marks, marks [1][3]=15; where the row position is 1 and the
    column position is 3.

    The expression marks [0] [0] will access the first element of the matrix marks and
    marks [2] [3] will access the last row and last column.

    Syntax to initializing two-dimensional arrays

    The two dimensional array marks which will hold 12 elements can be initialized like:

    BEGIN
    SET marks=Array[3] [4] of Integer
    marks[0][0]=18
    marks[0][1]=16
    marks[0][2]=14
    marks[0][3]=19
    marks[1][0]=10
    marks[1][1]=20
    marks[1][2]=12
    marks[1][3]=15
    marks[2][0]=15
    marks[2][1]=17
    marks[2][2]=18
    marks[2][3]=16

     END

    APPLICATION ACTIVITY 2.1.

    1. Four secondary schools in RUHANGO District are displaying the number
       of students per year that they registered in 2015, 2016, 2017 and 2018.

    a. How many rows and columns will be in the table that contains the
        displayed data?

    b. Declare an array called population to contain the needed data.

    c. Initialize the array population with numbers of your choice.

    2. Given below the case of array a:

    a[0][0]     1      a[1][0] 54

    a[0][1]     2       a[1][1] 23

    a[0][2]      3       a[1][2] 11

    a[0][3]     13          a[1][3] 45

    a[0][4]     17          a[1][4] 31

    a[0][5 ]    34          a[1][5] 65

    a[0][6]     19              a[1][6] 26

    a. Give the size of the above array;

    b. Declare array a;

    c. Initialize the above array.

    2.2.5. Accessing two dimensional array elements

    LEARNING ACTIVITY 2.2.

    What do the following statements mean:

    WRITE marks[1][2] ;
    What are the meanings of the above statements

    • Reading (storing) two dimensional array elements

    There exist two ways of accessing the elements of an array. The elements’
    values of the array can come from the input devices or from a given file so that
    these elements are written into the array. The function used is READ or other
    versions of it, depending on the programming languages used for programs
    writing.

    For example READ marks[1][2] stores a value in second row, third column
    location of the array marks.

    To store multiple values into array you must use a FOR loop.

    Syntax:
    FOR i=initial value TO upperlimit DO
    FOR j=initial value TO upperlimit DO
    READ array name[i][j]i=i+1
    j=j+1
    END FOR
    END FOR
    Where i refers to the row position and j refers to the column position.

    Initial value=lower limit

    Example: Write an algorithm of a program that allows the user to enter (store) two
    dimensional array elements
    BEGIN
    SET marks=Array [3] [8] of Integer
    Use variable i as integer
    Use variable j as integer
    FOR i=0 TO 2 DO
    FOR j=0 TO 7 DO
    READ marks[i] [j]i=i+1
    j=j+1


    END FOR
    END FOR
    END


    Writing (displaying) two dimensional array elements

    To access two dimensional array elements’ values, we can also take the elements’
    values of an array residing in the memory of the computer and write them in any
    output device or a given file.

    To write (display) elements from an array in an output device or other file, use a
    WRITE function or other versions of it depending on the programming languages
    used for programs writing together with the array name and location (index) of the
    element. In that case the elements of a two dimensional array can be displayed by
    the following syntax:

             WRITE Array name [i][j]

    Where i refers to the row position and j refers to the column position.

    To display a single value of an array you must provide the array name and index to
    write operation example:

    Example for writing on screen a two dimensional array element
    WRITE a[1][2], i=1 and j=2).

    Example: Write an algorithm of a program that displays stored two dimensional
    array marks’ elements
    BEGIN
    SET a=Array[3][8] of integer
    Use variable i As integer
    Use variable j As integer
    WRITE “stored two dimensional array elements are:”
    FOR i=0 to 2DO
    FOR j=0 to 7DO
    WRITE a[i][j]i=i+1
    j= j+1
    END FOR
    END FOR
    END

    Algorithm for reading and printing values in arrays

    Example: Write an algorithm that allows the user to enter(store) two dimensional
                   array elements and displays those stored elements.



    APPLICATION ACTIVITY 2.2.

    1. Write an algorithm to do the following operations on a two dimensional
         array A of size m x n.

    • Declare the array A;

    • Read the element ‘values into matrix of size m x n

    • Output the elements’ values of matrix of size m x n on the screen;

    • Calculate the sum of all elements’ values of matrix of size m x n;

    • Write a programme in C++ Language where you apply the above questions

    2. Write an algorithm that allows a user to input data through input device
        and display the smallest element’ s value on the screen.

    3. Write a programme in C++ language that implements the above
        algorithm.

    4. Consider a 2 by 3 array T

    a. Write a declaration of T

    b. How many rows does T have?

    c. How many columns does T have?

    d. How many elements does T have?

    e. Write name of elements in second row

    f. Write the name of element in third column

    g. Write a single statement that sets the elements of T in row 1and column 2
        to zero

    h. Write a statement that inputs the values of T from keyboard

    i. Write a statement that displays the elements of first row of T

    2.3. ABSTRACT DATA STRUCTURE

    LEARNING ACTIVITY 2.3



    1. Observe and analyze the above figure

    2. Explain different procedures that you can use to arrange the above books.

    2.3.1. Definition of Abstract Data type in data structure.

    Abstract Data structure is a mathematical model of a data structure that specifies the
    type of data stored, the operations supported on them and the types of parameters
    of the operations with no implementation. Each program language has its own way
    to implement abstract data type.

    2.3.2 Importance of abstract data type in data structures

    • Data structures study how data are stored in a computer so that operations
    can be implemented efficiently;

    • Abstract Data structures are especially important when you have a large
       amount of information;

    • Conceptual and concrete ways to organize data for efficient storage and
       manipulation

    2.3.3. Abstract Data type Operations

    The data appearing in our data structures are processed by means of certain
     operations. Following are some of the most frequently used operations.

    • Searching: Finding the location of the record with a given key value or finding
      the locations of all records which satisfy one or more conditions;

    • Sorting: Arranging the records in some logical order .

    2.4. List

    2.4.1. Introduction

    A list is a collection of data in which each element of the list contains the location of
    the next element.

    In a list, each element contains two parts: data and link to the next element. The data
    parts of the list hold the value information and data to be processed. The link part
    of the list is used to chain the data together and contains a pointer (an address) that
    identifies the next element in the list.
    In the list you can do the following operations:

    LIST: Creates an empty list;

    INSERT: inserts an element in the list;

    DELETE: deletes an element from the list;

    RETRIEVE: retrieves an element from the list;

    TRAVERSE: traverses the list sequentially;

    EMPTY: checks the status of the list.

    Example of a list:

    A bank has 10 branches created one after another at different dates. The Bank
    Inspector who wants to visit all of them can follow the order of their creation. He/
    she will be informed only about the name and location of the first branch. When he
    reaches that branch, the Branch Manager will tell him/her the address of the next
    branch, and so one.

    After visiting all branches, the Bank Inspector will realize that he/she has a list of the
    bank branches.

    Graphically, it will be represented like a list where each branch is considered as a
    node containing the names of the branch and the address of the next branch.

    Difference between Arrays and Lists

    A list is an ordered set of data. It is often used to store objects that are to be processed
    sequentially.

    An array is an indexed set of variables, such as dancer [1], dancer [2], dancer [3] It is
    like a set of boxes that hold things. A list is a set of items. An array is a set of variables
    that each store an item.

    In a list, the missing spot is filled in when something is deleted. While in an array, an
    empty variable is left behind when something is deleted.Simply a list is a sequence
    of data, and linked list is a sequence of data linked with each other.

      2.4.2 Linked list

    This is a dynamic table/ data structure used to hold a sequence. Its characteristics
     are the following:

    • Items forming a sequence are not necessarily held in contiguous data location
       or in the order in which they occur in the sequence.

    • Each item in the list is called a node and contains an information field and a
       new address field called a link or pointer field.

    • Information field holds actual data for list item; link field contains the address
      of the next item.

    • The link field in the last item indicates that there are not further items. E.g. has
       a value of 0.

    • Associated with the list is a pointer variable which points to the first node in
       the list.

    • We use linked list in linking files, for example, in a hard disk.

    • It can grow or shrink in size during execution of a program.

    • It can be made just as long as required

    • It does not waste memory space.

    Linked list is classified into three types as shown below:
     
       • Single linked lists

      • Double linked lists
     
      • Circular linked list

    1. Single linked lists

    Single linked list is a sequence of elements in which every element has link to its
    next element in the sequence. In any single linked list, the individual element is
    called as “Node”. Every “Node” contains two fields, data and next. The data field is
    used to store actual value of that node and next field is used to store the address of
    the next node in the sequence




    In a single linked list, the address of the first node is always stored in a reference node
    known as “front” (Sometimes it is also known as “head”).Always next part (reference part) of the last node  must be NULL


    Algorithm in Single Linked List

    Creating and read an element in a NODE
    BEGIN
    struct node{
    int info
    struct node next
    } head, current, temp
    head=null
    temp=null
    current=null
    Begin sub
    Step 1 Read the element into x
    Step 2 Create a temp node in the memory
    temp =(struct node )sizeof (node)
    Step 3 Assign the values in temp node as follows
    temp -> info =x
    temp ->next=null
    End sub
    END

    Inserting at Specific location in the list (After a Node)
    We can use the following steps to insert a new node after a node in the single linked list

    • Step 1: Create a newNode with given value.

    • Step 2: Check whether list is Empty (head == NULL)

    • Step 3: If it is Empty then, set newNode => next = NULL and head = newNode.

    • Step 4: If it is Not Empty then, define a node pointer temp and initialize with head.

    • Step 5: Keep moving the temp to its next node until it reaches to the node

    after which we want to insert the newNode (until temp1 => data is equal to
    location, here location is the node value after which we want to insert the
    newNode).

    • Step 6: Every time check whether temp is reached to last node or not. If it
       is reached to last node then display ‘Given node is not found in the list!!!
       Insertion not possible!!!’ and termin ate the function. Otherwise move the
      temp to next node.

    • Step 7: Finally, Set ‘newNode => next = temp => next’ and ‘temp => next = newNode’

       Deleting a Specific Node from the list

    We can use the following steps to delete a specific node from a single linked list

    • Step 1: Check whether list is Empty (head == NULL)

    • Step 2: If it is Empty then, display ‘List is Empty!!! Deletion is not possible’ and
         terminate the function.

    • Step 3: If it is Not Empty then, define two Node pointers ‘temp1’ and ‘temp2’
        and initialize ‘temp1’ with head.

    • Step 4: Keep moving the temp1 until it reaches to the exact node to be deleted
      or to the last node. And every time set ‘temp2 = temp1’ before moving the
     ‘temp1’ to its next node.

    • Step 5: If it is reached to the last node then display ‘Given node not found in
       the list! Deletion not possible!!!’ And terminate the function.

    • Step 6: If it is reached to the exact node which we want to delete, then check
       whether list is having only one node or not

    • Step 7: If list has only one node and that is the node to be deleted, then set
       head = NULL and delete temp1 (free (temp1)).

    • Step 8: If list contains multiple nodes, then check whether temp1 is the first
       node in the list (temp1 == head).

    • Step 9: If temp1 is the first node then move the head to the next node (head =
       head => next) and delete temp1.

    • Step 10: If temp1 is not first node then check whether it is last node in the list
       (temp1=> next == NULL).

    • Step 11: If temp1 is last node then set temp2 => next = NULL and delete
      temp1 (free (temp1)).

    • Step 12: If temp1 is not first node and not last node then set temp2 => next =
       temp1=> next and delete temp1 (free (temp1)).

    Displaying a Single Linked List

    We can use the following steps to display the elements of a single linked list

    • Step 1: Check whether list is Empty (head == NULL)

    • Step 2: If it is Empty then, display ‘List is Empty!!!’ and terminate the function.

    • Step 3: If it is Not Empty then, define a Node pointer ‘temp’ and initialize with
       head.

    • Step 4: Keep displaying temp=> data with an arrow (->) until temp reaches to
       the last node

    • Step 5: Finally display temp => data with arrow pointing to NULL (temp =>
       data -> NULL).
     
    2. Double linked lists

    Double linked list is a sequence of elements in which every element has links to its
    previous element and next element in the sequence. So, we can traverse forward by
    using next field and can traverse backward by using previous field. Every node in a
    double linked list contains three fields and they are shown in the following figure

    Algorithm in Double Linked List

    Inserting at Specific location in the list (After a Node)

    We can use the following steps to insert a new node after a node in the double
    linked list

    • Step 1: Create a newNode with given value.

    • Step 2: Check whether list is Empty (head == NULL)

    • Step 3: If it is Empty then, assign NULL to newNode => previous&newNode =>
                next and newNode to head.

    • Step 4: If it is not Empty then, define two node pointers temp1&temp2 and initialize temp1 with head.

    • Step 5: Keep moving the temp1 to its next node until it reaches to the node
      after which we want to insert the newNode (until temp1 => data is equal to
      location, here location is the node value after which we want to insert the newNode).

    • Step 6: Every time check whether temp1 is reached to the last node. If it is
       reached to the last node then display ‘Given node is not found in the list!!!
       Insertion not possible!!!’ and terminate the function. Otherwise move the
        temp1 to next node.

    • Step 7: Assign temp1 => next to temp2, newNode to temp1=> next, temp1
       to newNode => previous, temp2 to newNode => next and newNode to temp2
        => previous.

    Deleting a Specific Node from the list

    We can use the following steps to delete a specific node from the double linked list

    • Step 1: Check whether list is Empty (head == NULL)

    • Step 2: If it is Empty then, display ‘List is Empty!!! Deletion is not possible’ and
                 terminate the function.

    • Step 3: If it is not Empty, then define a Node pointer ‘temp’ and initialize with head.

    • Step 4: Keep moving the temp until it reaches to the exact node to be deleted
        or to the last node.

    • Step 5: If it is reached to the last node, then display ‘Given node not found in
      the list! Deletion not possible!!!’ and terminate the fuction.

    • Step 6: If it is reached to the exact node which we want to delete, then check
       whether list is having only one node or not

    • Step 7: If list has only one node and that is the node which is to be deleted
       then set head to NULL and delete temp (free(temp)).

    • Step 8: If list contains multiple nodes, then check whether temp is the first
       node in the list (temp == head).

    • Step 9: If temp is the first node, then move the head to the next node (head =
       head => next), set head of previous to NULL (head => previous = NULL) and
        delete temp.

    • Step 10: If temp is not the first node, then check whether it is the last node in
       the list (temp => next == NULL).

    • Step 11: If temp is the last node then set temp of previous of next to NULL
    (temp => previous => next = NULL) and delete temp (free(temp)).

    • Step 12: If temp is not the first node and not the last node, then set temp of
       previous of next to temp of next (temp => previous => next = temp => next),
       temp of next of previous to temp of previous (temp => next => previous =
       temp => previous) and delete temp (free(temp)).

    Displaying a Double Linked List

    We can use the following steps to display the elements of a double linked list

    Step 1: Check whether list is Empty (head == NULL)

    Step 2: If it is Empty, then display ‘List is Empty!!!’ and terminate the function.

    Step 3: If it is not Empty, then define a Node pointer ‘temp’ and initialize with
       head.

    Step 4: Display ‘NULL <= ‘.

    Step 5: Keep displaying temp → data with an arrow (↔) until temp reaches to
       the last node

    • Step 6: Finally, display temp → data with arrow pointing to NULL (temp → data ---> NULL).

    3. Circular Linked List

    In circular linked list, every node points to its next node in the sequence but the last
    node points to the first node in the list

    Algorithm in Circular Linked List

    Inserting at Specific location in the list (After a Node)

    We can use the following steps to insert a new node after a node in the circular
    linked list...

    • Step 1: Create a newNode with given value.

    • Step 2: Check whether list is Empty (head == NULL)

    • Step 3: If it is Empty then, set head = newNode and newNode → next = head.

    • Step 4: If it is Not Empty then, define a node pointer temp and initialize with head.

    • Step 5: Keep moving the temp to its next node until it reaches to the node
      after which we want to insert the newNode (until temp1 → data is equal to
     location, here location is the node value after which we want to insert the newNode).

    • Step 6: Every time check whether temp is reached to the last node or not. If
       it is reached to last node then display ‘Given node is not found in the list!!!
      Insertion not possible!!!’ and terminate the function. Otherwise move the
      temp to next node.

    • Step 7: If temp is reached to the exact node after which we want to insert the
       newNode then check whether it is last node (temp → next == head).

    • Step 8: If temp is last node then set temp → next = newNode and newNode
    → next = head.

    • Step 8: If temp is not last node then set newNode → next = temp → next
      and temp → next = newNode.

    Deleting a Specific Node from the list

    We can use the following steps to delete a specific node from the circular linked list...

    Step 1: Check whether list is Empty (head == NULL)

    Step 2: If it is Empty then, display ‘List is Empty!!! Deletion is not possible’
      and terminate the function.

    Step 3: If it is Not Empty then, define two Node pointers ‘temp1’ and ‘temp2
      and initialize ‘temp1’ with head.

    Step 4: Keep moving the temp1 until it reaches to the exact node to be deleted
      or to the last node. And every time set ‘temp2 = temp1’ before moving the
      ‘temp1’ to its next node.

    Step 5: If it is reached to the last node then display ‘Given node not found in
      the list! Deletion not possible!!!’
    . And terminate the function.

    Step 6: If it is reached to the exact node which we want to delete, then check
       whether list is having only one node (temp1 → next == head)

    Step 7: If list has only one node and that is the node to be deleted then set
       head = NULL and delete temp1 (free(temp1)).

    Step 8: If list contains multiple nodes then check whether temp1 is the first
      node in the list (temp1 == head).

    Step 9: If temp1 is the first node then set temp2 = head and keep moving
       temp2 to its next node until temp2 reaches to the last node. Then set head =
       head → next, temp2 → next = head and delete temp1.

    Step 10: If temp1 is not first node then check whether it is last node in the list

    (temp1 → next == head).

    Step 11: If temp1 is last node then set temp2 → next = head and delete
    temp1 (free (temp1)).

    Step 12: If temp1 is not first node and not last node then set temp2 → next
    = temp1 → next and delete temp1 (free (temp1)).

    Displaying a circular Linked List

    We can use the following steps to display the elements of a circular linked list

    Step 1: Check whether list is Empty (head == NULL)

    Step 2: If it is Empty, then display ‘List is Empty!!!’ and terminate the function.

    Step 3: If it is Not Empty then, define a Node pointer ‘temp’ and initialize with
                 head.

    Step 4: Keep displaying temp → data with an arrow (--->) until temp reaches
       to the last node

    • Step 5: Finally display temp → data with arrow pointing to head → data.

    2.5. Queue

    A queue is a linear list in which data can only be inserted at one end, called the REAR,
    and deleted from the other end, called the FRONT. These restrictions ensure that the
    data is processed through the queue in the order in which it is received. In an other
    words, a queue is a structure in which whatever goes fist comes out first (first in,
    first out(FIFO) structure).



    2.5.1 Types of queues

    There exist two types of queues:

    • Linear queue

    • Circular queue

    a. Linear Queue

    Queue data structure is a linear data structure in which the operations
    are performed based on FIFO principle. Queue Operations using Array
    before we implement actual operations, first follow the below steps to create an
    empty queue.

    Step 1: Include all the header files which are used in the program and define
      a constant ‘SIZE’ with specific value.

    Step 2: Declare all the user defined functions which are used in queue
        implementation.

    Step 3: Create a one dimensional array with above defined SIZE (int queue[SIZE])

    Step 4: Define two integer variables ‘front’ and ‘rear’ and initialize both with
        ‘-1’. (int front = -1, rear = -1)

    • Step 5: Then implement main method by displaying menu of operations list
     and make suitable function calls to perform operation selected by the user on
      queue.

    enQueue(value) - Inserting value into the queue


    • Step 1: Check whether queue is FULL. (rear == SIZE-1)

    • Step 2: If it is FULL, then display “Queue is FULL!!! Insertion is not possible!!!””
       and terminate the function.

    • Step 3: If it is NOT FULL, then increment rear value by one (rear++) and set
      queue [rear] = value.

    deQueue() - Deleting a value from the Queue

    • Step 1: Check whether queue is EMPTY. (front == rear)

    • Step 2: If it is EMPTY, then display “Queue is EMPTY!!! Deletion is not possible!!!”
       and terminate the function.

    • Step 3: If it is NOT EMPTY, then increment the front value by one (front ++).
      Then display queue[front] as deleted element. Then check whether both front
       and rear are equal (front == rear), if it TRUE, then set both front and rear to ‘-1’
       (front = rear = -1).

    display() - Displays the elements of a Queue

    We can use the following steps to display the elements of a queue

    Step 1: Check whether queue is EMPTY. (front == rear)

    • Step 2: If it is EMPTY, then display “Queue is EMPTY!!!” and terminate the
      function.

    Step 3: If it is NOT EMPTY, then define an integer variable ‘I’ and set ‘i = front+1’.

    Step 3: Display ‘queue[i]’ value and increment ‘I’ value by one (i++). Repeat
       the same until ‘I’ value is equal to rear (i<= rear)

    b. Circular Queue

    Circular Queue is a linear data structure in which the operations are performed
    based on FIFO (First In First Out) principle and the last position is connected back to
    the first position to make a circle.

    Circular Queue Operation

    To implement a circular queue data structure using array, we first create it.

    Step 1: Include all the header files which are used in the program and define a
       constant ‘SIZE’ with specific value.

    Step 2: Declare all user defined functions used in circular queue implementation.

    Step 3: Create a one dimensional array with above defined SIZE (int cQueue[SIZE])

    Step 4: Define two integer variables ‘front’ and ‘rear’ and initialize both with ‘-1’. (int
       front = -1, rear = -1)

    Step 5: Implement main method by displaying menu of operations list and make
      suitable function calls to perform operation selected by the user on circular queue.

    enQueue(value) - Inserting value into the Circular Queue

    • Step 1: Check whether queue is FULL. ((rear == SIZE-1 && front == 0) || (front ==
       rear+1))

    • Step 2: If it is FULL, then display “Queue is FULL!!! Insertion is not possible!!!” and
       terminate the function.

    • Step 3: If it is NOT FULL, then check rear == SIZE - 1 && front != 0 if it is TRUE, then
       set rear = -1.

    • Step 4: Increment rear value by one (rear++), set queue[rear] = value and check
    ‹front == -1’ if it is TRUE, then set front = 0.

    deQueue() - Deleting a value from the Circular Queue

    Step 1: Check whether queue is EMPTY. (front == -1 && rear == -1)

    Step 2: If it is EMPTY, then display “Queue is EMPTY!!! Deletion is not possible!!!” and
       terminate the function.

    • Step 3: If it is NOT EMPTY, then display queue[front] as deleted element and
       increment the front value by one (front ++). Then check whether front == SIZE, if it
       is TRUE, then set ‘front = 0’. Then check whether both ‘front – 1’ and rear are equal
       (front -1 == rear), if it TRUE, then set both front and rear to ‘-1’ (front = rear = -1).

    display () - Displays the elements of a Circular Queue

    Step 1: Check whether queue is EMPTY. (front == -1)

    Step 2: If it is EMPTY, then display “Queue is EMPTY!!!” and terminate the function.

    Step 3: If it is NOT EMPTY, then define an integer variable ‘i’ and set ‘i = front’.

    Step 4: Check whether ‘front <= rear’, if it is TRUE, then display ‘queue[i]’ value and
       increment ‘I’ value by one (i++). Repeat the same until ‘i <= rear’ becomes FALSE.

    Step 5: If ‘front <= rear’ is FALSE, then display ‘queue[i]’ value and increment ‘I’ value
       by one (i++). Repeat the same until ‘i <= SIZE – 1’ becomes FALSE.

    Step 6: Set i to 0.

    Step 7: Again display ‘cQueue[i]’ value and increment i value by one (i++). Repeat
       the same until ‘i <= rear’ becomes FALSE.

    2.5.2 Queue operations

    There are three main operations related to queues.

    Enqueue: the enqueue operation inserts an items at the rear of the queue

    Dequeue: the dequeue operation deletes the item at the front of the queue

    Display: show elements in the array

       2.6 Stack

    A stack is a restricted linear list in which all additions and deletions are made at one
    end, the top. If we insert a series of data items into a stack and then remove them,
    the order of the data is reversed. Data input as 5, 10, 15, 20, for example would be
    removed as 20, 15, 10, and 5. This reversing attribute is why stacks are known as Last
    in, First out (LIFO) data structures.

    We use many different types of stacks in our daily lives. We often talk of a stack of
    coins, stack of books on a table and stack of plates in a kitchen. Any situation in which

    we can only add or remove an object at the top is a stack. If we want to remove an
    object other than the one at the top, we must first remove all objects above it. The
    following charts illustrates cases of stack

    A Stack is a Last in First out (LIFO) dynamic table or data structure. It has the following
    characteristics:

    • List of the same kind of elements;

    • Addition and deletion of elements occur only at one end, called the top of the
      stack;

    • Computers use stacks to implement method calls;

    • Stacks are also used to convert recursive algorithms into non recursive
      algorithm.

    2.6.1 Operations performed on stacks

    The different operations performed on stacks are as follows:

    Push: adds an element to the stack

    Pop: removes an element from the stack

    Peek: display at top element of the stack

    Stack Operations using Array

    Before implementing actual operations, first follow the below steps to create an
    empty stack.

    Step 1: Include all the header files which are used in the program and define a
    constant ‘SIZE’ with specific value.

    Step 2: Declare all the functions used in stack implementation.

    Step 3: Create a one dimensional array with fixed size (int stack[SIZE])

    Step 4: Define a integer variable ‘top’ and initialize with ‘-1’. (int top = -1)

    • Step 5: In main method display menu with list of operations and make suitable
      function calls to perform operation selected by the user on the stack.

    push(value) - Inserting value into the stack

    Step 1: Check whether stack is FULL. (top == SIZE-1)

    Step 2: If it is FULL, then display “Stack is FULL!!! Insertion is not possible!!!” and
      terminate the function.

    Step 3: If it is NOT FULL, then increment top value by one (top++) and set stack [top]  to value (stack[top] = value).

    pop() - Delete a value from the Stack

    Step 1: Check whether stack is EMPTY. (top == -1)

    Step 2: If it is EMPTY, then display “Stack is EMPTY!!! Deletion is not possible!!!’” and
      terminate the function.

    Step 3: If it is NOT EMPTY, then delete stack [top] and decrement top value by
       one(top-).

    Display() - Displays the elements of a Stack

    Step 1: Check whether stack is EMPTY. (top == -1)

    Step 2: If it is EMPTY, then display “Stack is EMPTY!!!” and terminate the function.

    Step 3: If it is NOT EMPTY, then define a variable ‘I’ and initialize with top.
      Display stack[i] value and decrement i value by one (i--).

    • Step 3: Repeat above step until i value becomes ‘0’.

      2.6.2 Stack exceptions

    Adding an element to a full stack and removing an element from an empty stack
    would generate errors or exceptions:

    Stack overflow exception: it occurs if you try to add an item to stack or queue
      which is already full.

    Stack underflow exception: it occurs if you try to remove an item from an
    empty queue or stack.

    Notec 1: Stack and Queue data structures can be implement in two ways: By using
    array or by using linked list.

    Notice 2: When stack or Queue is implemented using array, that stack or Queue can
    organize only a limited number of elements. When stack or Queue is implemented
    using linked list, that stack or Queue can organize an unlimited number of elements.

       2.7 Tree

    In linear data structure, data is organized in sequential order and in non-linear data
    structure; data is organized in random order. Tree is a very popular data structure
    used in wide range of applications. A tree data structure can be defined as follows.

    In a tree data structure, if we have N number of nodes then we can have a maximum
    of N-1 number of links.

    Tree data structure is a collection of data (Node) which is organized in hierarchical
    structure and this is a recursive definition.

    Example


    2.7.1 Tree Terminology

    In a tree data structure, we use the following terminology:

    a. Root

    In a tree data structure, the first node is called as Root Node. Every tree must have
    root node..



       b. Edge

    In a tree data structure, the connecting link between any two nodes is called an Edge.
    In a tree with ‘N’ number of nodes there will be a maximum of ‘N-1’ number of edges.

    c. Parent

    In a tree data structure, the node which is predecessor of any node is called a
    PARENT NODE. In simple words, the node which has branch from it to any other
    node is called as parent node.
          d. Child

    In a tree data structure, the node which is descendant of any node is called a CHILD
    Node. In a tree, any parent node can have any number of child nodes. In a tree, all
    the nodes except root are child nodes.

         e. Siblings
    In a tree data structure, nodes which belong to same Parent are called SIBLINGS.

    In a tree data structure, the node which does not have a child is called a LEAF Node.
    In a tree data structure, the leaf nodes are also called a External Nodes or Terminal
    node.

               g. Internal Nods

    In a tree data structure, the node which has at least one child is called INTERNAL Node.
    In a tree data structure, nodes other than leaf nodes are called Internal Nodes. The
    root node is also said to be Internal Node if the tree has more than one node. Internal
    nodes are also called as ‹Non-Terminal’ nodes.


          h. Degree

    In a tree data structure, the total number of children of a node is called as DEGREE of
    that Node. In simple words, the Degree of a node is total number of children it has. The
    highest degree of a node among all the nodes in a tree is called as ‹Degree of Tree’

         i. Level

    In a tree data structure, the root node is said to be at Level 0 and the children of root
    node are at Level 1 and the children of the nodes which are at Level 1 will be at Level
    2 and so on... In simple words, in a tree each step from top to bottom is called as a
    Level and the Level count starts with ‘0’ and incremented by one at each level (Step).



          j. Height

    In a tree data structure, the total number of edges from leaf node to a particular
    node in the longest path is called as HEIGHT of that Node. In a tree, height of the root
    node is said to be height of the tree. In a tree, height of all leaf nodes is ‘0’.


    Figure 2.25.: Height representation
                
               k. Depth
    In a tree data structure, the total number of edges from root node to a particular
    node is called DEPTH of that Node. In a tree, the total number of edges from root node
    to a leaf node in the longest path is said to be Depth of the tree. In a tree, depth of
    the root node is ‘0’.



            l. Path

    In a tree data structure, the sequence of Nodes and Edges from one node to another
    node is called as PATH between those two Nodes. Length of a Path is total number of
    nodes in that path. In below example the path A - B - E - J has length 4.



            m. Sub Tree

    In a tree data structure, each child from a node forms a sub tree recursively. Every
    child node will form a sub-tree on its parent node.


       2.7.2 Binary Tree Representations

    A binary tree data structure is represented using two methods. Those methods are
    as follows:

    • Linked List of Binary Tree representation

    • Array Representation
    Let T be a Binary Tree. There are two ways of representing T in the memory as follow
    Linked

    a. Linked List of Binary Tree representation

    Consider a Binary Tree T. T will be maintained in memory by means of a linked list
    representation, which uses three parallel arrays; INFO, LEFT, and RIGHT pointer
    variable ROOT as follows. In Binary Tree, each node N of T will correspond to a
    location k such that:

    1. LEFT [k] contains the location of the left child of node N.

    2. INFO [k] contains the data at the node N.

    3. RIGHT [k] contains the location of right child of node N.
        • Representation of a node:


    In this representation of binary tree, root will contain the location of the root R of T.
    If any one of the sub tree is empty, then the corresponding pointer will contain the
    null value if the tree T itself is empty, the ROOT will contain the null value.

    Example

    Consider the binary tree T in the figure of Binary Tree


    Linked Representation of the Binary Tree

    b. Array Representation of Binary Tree
    Let us consider that we have a tree T. let our tree T is a binary tree that us complete binary
    tree. Then there is an efficient way of representing T in the memory called the sequential
    representation or array representation of T. This representation uses only a linear array
    TREE as follows:

    1. The root N of T is stored in TREE [1].

    2. If a node occupies TREE [k] then its left child is stored in TREE [2 * k] and its
       right child is stored into TREE [2 * k + 1].

    For Example:
    Consider the following Tree:




    Its sequential representation is as follow:


    2.7.3 Binary Tree Traversals

    When we wanted to display a binary tree, we need to follow some order in which all
    the nodes of that binary tree must be displayed. In any binary tree displaying order
    of nodes depends on the traversal method.

    Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree
    Traversal.

    There are three types of binary tree traversals.

    • In - Order Traversal

    • Pre - Order Traversal

    • Post - Order Traversal

    Traversal is a process to visit all the nodes of a tree and may print their values too.
    Because, all nodes are connected via edges (links) we always start from the root
    (head) node. That is, we cannot randomly access a node in a tree.

    Generally, we traverse a tree to search or locate a given item or key in the tree or to
    print all the values it contains.

    a. In-order Traversal

    In this traversal method, the left sub tree is visited first, then the root and later the
    right sub-tree. We should always remember that every node may represent a sub
    tree itself.

    If a binary tree is traversed in-order, the output will produce sorted key values in an
    ascending order.


    We start from A, and following in-order traversal, we move to its left subtree B. B is
    also traversed in-order. The process goes on until all the nodes are visited. The output
    of inorder traversal of this tree will be −

    D → B → E → A → F → C → G

    Algorithm:

    Until all nodes are traversed −

    Step 1 − Recursively traverse left subtree.

    Step 2 − Visit root node.

    Step 3 − Recursively traverse right subtree.

    b. Pre-order Traversal

    In this traversal method, the root node is visited first, then the left subtree and finally
    the right subtree.

    We start from A, and following pre-order traversal, we first visit A itself and then
    move to its left subtree B. B is also traversed pre-order. The process goes on until all the
    nodes are visited. The output of pre-order traversal of this tree will be −

    A → B → D → E → C → F → G

    Algorithm:

    Until all nodes are traversed −

    Step 1 − Visit root node.

    Step 2 − Recursively traverse left subtree.

    Step 3 − Recursively traverse right subtree.

    c. Post-order Traversal

    In this traversal method, the root node is visited last, hence the name. First we
    traverse the left sub tree, then the right sub tree and finally the root node.



    We start from A, and following Post-order traversal, we first visit the left sub tree B. B is also
    traversed post-order. The process goes on until all the nodes are visited. The output of
    post-order traversal of this tree will be −
    D → E → B → F → G → C → A

    Algorithm:

    Until all nodes are traversed −

    Step 1 − Recursively traverse left subtree.

    Step 2 − Recursively traverse right subtree.

    Step 3 − Visit root node.

    Binary Search tree exhibits a special behavior. A node’s left child must have a value
    less than its parent’s value and the node’s right child must have a value greater than
    its parent value.

        2.7.4. Basic Operations on binary tree

    A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
       properties

    • The left sub-tree of a node has a key less than or equal to its parent node’s key.

    • The right sub-tree of a node has a key greater than to its parent node’s key.

    Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right

    sub-tree and can be defined as
    left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)

    Representation

    BST is a collection of nodes arranged in a way where they maintain BST properties.
    Each node has a key and an associated value. While searching, the desired key is
    compared to the keys in BST and if found, the associated value is retrieved.
    Following is a pictorial representation of BST






  • UNIT 3: INTRODUCTION TO COMPUTER NETWORK

    Key Unit Competency:
    To be able to explain principles, standards and purposes of computer network

    Read the following scenario and answer to the asked questions.

    In the school computer labs, choose a classmate and send him/her an email that
    has “Computer Network “as the email subject and the email body contains names of
    previous units already covered in senior 5 computer science. Ask him/her to reply
    immediately to your email.

    After receiving the reply, answer the following questions:

    1. List all possible elements that make this communication possible

    2. What devices are used to facilitate sending email successfully?

    3. Discuss what made possible the sending and receiving of emails

    4. Do you like using email?

    5. How do you value the factor of sending and receiving an email

    6. Describe what you see in the photo below?

    3.1. Fundamental of computer Networ

    3.1.1. Computer Network Definition

    ACTIVITY 3.1

    Observe computers in the computer lab and answer the following question?

    1. Describe what you see?

    2. What are transmission media used to connect computers in the
        computer labs?

    3. Are all devices connected?

    A computer network is a system of interconnected computers for the purpose of
    sharing data and resources.

    Computers on a network are called nodes. Nodes can include hosts such as personal
    computers, phones, servers as well as networking hardware. Two devices are
    networked together when one device is able to exchange information with the
    other device. The computer can be connected to another in the two ways.

    Wired network: Computers are connected using cable media. Most commonly
    Ethernet Cable, coaxial cable and optic fiber.

    Wireless network: Computers are connected using wireless media. Radio waves are
    used in wireless mode.

    3.1.2 Properties of Computer Network

    • Easy Sharing of Resources: Computers are able to share various resources
    easily over a network. Shared resources can be Internet, files, printer, storage
    and others.

    Performance: It is achieved by measuring the speed of data transmission
    with number of network users, connectivity used and the software used. The
    commonly measured qualities in the network performance are Bandwidth
    and Latency.

    Reliability: It means that computer network provides assurance of the
    delivery of data to the intended recipient.

    Scalability: The possibility of adding new computer without affecting the
    network performance.

    Security: computer network must be secured for the benefit of the user and
    data protection. The security is achieved by protecting data from unauthorized
    access.

    Quality of Service (QoS): Quality of Service refers to the mechanism that
       manage congested network traffic.

    Fault tolerant: A fault tolerant network limits the impact of hardware or
    software failure and recovers quickly when a failure occurs

    APPLICATION ACTIVITY 3.2

    1. Investigate what happen when a shared resource is disconnected from
    the computer network?

    2. Imagine other areas where computer network is used?

    3.1.3 Advantages and Disadvantage of Computer Networking
           The common advantages of computer network

    Activity 3.2

    1. Discuss the disadvantages of using computer network within your school?

    2. In class of senior 5 MPC, Computer Science Teacher decides to share notes
       for students to use on our school network. The mathematics teacher decides
       to print notes of 100 pages and distributes to each member of senior 5 MPC
       class.

    i. Evaluate the cost impact for both teachers

    ii. Both teachers, whom save money in giving notes.

    The common advantages of computer network

    1. Enhanced communication and availability of information: It allows access
       to a vast amount of useful information.

    Example: Population data, newsletters, online businesses, contents,
    Applications.

    2. Allow resource sharing: Fewer resources are needed when an organization
    uses a computer network.
    Example: only one printer is needed instead of buying a printer for each office.

    3. File sharing made easy: computer network allows people to share files, which
        helps to save more time and effort.
        Example: A teacher can share homework to all students through school
        network

    4. Improve storage capacity: since you are going to share information, files and
        resources to other people, you have to ensure that all data and content are
        properly stored in the system.

    5. Cost efficiency: on computer network, you can share software license installed
    on the server and can then be used by various workstations.

    6. Security of information and resources: users cannot see other users' files
    unlike on stand-alone machines.

    7. Backup of data is easy as all the data is stored on the file server.

    The common disadvantages of computer networking

    1. Lack of independence: people rely on computer network and when the
    system is down, people get stack. Most of organizations depend on the
    computer networks.

    2. Security issues: huge number of people use a computer network to get and
    share their files and resources, a certain user’s security would be always at
    risk. Viruses can spread to other computers throughout a computer network.
    There is a danger of hacking, particularly with wide area networks. Security
    procedures are needed to prevent such abuse, Examples: The use of Antivirus
    and firewall.

    3. Lack of robustness: computer network’s main server breaks down, the entire
    system would become useless

    APPLICATION ACTIVITY 3.2

    1. Investigate what happen when a shared resource is disconnected from
        the computer network?

    2. Imagine other areas where computer network is used?

    3.1.4 Types of computer networks

    Activity 3.3

    With two or more Bluetooth enabled devices available in the classroom:

    1. Turn on the Bluetooth feature on both devices

    2. Share and receive files such images and documents between the
       devices

    3. Turn off Bluetooth feature in the two devices.

    A computer network is classified basing on the size of the area covered, the number
    of users connected and the number & types of services available.

    The followings are type of computer networks:

    1. Personal Area Network (PAN)

    A personal area network (PAN) is a network that connects devices, such as mice,
    keyboards, printers, Smartphone, and tablets within the range of an individual
    person. PAN has connectivity range up to 10 meters. PAN may include wireless
    computer keyboard and mouse, Bluetooth enabled headphones, wireless printers
    and TV remotes. All of these devices are dedicated to a single host and are most
    often connected with Bluetooth technology.

    Bluetooth is a wireless technology that enables devices to communicate over short
    distances. A Bluetooth device can connect up to seven other Bluetooth devices.

    2. Local Area Network (LAN)

    Traditionally, a LAN is defined as a network that covers a small geographical area.
    However, the distinguishing characteristic for LANs today is that they are typically
    owned by an individual, such as in a home or small business, or wholly managed
    by an IT department, such as in a school or corporation. This individual or group
    enforces the security and access control policies of the network. LAN uses Ethernet
    IEEE 802.3 as its standard.

    A Wireless LAN (WLAN) is a LAN that uses radio waves to transmit data between
    wireless devices. In a traditional LAN, devices are connected together using copper
    cabling. In some environments, installing copper cabling might not be practical,
    desirable, or even possible. In these situations, wireless devices are used to transmit
    and receive data using radio waves. As with LANs, on a WLAN, you can share resources,
    such as files, printers, and Internet access. WLAN uses Ethernet IEEE 802.11 as its
    standard.

    3. Metropolitan Area Network (MAN)

    A metropolitan area network (MAN) is a network that spans across a large organization
    like campus or a city. The network consists of various buildings interconnected
    through wireless or fiber optic backbones.

    A backbone is the part of the computer network infrastructure that interconnects
    different LAN networks and provides a path for exchange of data between these
    different networks

    The communication links and equipment are typically owned by a network service
    provider who sells the service to the users. A MAN can acts as a high-speed network
    to enable sharing of regional resources.

    4. Wide Area Network (WAN)

    A WAN connects multiple networks that are in geographically separated locations.

    The distinguishing characteristic of a WAN is that it is owned by a service provider.
    Individuals and organizations contract for WAN services. WAN network provides
    connectivity to MANs and LANs. The most common example of a WAN is the
    Internetwork or Internet in short. The Internet is a large WAN that is composed of
    millions of interconnected networks.

    Example: Kigali and Nairobi networks are connected through the Internet

    APPLICATION ACTIVITY 3.3

    1. Discuss the role ISP services for LANs?

    2. Do an observation in the school computer lab and categorize the
    computer network type available at your school? Justify your answer.

    3. Using clear examples, Distinguish Personal Area Network and Local Area
    Network?

    4. Using an arrow match the following in Group A with their
    corresponding in Group B

    Group A                                               Group B
    a. Radio waves                                     1. Qualities of Computer network
    Performance

    b. Millions of interconnected network    2. Disadvantages of Computer network

    c. Sharing resources                             3. Wireless

    d. Hacking attacks                                 4. WAN

    e. Bandwidth and Latency                     5. Advantages of Computer network

    3.2 Computer Network Concept and Technology

    ACTIVITY 3.4

    You are browsing a website on the internet while the speed is okay and suddenly you
    find that the page is loading slowly. Investigate the reason behind slowness?

    3.2.1 Network metrics

    Network metrics are defined as standards of measurement by which efficiency,
    performance, progress, or quality of a plan, process can be assessed. Network metric
    are used by a router to make routing decisions.

    When data is sent over a computer network, it is broken up into small chunks called
    packets. Each packet contains source and destination address information. Packets
    are sent across a network one bit at a time.

          a. Bandwidth

    Bandwidth is the amount of data that can be transmitted in a fixed amount of time.
    Bandwidth is measured in the number of bits that can be sent every second.
    The following are examples of bandwidth measurements:

    • b/s - bits per second

    • kb/s - kilobits per second

    • Mb/s - megabits per second

    • Gb/s - gigabits per second

                    b. Latency
    Latency is the time between requesting data and receiving data. More simply put,
    the time it takes to establish a connection between your computer and the server
    hosting the website you requested. The important thing to take away here is that
    latency is not speed. Data is delayed by network devices and cable length. Network
    devices add latency when processing and forwarding data.

                     c. Throughput:
    Throughput is the actual rate at which information is transferred. It measures the
    amount of completed work against time consumed and may be used to measure
    the performance of a processor, memory and/or network communications.

                       d. Error rate:
    Error rate is the number of corrupted bits expressed as percentage or fraction of the
    total sent.
                        e. Jitter:
    Jitter is variation in packet delay at the receiver of information. For measuring the
    capacity of all of these metrics above, we focus on capacity of message and this one
    change into different form depending on the network devices where this message
    is located.

                   3.2.2 Data Transmission model

    The term transmission mode is used to define the direction of signal flow between
    two linked devices. The data that is transmitted over the network can flow using one
    of three modes: simplex, half-duplex and full-duplex.

    1. Simplex: it is a single one-way transmission. In a simplex transmission
    mode, the communication between sender and receiver occurs only in one
    direction. That means only the sender can transmit data, and receiver can
    receive that data. The receiver cannot transmit any information back to the
    sender.

    The keyboard to monitor transmission is an example of simplex transmission
    mode. Other examples are communication between a computer and a
    printer, listening to the radio and the signal that is sent from a TV station to
    your home TV.

    2. Half-Duplex: data flows in one direction at a time. In half-duplex, the
        channel of communications allows alternating transmission in two
       directions, but not in both directions simultaneously. An Example of Halfduplex
       is the Talkie- Walkie used by the police.

    3. Full-Duplex: data flows in both directions at the same time. In a full duplex
       transmission mode, the communication between sender and receiver can
      occur simultaneously. Sender and receiver both can transmit and receive
      simultaneously at the same time.

    A telephone conversation is an example of full-duplex communication. Both people
    can talk and be heard at the same time.

    APPLICATION ACTIVITY 3.4

    1. Examine 2 reasons that cause latency in computer network.

    2. What is your school download bandwidth and upload bandwidth?

    3. Contrast upload bandwidth and download bandwidth?

    4. Categorize following devices according to their transmission modes

                         a. TV

                         b. Radio

                         c. Walkie -Talkie

                         d. Phone

                         e. Computer

    3.2.3. Internetwork (Internet, Intranet, Extranet)

    ACTIVITY 3.5

    Using computer network, an organization’s employees can access data when
    they are inside the organization buildingand when they are physically outside.
    Investigate technologies that can be used to allow employees inside and outside
    to access organization’s data.

    A network of networks is called an internetwork, or simply the Internet. The Internet,
    extranets, and intranets all rely on Transport Control Protocol / Internet Protocol
    (TCP/IP). However, they are different in terms of the levels of access they allow to
    various users inside and outside the organization and the size of the network.

    1. An Intranet is a private computer network that uses Internet Protocol to
       securely share any part of an organization’s information or operational
       systems within that organization. Only users inside the organization are
        only allowed to access it.

    2. An Extranet is a private network that uses Internet protocols, network

    connectivity. An extranet can be viewed as part of a company’s intranet
    that is extended to users outside the company, the connectivity is made
    possible by the Internet.

    3. The Internet is a global system of interconnected computer networks that
    use the standard Internet Protocol suite (TCP/IP) to serve billions of users
    worldwide.

    The difference between the Internet and Extranets is that while the extranet allows
    limited access to non-members of an organization, the Internet generally allows
    everyone to access all network resources.

    APPLICATION ACTIVITY 3.5

    General supply Ltd. sell various services online and offline. It has various partners such
    as suppliers, sellers, buyers and clients in different Districts of Rwanda. Each partner
    wants to access the General supply data from its servers located at the main office in
    Ruhango District.

    Examine in details the appropriate technology for each user to access the General
    supply Ltd. data to avoid the user location problem

    3.3 Local Area Networks (LANs)

    ACTIVITY 3.6

    By definition, computer network is said to be a group of computers connected together
    and share resources. Using your school environment, observe followings:

    1. The range covered by your school network?

    2. The number of users on your school network?

    3. Resources shared on your school network?

    3.3.1 Definition

    Local Area Networks (LANs) are networks usually confined to a geographic area, such
    as a single building or a college campus. LANs can be small, linking as few as three
    computers, but often link hundreds of computers used by thousands of people.

    3.3.2 LAN Categories

    1. Peer-to-Peer Network

    A peer-to-peer (P2P) network is created when two or more computers are connected
    and share resources without going through a separate server computer. In a peerto-
    peer network, there is no hierarchy among the computers, nor are there any
    dedicated servers.

    Each device on the network, also called a client, has equivalent capabilities and
    responsibilities. A user is responsible for its own resources and can decide which
    data and devices to be shared with other computers. Because individual users are
    responsible for the resources on their own computers, the network has no central
    point of control and no central administration. Peer-to-peer networks work best in
    environments with ten or fewer computers.

    Advantages of peer to peer network are as follows:

    • The main advantage of peer to peer network is that it is easier to set up

    • In peer-to-peer networks all nodes are act as server as well as client therefore
      no need of dedicated server

    • The peer to peer network is less expensive

    • Peer to peer network is easier to set up and use this means that you can spend
     less time in the configuration and implementation of peer to peer network.

    Disadvantages of peer to peer network

    • A computer can be accessed anytime

    • Network security has to be applied to each computer separately

    • Backup has to be performed on each computer separately

    • No centralized server is available to manage and control the access of data.

    2. Client-Server Network

    In a client-server network, the client requests information or services from the server
    and the server provides the requested information or service to the client. Servers
    on a client-server network commonly perform some of the processing work for
    client machines.

    In a client-server network, resources are controlled by a centralized network
    administration. The network administrator implements data backups and security
    measures. The network administrator also controls user access to the server
    resources.

    Note: In a home or small business, a single server can run multiple types of server
    software, it may be necessary for one computer to act as a file server, a web server,
    and an email server. A client computer can also run multiple types of client software.
    There must be client software for every service required. With multiple client software
    installed, a client can connect to multiple servers at the same time.

    Advantages of Client-Server Network

    • Centralization of control: Access, resources and integrity of the data are
      controlled by the dedicated server so that a program or unauthorized client
      cannot damage the system.

    • Scalability: You can increase the capacity of clients and servers separately.
      Any element can be increased (or enhanced) at any time, you can add new
      nodes to the network (clients or servers).

    • Easy maintenance: Distribute the roles and responsibilities to several
      standalone computers, you can replace, repair, upgrade, or even move a server,
      while customers will not be affected by that change (or minimally affect).

    Disadvantage of Client Server Networks

    • There is a reliance on the central server, if it fails, no work can be done

    • A network manager is required and this costs money

    • The server costs money, as does the network operating system

    • Servers are powerful, thus expensive

    • Lots of network traffic.

    Advantages of Client Server Networks over Peer to Peer Networks

    Centralization: Unlike Peer to Peer, where there is no central administration,
      Client Server Networks have a centralized control.

    Proper Management : All the files are stored at the same place. Therefore,
    management of files becomes easy and it is easier to find files.

    Back-up and Recovery possible: As all the data is stored on server it is easy to
      make a back-up of it. Also, in case of some break-down if data is lost, it can be
      recovered easily and efficiently. While in peer to peer network, we have to take
      back-up at every workstation.

    Upgrade and Scalability in Client-server set-up: Changes can be made
      easily by just upgrading the server. Also new resources and systems can be
       added by making necessary changes in server.

    Accessibility: From various platforms in the network, server can be accessed
      remotely.

    Security: Rules defining security and access rights can be defined at the time of
    set-up of server.

    Disadvantages of client server network over the Peer to peer network

    • Congestion in Network: Too many requests from the clients may lead to
      congestion, which rarely takes place in Peer to Peer network. Overload can
      lead to breaking-down of servers. In peer-to-peer, the total bandwidth of the
      network increases as the number of peers increase.

    • Client-Server network is not as robust as a Peer to Peer network and if the
      server fails, the whole network goes down.

    • Cost: It is very expensive to install and manage client server network.

    APPLICATION ACTIVITY 3.6

    Respond the following questions by True or False and justify your answer

    • Peer to Peer network is only implemented by computers which run same
    operating system.

    • In Server-Client network, Server respond to service only requested by the
    Client.

    • Limit number of hosts in the Peer to Peer network are 10 computers.

    • Client requests only the service available on the server in Server-Client
      network.

    • Peer to Peer network is more secure than Server-Client network.

    • There is a dedicated computer in Peer to Peer network.

    • In Client- Server network, both client and server must run the same Operating
     System.

    3.4. Physical Components

     ACTIVITY 3.7

    In the computer lab observe devices that are directly participating in the
    network. Examine the role of each device you have identified.

    3.4.1. Definition of network device

    A network host or a node is a computer or any other device that is directly connected
    to a computer network. A network host may offer information resources, services,
    and applications to users.

    i. Network Interface Card (NIC)

    Network Interface card is a component that allows the computer to communicate
    across a network. This component is frequently built into the motherboard of today’s
    computers, but it can also be a separate card for use in a PCI slot.

    Network Interface cards can be either wired or wireless. However, some cards do
    support both wireless and wired networking

    APPLICATION ACTIVITIES 3.7

    NIC Card installation in a desktop computer:

    Step 1: Shut down your Computer and disconnect it from the power source

    Step 2: Remove the case cover. Then remove the cover of the available slot.

    Step 3: Install NIC in proper slot and secure it

    Step4: Replace the case cover.

    Note: A wireless NIC has an antenna connected to the back of the card or attached
    with a cable so that it can be positioned for the best signal reception. You must
    connect and position the antenna.

         ii. Media Access Control Address

    Media Access Control Address (MAC address) of a device is a unique identifier
    assigned to network interfaces for communications at the data link layer of a
    network segment. MAC address is a physical address of Network Interface Card. In
    other words MAC addresses are linked to the hardware of network adapters. A MAC
    address is given to a network adapter when it is manufactured.
    Example of a MAC address: 00:0a:95:9d:68:16.

    iii. Modem

    A modem is a hardware device that enables a computer to send and receive data
    over a telephone line or a cable or satellite connection. Modem is used to transmit
    digital information via analog systems. The word “modem” is derived from the term
    “Modulator - Demodulator.”

    The essential functions of a modem are:

    • Modulate: an analog carrier signal to carry digital information, it means to
       convert the analog signal to digital signal.

    • Demodulate: a similar signal so as to decode the digital information from
    the analog carrier signal and it means to convert the same signal back to the
    analog signal then transmitted through telephone line.

    They are two types of modems:

    Internal modem which are circuit boards that plug into a computer’s motherboard and
    external modems which are discrete units housed in a separate case. Typically, an external
    modem is connected to the telephone line and the computer via cables or USB.

    APPLICATION ACTIVITY 3.8

    Find the Mac address of your computer

    Step1: Click the Run button in the windows 10 Start Menu

    Step 2: Type cmd in the Open prompt of the Run menu and click OK to launch a
                 command prompt window

    Step 3: Type ipconfig /all at the command prompt to check the network card
                 settings.

    Step4: MAC address is listed by ipconfig under Physical Address

    iv. RJ 45 Connector and Port

    A registered jack (RJ) is a standardized physical network interface for connecting
    telecommunications or data equipment. The physical connectors that registered
    jacks use are mainly of the modular connector and 50-pin miniature ribbon connectortypes

    The RJ45 port is the network port on a computer. This socket has many names. It is
    also known as the Ethernet port, the network adapter, the network jack or the RJ45jack.

    3.5. Network Devices

    ACTIVITY 3.8

    Observe the connection between network devices that make your school network.
    Then answer following questions:

    1. Examine how computers are connected together in order to exchange
        data?

    2. Investigate how data / message is forwarded from the Computer A (as
         source) to Computer B (as destination)?

    3. The equipment used to connect devices within a LAN has evolved from
         hub to bridge to switch. Contrast both devices?

    3.5.1 Hub

    A hub is a network hardware device for connecting multiple devices together and
    making them act as a single network segment.

    Definition:A network segment is a portion of a computer network that is separated from
    the rest of the network by a network device.

    Hub receives message on one port and then send it out to all other ports, this means
    that when hub receives message, the received message is regenerated or duplicated
    and sent to all computers connected to the hub, each computer on the network
    receives the message, if it is not the destination message is destroyed, if it is the
    destination it reads the message.

    Note: Hubs are used less often today because of the effectiveness and low cost of
    switch. Hub do not segment network traffic. When one device sends traffic, the hub
    floods that traffic to all other devices connected to hub. The devices are sharing the
    bandwidth.

    3.5.2 Switches

    Switch filters and segments network traffic by sending messages only to the device to
    which it is sent. This means that when a switch receives a message do not duplicated
    it, it sends it directly to the destination computer. This provides higher dedicated
    bandwidth to each device on the network.

    A switch maintains a switching table, the switching table contains a list of all MAC
    addresses of computers on the network and a list of switch port which are used to
    reach a computer with a given MAC address.
    When message arrives that is destined for a particular MAC address, the switch uses
    the switching table to determine which port to use to reach the MAC address. Then message is forwarded to the destination.

    3.5.3 Bridge

    A network bridge is a computer networking device that creates a single aggregate
    network from multiple communication networks or network segments. This function
    is called network bridging

    Bridges keep a record of all the devices on each segment. A bridge can then filter
    network traffic between LAN segments. This helps reduce the amount of traffic
    between devices

    3.5.4 Access point

    The Access Point is connected to a switch using UTP cable, therefore it can provide
    access to the rest of the network. Instead of providing copper cabling to every
    network host, only the wireless access point is connected to the network with
    copper cabling and spread radio waves to the rest of network.
    The range (radius of coverage) for Access Point indoors is 98.4 ft (30 m) and too
    much greater distances outdoors depending on the technology used.

    APPLICATION ACTIVITY 3.9

    1. Justify why outdoor range is better that indoor range?

    2. Discuss how a switch perform micro-segmentation?

    3. Analysis why Switch is much preferred than a HUB

    4. Examine the difference between Access Point and Bridge?

    5. Identify the purpose of switching table in the switch?

    6. Using the internet search for the diagram representation of hubs,
        switches and bridges in a network

    3.6 Network Transmission Medium

    ACTIVITY 3.9

    Draw a computer network of 10 computers
    This is the physical mean of communication between network computers.
    Data transmission media are the physical materials used to transmit data between
    computers. Packet of data can be transmitted on network as electrical signals
    in electric wire, light signal in fiber optic cables or as electromagnetic waves
    through space.
    There are two main types of data communication media used in network:

    1. Bounded or Guided media: which transmit signals by sending electricity
       or light over a cable wire. Common examples of bounded media are
      twisted cables, Coaxial cables and fiber optic cables.

    2. Unbounded media: which transmit data through the air, radio waves,
    layer or infrared signal and satellite based microwaves, etc.

    3.6.1 Guided transmission media

    A wide variety of networking cables are Coaxial, Fiber optic and twisted-pair
    cables which use electrical signals over copper to transmit data while Fiber-optic
    cables use light signals to transmit data. These cables differ in bandwidth, size, and
    cost.

    It is used by both cable television companies and satellite communication systems
    and it carries data in the form of electrical signals. There are several types of coaxial
    cable:

    • Thicknet or 10BASE5 - used in networks and operated at 10 Mb/s with a
    maximum length of 1640.4 ft. (500 m.)

    Thinnet 10BASE2 - used in networks and operated at 10 Mb/s with a maximum
    length of 607 ft. (185 m.)

          b. Twisted-pair copper cabling

    Twisted-pair is a type of copper cabling used for telephone communications and
    most Ethernet networks. The pair is twisted to provide protection against crosstalk,
    which is the noise generated by adjacent pairs of wires in the cable.
    The use of this cable is limited by two factors:

    a. Attenuation: the strength of signal reduces as the distance increases i.e the
    cables loose signals strength when they exceed their maximum length stated
    in network specification.

    b. Crosstalk: this refers to interference generated by cables when they are too
    close to each other. Signals from one line get mixed with signals from another.

    3.6.2. Types of twisted pair cables

    There are two types of twisted pair cables: unshielded and shielded cables

    a. Unshielded twisted-pair (UTP)

    Unshielded twisted-pair (UTP) cabling is the most common variety of twisted-pair
    cabling.

    UTP cable consists of four pairs of color-coded wires that are twisted together and
    then encased in a flexible plastic sheath that protects from minor physical damage.
    The twisting of wires helps protect against crosstalk. However, UTP does not protect
    against electromagnetic interference (EMI) or radio frequency interference (RFI).
    EMI and RFI can be caused by a variety of sources including electric motors and
    fluorescent lights.

    There are two different wiring schemes called T568A and T568B. Using the T568A
    and T568B wiring schemes, two types of cables can be created: a straight-through
    cable and a crossover cable.

    1. A straight-through cable is the most common cable type. It maps a wire
        to the same pins on both ends of the cable. The order of connections (the
        pin out) for each color is the exact same on both ends.

    Two devices directly connected and using different pins for Transmit and Receive
    are known as unlike devices. They require a straight-through cable to exchange
    data. For example, connecting a PC to a switch requires a straight-through cable.

    2. A crossover cable uses both wiring schemes. T568A on one end of the
    cable and T568B on the other end of the same cable.
    Devices that are directly connected and use the same pins for transmit and receive,
    are known as like devices. They require the use of a crossover cable to exchange
    data. For example, connecting a PC to another PC requires a crossover cable.

    Note: The most used cable standards are below:

    • 100Base-TX: known as Fast Ethernet, it uses category 5, 5E, or 6 UTP cable and
    it wires u to 100 meters long.

    • 1000Base-T means that the speed of the network is up to 1000
    Mbps, baseband signaling is sed, T stands for twisted-pair as UTP cable used

    b. Shielded twisted-pair (STP)

    The STP type similar to UTP cable except that there is a metal foil or braided metal-
    mesh cover that encases each pair of insulated wires. The extra covering in shielded
    twisted pair wiring protect the transmission line from electromagnetic interference
    ( EMI) leaking into or out of cable. However this can make cables quite bulky
     and harder to install.
    The basic difference between UTP and STP is that UTP is a cable with wires that are twisted
    together to reduce noise and crosstalk. On other hand, STP is a twisted pair cable confined
    in foil or mesh shield that guards the cable against electromagnetic interference.

    APPLICATION ACTIVITY 3.10

    Requirements:

    1. Unshielded twisted pair (UTP) patch cable

    2. Modular connector (8P8C plug, aka RJ45)

    3. Crimping tool

    4. Cable tester (optional, but recommended

    Step 1: Strip the cable jacket about 1.5 inch down from the end.

    Step 2: Spread the four pairs of twisted wire apart.

    Step 3: Untwist the wire pairs and neatly align them in the T568B orientation.

    Step 4: Cut the wires as straight as possible, about 0.5 inch above the end of the jacket.

    Step 5: Carefully insert the wires all the way into the modular connector, making sure
                that each wire passes through the appropriate guides inside the connector.

    Step 5: Carefully insert the wires all the way into the modular connector, making sure
                that each wire passes through the appropriate guides inside the connector.

    Step 6: Push the connector inside the crimping tool and squeeze the crimper all the
                way down.

    Step 7: Repeat steps 1-6 for the other end of the cable.

    Step 8: To make sure you›ve successfully terminated each end of the cable, use a cable
                tester to test each pin.

    APPLICATION ACTIVITY 3.11

    Step 1: Open the Network and Sharing Center:

    Step 2: Select the Control Panel from the Start menu.

    Step 3: Select Open Network and Sharing Center and click Network and Sharing Center

    3.6.3 Fiber optic cables

    An optical fiber cable, also known as a fiber optic cable, is an assembly similar to an
    electrical cable, but containing one or more optical fibers that are used to carry light
    signals

    Advantages of fiber optic

    a. Since they transmit light rather than electronic signal, the problem of electrical
        interference is eliminated , therefore they are not affected by radio interference
         or cross talk

    b. They have become the standard for connecting networks between buildings due
         to their immunity the effects of moisture and lighting.

    c. Fiber optic can transmit signal over much longer distance than coaxial cable and
        twisted cables

    d. They can carry information at high rate speed between

    e. The distance can be up to 2000 meters without repeater

    f. Security: it is difficult to tap into optical fiber line. If this is happen it will be
        noticed immediately.

    g. Low transmission loss

    h. Data can be transmitted digitally

    i. They are more resistant to adverse weather conditions.

    3.6.4 Unguided transmission media

    Unguided media transport electromagnetic waves without using a physical
    conductor. This type of communication is often referred to as wireless communication.
    The mediums used in wireless communications are air, vacuum and even water. Air
    is the most commonly used medium.

          a. Wireless Transmission

    Wireless transmission can be categorized into three broad groups namely radio
    waves, microwaves, infrared

          1. Radio waves

    Radio waves are normally omnidirectional. When an antenna transmits radio
    waves, they are propagated in all directions. This means that the sending and
    receiving antennas do not have to be aligned. The omnidirectional characteristics
    of radio waves make them useful for multicasting, in which there is one sender but
    many receivers. Our FM radio stations, cordless phones and televisions are examples
    of multicasting.

         2. Infrared

    Infrared is used in devices such as the mouse, wireless keyboard and printers. Some
    manufacturers provide a special port called the IrDA port that allows a wireless
    keyboard to communicate with a PC.

    Infrared signals have frequencies between 300 GHz to 400 THz. They are used for
    short-range communication. Infrared signals have high frequencies and cannot
    penetrate walls. Due to its short-range communication system, the use of an infrared
    communication system in one room will not be affected by the use of another system
    in the next room. This is why using an infrared TV remote control in our home will
    not interfere with the use of our neighbor’s infrared TV remote control.

    The disadvantages of using infrared

    • Infrared signals cannot be used for long distance communication.

    • Infrared waves can not be used outside of a building because sun’s rays contain
    infrared waves that can interfere with communication.

           3. Bluetooth

    Bluetooth technology is designed to serve as a new way of connecting devices.
    Bluetooth technology has an advantage of being low investment and low energy
    consumption demanding.

    The difference between Bluetooth and infrared is that Bluetooth allows communication
    when there is a barrier or a wall.

    4. Wi-Fi (Wireless Fidelity)

    Wi-Fi (Wireless Fidelity) is a standard that certifies that wireless devices in Wireless
    LAN to work together. It supports IEEE802.11b Ethernet standard.

    Wi-Fi uses radio signals to transmit high speed data over the wireless network, the
    Access Point is used to connect devices and it acts as the central device for Wireless
    LAN. Wireless devices can be: smartphones, PDAs, IPad, laptop and notebook.

    APPLICATION ACTIVITY 3.11
    General steps to connect to a WI-FI network near you
    The following steps run through the general steps that anyone needs to take to get
    connected to the internet via WI-FI. (Do this exercise and discover the corresponding
    windows for every step. What is the meaning of different icons forms that a wireless
    network take?)

    Step 1: Locate yourself in a property or public space that has a wireless router.

    Step 2: Make sure that the device you›re going to use is:

              • Capable of connecting to the internet and

             • Capable of connecting to WI-FI.

    Step 3: Find out the name of the WI-FI network that the router in your location is
               transmitting.

    Step 4: Once you know the name of the WI-FI network, use your chosen device to find
                it.

           3.7. IP Address

           3.7. IP Address

    The fingerprint and addressed letters are ways of identifying and addressing a person.
    A person's fingerprints usually do not change. They provide a way to physically identify
    people. The mailing address of a person can change, as it relates to where the person
    lives or picks up mail. Do network devices have addresses? Justify your answer.

        3.7.1 Understand IP Addresses

    An IP address is an address used in order to uniquely identify a device on a computer
    network.

          IP Versions

    There are two versions of IP addressknown as IP version 4 and IP version 6

          a. IP version 4

    IP version 4 is the common used IP address,

        a.1 Structure of IP address

    • An IP address is simply a series of 32 binary bits. Because it is difficult for human
       to read a binary IP address, the 32 bits are grouped into fout-8-bits bytes called
        octets.

    • When a computer is configured with an IP address it is entered as doted decimal
       number such as 192.168.1.5

    • When a host receives an IP address , it looks at all 32 bits as they are received by
       the NIC

    • Each octet is made up with 8 bits an each bit has a value. The four groups of 8 bits
       have same set of value.

    • Parts of the IP address
     The logical 32 bits IP address is made up two parts which are network part or network
     address and the second one is host address .

     a.2 Classes of IP version 4

    There are five classes of available IP ranges: Class A, Class B, Class C, Class D and Class
    E, while only A, B, and C are commonly used classes D and E are reserved.
    Here is a listing of these addresses:

    Class A

    In class A the first bit of the first byte is always 0

    0xxxxxxx where x stand for any value (either o or 1)

    Minimum: 00000000
    Maximum: 01111111

    The valid range in class A =

    The range of IPs 127.x.x.x is reserved for the loopback or localhost, for example,
    127.0.0.1 is the common loopback address. Range 255.255.255.255broadcasts to

    all hosts on the local network.
    The first byte in class A represent Network address while the three remaining
    represent the host address thus class A=Network. Host-Host-Host

    Class B

    In class B the first bit of first byte is always 1 and the second bit of first byte is always
    0

    10xxxxxx

    Minimum: 10000000=128
    Maximum: 10111111=191

    Valid range[ 128-191]

    The two first byte in class B represent Network address while the two remaining
    represent the host address thus class B=Network-Network-Host-Host

    Class C

    The first bit of first byte is always 1, the second bit of first byte is always 1 and the
    third bit of first byte is always 0 i.e 1100000

    Minimum: 11000000= 192
    Maximum: 11101111= 223
    Valid range: 192-223
    The three first bytes in class C represent Network address while the last byte remaining
    represent the host address thus class C=Network. Network -Network -Host

    a.3 Subnet Masks

    A subnet mask help to know which portion of the address identifies the network
    and which portion of the address identifies the host. Class A, B, and C networks have
    default masks, also known as natural masks, as shown here:

    Class A: 255.0.0.0

    Class B: 255.255.0.0

    Class C: 255.255.255.0

    Devices that are attached to a network have two addresses that are similar to a
    person’s fingerprints and a person’s mailing address. These two types of addresses
    are the Media Access Control (MAC) address and the IP address. The MAC address is
    hard coded onto the network interface card (NIC) by the manufacturer and it does
    not change. The IP address is assigned to a host to the network and may change.

      b. Internet Protocol Version 6 (IPv6)

    IPv6 (Internet Protocol Version 6) also called IPng (Internet Protocol next generation)
    is the newest version of the Internet Protocol reviewed to replace the current version
    of IPv4. IPv6 is designed to allow the Internet to grow steadily, both in terms of the
    number of hosts connected and the total amount of data traffic transmitted.

    IPv6 shows a 128-bit address in eight 16-bitblocks separated by colons

    Example: 3ffe:1900:4545:3:200:f8ff:fe21:67cf.

    FE80:0000:0000:0000:0202:B3FF:FE1E:8329

      b.1 Features of IPv6

    • Supports source and destination addresses that are 128 bits (16 bytes) long.

    • No more NAT (Network Address Translation)

    • Auto-configuration

    • No more private address collisions. Requires IPSec support to provide two
       security headers which can be used separately

    • Those security headers are Authentication Headers(AH) and Encrypting
       security payload(ESP)

    • Uses Flow Label field to identify packet flow for Quality of Service handling by
       router.

    • Allows the host to send fragments packets but not routers.

    • Does not require manual configuration or DHCP.

    • Moves optional data to IPv6 extension headers.

    • Uses Multicast Neighbor Solicitation messages to resolve IP addresses to linklayer
       addresses.

    • Uses Multicast Listener Discovery (MLD) messages to manage membership in
       local subnet groups.

    • Uses ICMPv6 Router Solicitation and Router Advertisement messages to
      determine the IP address of the best default gateway

    Why there is no different classes in IP v6?

    In IPv4 we have class A, B, C,D and E. In IPv6 we have only global prefix and interface
    id

    IP v6 has three types of addresses, which can be categorized by type and scope:

    Unicast addresses: a packet is delivered to one interface.

    Multicast addresses: a packet is delivered to multiple interfaces.

    Anycast addresses:a packet is delivered to the nearest of multiple interfaces (in
    terms of routing distance).

    3.7.2. IP address assignment1. Static IP assignment

     The manual configuration of a host in a network, allows to assign the static IP address
     and the following information has to be specified:

    IP address - identifies the computer on the network

    Subnet mask - is used to identify the network on which the computer is
       connected

    Default gateway - identifies the device that the computer uses to access the
    Internet or another network

    Optional values - such as the preferred Domain Name System (DNS) server
    address and the alternate DNS server address

    Note that host on the same network should have the same Network ID

    APPLICATION ACTIVITY 3.12

    Go through all these steps to assign to your computer a static IP address

    STEP 1: Go to Network Connections.

    STEP 2: Go to the network connection your computer is currently using, then
                 select Properties.

    STEP 3: Go to Internet Protocol Version 4 (IPv4) from the list and click the Properties
                 button
    STEP 4: Choose Use the following IP address option

    NOTE: When assigning a static IP address, make sure to set a value that will not
                conflict with others on your network. You may refer to your router documentation
               for the range of IP address that it assigns to its devices.

    STEP 5: Next to the IP address field, enter the IP address value you want to assign
                  to the computer.

    NOTE: If the DHCP range of your router is from say 192.168.1.100-200, you can use
    any range from 192.168.1.2-99 for example.

    STEP 6: In the Subnet mask field, enter “255.255.255.0.”

    STEP 7: In the Default gateway field, enter the IP address of your router or gateway
                  device.

    NOTE: Usually, the default gateway address for most routers is 192.168.1.1. Again,
    you may refer to your device documentation to determine the correct IP address
    of your router.

    STEP 8: For the Preferred DNS server and Alternate DNS server fields, you can take
                 a look for the exact DNS values that your router is getting from your ISP, which can
                 be usually found by accessing your router’s configuration page.

    STEP 9: Click OK on all windows to save your changes.

    3. Dynamic IP configuration

    A DHCP (Dynamic Host Configuration Protocol) server automatically assigns IP
    address to host. It simplifies the addressing process. DHCP server can automatically
    assign to a host an IP addres, Subnet mask, Default gateway and Optional values,
    such as a DNS server address

    APPLICATION ACTIVITY 3.13

    Go through all the steps to assign an IP address using DHCP

    Step 1: Go to network connections

    Step 2: Select “View network connections”.

    Step 3: Locate the “Network connection” you want to view

    Step 4: After locating connection, right –click on it and select “Properties”

    Step 5: Double-click “Internet Protocol Version (TCP/IPv4)”

    Step 6: Select the followings:

              • Obtain an IP address automatically

              • Obtain DNS server addresses automatically
              • OK

    Step 7: Select “OK” and restart your computer.

    3.7.3 Some common protocols

    A protocol is defined a set of rules and procedures that control communication
    between computers or other network devices on a network.

    a. Internet control message protocol (ICMP)

    Internet Control Message Protocol (ICMP) is used by devices on a network to send
    control and error messages to computers and servers. There are several different
    uses for ICMP, such as announcing network errors, announcing network congestion,
    and troubleshooting.

    b. HTTP (Hypertext Transfer Protocol)

    e.g. http://www.reb.rw/
    http:stands for hypertext transfer protocol used to connect computer to the server.
    It provides a standard web browser to communicate with a server FTP (File Transfer
    Protocol)

    This protocol allows you to transfer files between two computers on internet.

         c. TCP and UDP

    Transmission Control Protocol and User Datagram Protocolare most common
    transport layer both protocols that manage the communication of multiple
    applications. The difference between the two are the specification function that
    each protocol implements.

    d. SMTP (Simple mail Transfer protocol)

    The SMTP stands for Simple mail Transfer protocol is a TCP/IP used in sending and
    receiving e-mails. However, since it is limited in its ability to queue message at the
    receiving end, it is used with one of two other protocols POP or IMAP that let users to
    save messages in server mailbox and download them from the server once needed.

    e. POP (Post Office Protocol)

    Post Office Protocol is a protocol designed to allow single user computer to retrieve
    electronic mail from a POP server via TCP/IP.

    3.7.4 Commands used to verify computer connection on a network

    3.7.4.1 Ping

    The command Ping is commonly used to test connections between computers.
    Ping is a simple but highly useful command-line utility used to determine whether a
    specific IP address is accessible.

    3.7.4.2 ipconfig

    The ipconfig command is used to find out your current local IP address, default
    gateway, TCP/IP settings and more.

    All Ipconfig commands explained:

              i. ipconfig/all: it displays all current IP information for all adapters.

              ii. ipconfig /release: Used to release current IP information and obtain a
                  new IP Address from the DHCP server.

            iii. ipconfig /renew: it is used to renew IP Address if you have it set to

               obtain IP Address automatically.

     3.8. Data and device sharing

       ACTIVITY 3.10(b)

    1. Share a folder with your classmate on your school computer network

    2. Identify how resource are shared on computer network

    3.8.1 Workgroup

    A workgroup is a collection of computers and servers on a LAN that are designed
    to communicate and exchange data with one another. Each individual workstation
    controls its user accounts, security information, and access to data and resources.

    APPLICATION ACTIVITY 3.14

    Go through the steps below in order to create a WorkGroup

    Step 1: Open the Start menu, do a search for HomeGroup and press Enter.

    Step 2: Click Create a HomeGroup.

    Step 3: Click Next.

    Step 4: Choose what to share on the network. By default Windows sets Pictures, Videos,
    Music, and Printers & Devices as Shared. However, the Documents folder is marked as
    not shared.

    Note: The sharing options you choose will only apply to devices connecting with
    different accounts. If you sign-in with the same user account on another computer,
    you will have access to all files regardless of what you chose to share.

    Step 5: Once you've decided what content to share, click Next.

    Step 6: The wizard will complete the setup, and you'll be presented with a HomeGroup
    password, which is needed to allow other computers to access files and printers. Write
    down or click the link to print the password.

    APPLICATION ACTIVITY 3.15

    Go through these steps to add computers to a HomeGroup

    Step 1: Open the Start menu, do a search for HomeGroup and press Enter.

    Step 2: Click the Join now button.

    Note: If you don't see the Join now button, there is something wrong, make sure
    you're connected to the network and restart your computer.

    Step 3: Click Next.

    Step 4: Select the content you want to share on the network by using the drop
    down menu for each folder and click Next.

    Step 5: Enter your HomeGroup password and click Next.

    Note: If you're signed into another computer, but you're using your Microsoft
    Account, then you won't be prompted to enter a password.

    Step 6: Click Finish to complete the task.

    3.8.2 Network Resource Sharing

    First determine which resources will be shared over the network and the type of
    permissions users will have to the resources. Any device which is connected to a
    host /node is called a Network Peripheral in other word network peripheral is any
    device that is indirectly connected to the network. Examples of network peripheral
    are: printer, scanner

    APPLICATION ACTIVITY 3.16

    Go through the steps below to add new folders to shared HomeGroup libraries

    Step 1: Use the Windows key + E keyboard shortcut to open File Explorer.

    Step 2: On the left pane, expand your computer’s libraries on HomeGroup.

    Step 3: Right-click Documents.

    Step 4: Click Properties.

    Step 5: Click Add.

    Step 6: Select the folder you want to share and click Include folder.

    Step 7: Click Apply.

    Step 8: Click OK.

    Application activity 3.17

    Go through these steps to add new folder via Windows network share to your
    HomeGroup

    Step 1: Right-click the folder you want to share.

    Step 2: Select Share with and click the Homegroup (view) option.
    Users can access the newly shared folder by:

    Step 3: Using the Windows key + E keyboard shortcut to open File Explorer.

    Step 4: Clicking Network on the left pane.

    Step 5: Double-clicking the computer name with shared content, and browsing the
                folder location.

    By default, every HomeGroup folder shared on the network are set with read only
    permissions. It has to be this way to prevent accidental deletions and modification to
    your files by other users.

    3.9. Network Topology

    ACTIVITY 3.11

    Draw a Peer-to-peer network and assign each host an IP address. Network must have 1
    switch, 8 computers, one printer which has NIC card and a printer.

    The network topology describes the configuration of network, the physical and
    logical arrangement of nodes that form a network. Network topologies are classified
    as physical, logical and signals topologies.

    Physical topology describes the mapping of network nodes and physical connection
    between them. Signal topology describes the paths which signals take while they
    pass over network that mapping of the paths taken by data as they travel over
    network. A logical topology is the way data signals pass from one device to another.

    There exist different types of network topologies which are Bus topology, Ring
    topology, Star topology, Mesh topology, Tree topology and Hybrid topology,

    3.9.1 BUS Topology

    Bus topology is a network type in which every computer and network device is
    connected to single cable. When it has exactly two endpoints, then it is called Linear
    Bus topology.

    It is the most used and employed in LAN architecture. All devices are connected to a
    central cable, called the bus or backbone. This topology is relatively inexpensive and
    easy to install for small networks.

    Features of Bus Topology

    1. It transmits data only in one direction.

    2. Every device is connected to a single cable

    3.9.2 RING Topology

    It is called ring topology because it forms a ring as each computer is connected to
    another computer, with the last one connected to the first. Exactly two neighbors
    for each device. In a Ring topology each device is connected directly to two other
    devices, one on either side of it, to form a closed loop. This topology is relatively
    expensive and difficult to install, but it offers high bandwidth and can span large
    distances

    A ring topology is a computer network configuration in which computer connections
    create a circular data path. Each networked computer is connected to two others
    like points on a circle.

    In a ring network, data travel from one device to the next until they reach their
    destination. Most ring topologies allow data to travel only in one direction called
    a unidirectional ring network. Others permit data to move in both directions called bidirectional.

    3.9.3 STAR Topology

    In this type of topology all the computers are connected to a single hub or a switch
    through a cable. This hub or switch acts as the central device and all others nodes
    are connected to the central device.

    So, in a Star topology all devices are connected directly to a central computer or
    server. Such networks are relatively easy to install and manage

    Features of Star Topology

          1. Every node has its own dedicated connection to the hub.

          2. Hub acts as a repeater for data flow.

         3. Can be used with twisted pair or coaxial cable.

    3.9.4 MESH Topology

    • It is a point-to-point connection to other nodes or devices. All the network
    nodes are connected to each other. A Mesh topology can be either a full mesh
    or a partial mesh. In the former, each computer is connected directly to each
    of the others.

    Types of Mesh Topology

    1. Partial Mesh Topology: In this topology some of the systems are connected
    in the same fashion as mesh topology but some devices are only connected to
    two or three devices.

    2. Full Mesh Topology: all devices are connected to each other which is very
    expensive but provides the best redundancy as a failure of a single does not
    affect the network connectivity.

    Features of Mesh Topology

    1. Fully connected.

    2. Robust.

    3. Not flexible.

    3.9.5 Tree Topology

    It has a root node and all other nodes are connected to it forming a hierarchy. It is
    also called hierarchical topology. It should at least have three levels of hierarchy.

    Features of Tree Topology

    1. Ideal if workstations are located in groups.

    2. Used in Wide Area Network.

    3.9.6 Hybrid Topology

    Hybrid, as the name suggests, is mixture of two different things. Similarly in this
    type of topology that integrate two or more different topologies to form a resultant
    topology which has good points (as well as weaknesses) of all the constituent
    basic topologies rather than having characteristics of one specific topology. This
    combination of topologies is done according to the requirements of the organization.

    For example, if there exists a ring topology in one office department while there is a bus
    topology in another department, connecting these two will result in hybrid topology.
    However, connecting two similar topologies cannot be termed as Hybrid topology.

    Notice that the cost of technology, network devices, and transmission mediums to
    be used in the computer network has to be considered while choosing the network
    topology to use.

    APPLICATION ACTIVITY 3.18

    Using clear example, compare computer network devices, network peripherals
    and computer peripherals?

    1. In an organization there are 20 computers distributed into different offices
        and all offices share one printer .The managements wants to build a
         computer network that connects all the computers and printer.

         i. Identify a topology to use in this situation

         ii. Draw arrangement of computers using identified topology

    2. Draw a hybrid topology

    Quiz: 1
  • UNIT 4: INTRODUCTION TO DATABASE

    Key Unit Competency: To be able to identify concepts of database and differentiate
    database models

    INTRODUCTORY ACTIVITY

    Observe the following diagram showing the collection of files for the school. Answer
    to the questions below:

    4.1. Definitions of key terms

    Activity 4.1 1.

    1. Interview someone from the administration office at your school who
        is dealing with student’s information on daily basis. In your interview,
        include the following questions:

       a. How do you collect data of students?

       b. What are the data do you need from the student?

       c. Where are you keeping that data?

       d. How do you call the set of all information related to students?

       e. Have you full information about students

        f. With whom else do you share that information?

    2. After you have done the interview, write up findings in the form of report
        to be presented to the class.

           i. Data

    Data is commonly referred to as ‘raw’ data – a collection of text, numbers and
    symbols, images with no meaning. Data therefore has to be processed, or provided
    with a context, before it can have meaning.

         ii. Information

    Information is the result of processing data, usually by computer. This results in
    facts, which enables the processed data to be used in context and have meaning.
    Information is data that has meaning.

    iii. Database

    Database is an organized collection of related data. It is considered to be
    organized because the data is stored in categories that are accessible in a logical
    manner. A database is a collection of one or more relations, where each relation is a
    table made of rows and columns.

    Note: An information system is a combination of computer hardware and software
    that is designed to create, store, process and present information. The heart of all
    information systems is a database.

    In general data management consists of following tasks:
    Data capture, Data classification, Data storage, Data arranging, Data retrieval, Data
    maintenance, Data verification, Data coding, Data editing, Data transcription, Data
    transmission.

    Application Activity 4.1

    Using the following exam results of S5MCE students:

    1. KANEZA has 39/40 in Math, 37/40 in C++, 20/20 in ICT and 15/20 in English,

    2. CYUSA has 40/40 in C++, 35/40 in Math, 18/20 in ICT, and 17/20 in English

    3. KEZA has 35/40 ni Math, 38/40 in C++, 19/20 in ICT and 16/20 in English,

    4. NTWARI has 35/40 in Math, 35/40 in C++, 16/20 in ICT and 15/20 in English,

    5. MUTESI has 37/40 in Math, 37/40 in C++, 20/20 in ICT and 20/20 in English

    Using spreadsheet:

    a. Organize the students’ marks in a table

    b. Calculate total marks

    c. Calculate the Calculate the percentage

    d. Arrange their marks by descending order

    4.2. Different area where database can be applied

    Databases touch all aspects of our lives such as:

    1. Human resources: to track information about employees

    2. Banking: to keep customer information, accounts, and loans, and banking
        transactions.

    3. Airlines: to keep for reservations and schedule information. Airlines were
        among the first to use databases in a geographically distributed manner

    4. Universities: to keep student information, course registrations, and grades.

    5. Credit card transactions: to keep purchases on credit cards and generation
    of monthly statements.

    6. Telecommunication: to keep records of calls made, generating monthly
        bills, maintaining balances on prepaid calling cards, and storing information
        about the communication networks.

    7. Finance: to keep storing information about holdings, sales, and purchases
       of financial instruments such as stocks and bonds.

    8. Manufacturing: to keep management of supply chain and for tracking
       production of items in factories, inventories of items in warehouses / stores,
       and orders for items. etc.

    Application activities 4.2

    1. Research and identify the impact of database in society

    2. Present your findings to the class

    4.3. Database approaches

    Activity 4.2

    Mr. Mugabo is managing a shop in our village. All daily sold products are recorded
    manually in book note so that he can know how much money he got. Sometimes
    he uses to write that the payment is cash or not. However, when it is time to make a
    verification of the whole week so that he can buy new products for the shop, he uses
    to meet serious problems related to calculations, to know how much sold, how much
    remain and who have not reimbursed the depts.

    1. How Mr. Mugabo can improve his shop management?

    2. Identify approaches of database which are replacing manual database
        system;

    3. After that replacement of systems where Mugabo will puts some useless
        hard copy files?

    4.3.1 Traditional File Processing Systems (TFPS) approach

    This is an approach which was used earlier, prior to DBMS. With this approach, users
    had to write their application programs to store data in form of files on the computer
    permanent storage device (Hard Disk). A user must have knowledge of programming
    languages but this is not easy for a common computer user, even an experienced
    programmer would find it difficult to write a program each time a new database was
    to be created. Each application program written by a user had to define and manage
    its own data.

    a. Advantages of the Traditional File Processing

    Compared to manual management of information, the Traditional File
    Processing presents the following advantages:

    Simplicity: the design of file processing is more simple than designing
                        Database

    Efficiency: file processing cost less and can be more speed than Database

    Customization: you can customize file processing more easily and efficiently
      than Database because files are related with the application and it have all the
       data needed for that application.

    b. Disadvantages of Traditional File Processing System

    • Separation and Isolation of Data: In file-based approach, data is stored in
      separate files, hence it is difficult to access it.

    Duplication of Data: Duplication of data means same data being stored more
      than once. This can also be termed as data redundancy.

    Misuse of storage space: Duplication of data leads to misuse of storage space.
      If the storage space is not properly it will have a direct impact on cost. The cost
      will increase.

    Loss of data integrity: Data integrity means that the data contained in the
      database is both accurate and consistent (Data inconsistency means different
      copies of the same data will have different values).

    Data Dependence: In traditional file processing, the structure of data files is
      embedded in the application programs, so any changes to the structure of a
      file may require changing all programs that access this file.

    Security problems: File based approach is not secured because different files
    are stored in different locations.

    Application activity 4.3

    Located in Nyarugenge District, Lycee de Kigali has 50 teachers and there are
    different departments within. There are 3 departments that need information
    about those teachers namely Salaries, Restaurant and Dispensary. The information
    for salaries is represented as follows:

    MUNEZA is from Huye district, Salary is 11000, born on 1/3/1991and his bill is 10000.
    UMUTESI was born on 7/9/1992, in Gisagara district, Salary is 11000 and his bill is 15000
    MUKANTWARI is from Gatsibo district, she was born on 3/2/1990, Salary is 12000, her bill is 12000.
    NYINAWUMUNTU is from Gasabo and born on 3/1/1992 her Salary is 15000 and bill is 11000.
    KABALISA is from Musanze district, born on 3/2/1980, Salary is 13000 and bill is 10000

    Information for Dispensary is:

    MUNEZA from, Huye , Salary is 11000, born on 1/3/1991, bill is 5000.
    UMUTESI born on 7/9/1992, from Gisagara, Salary is 11000, bill is 1000
    MUKANTWARI from Gatsibo born on 3/2/1990 Salary is 12000, bill is 2000
    NYINAWUMUNTU from Gasabo born on 3/1/1992 Salary is 15000, bill is 1000
    KABALISA from Musanze born on 3/2/1980 Salary is 13000, bill is 1200

    In groups do the following:

    a. Analyze how information is organized in 3 departments

    b. Write down your critics about this information management in respective
      departments

    c. What do you propose as a solution to minimize the cost of information
        management at Lycee de Kigali?

    4.3.2 Database Management System (DBMS)

    Database Management system (DBMS) is referred to as a software system that
    is used to store, access, manage, organize, maintain, modify and delete data from
    databases. Some of the most popular software include, Microsoft Access, Oracle,
    Microsoft SQL Server, MySQL

    MySQL is, one of the most popular database management systems used when there
    is a need to have access to information online.

    a. The advantages of database management system

    There are many advantages of database management system.

    1. Reduce data redundancy: Data redundancy refers to the duplication or
       repetition of data. The database system is used to eliminate the problems
        of data redundancy and data inconsistency.

    2. Data integration: Data integrity means that the data contained in the
        database is both accurate and consistent.

    3. Data Independence: Data independence means that programs are isolated
       from changes in the way the data are structured and stored.

    4. Reduce data inconsistency: Actually, data redundancy and data
       inconsistency are inter-related. If data redundancy is controlled, then data
       inconsistency will also be controlled automatically. Data inconsistency
       means different copies of the same data will have different values.

    5. Data sharing: Due to the fact that data is centralized, many different users
       from different locations can share data.

    6. Data recovery after a crash (a break down): DBMS allows to recover data
       after a crash. The crash may depend on power failure or hardware failure.

    7. Concurrent transaction control: A transaction means a collection of
      operations that perform a single action in a database.

    8. Increased Data security and safety: DBMS allows data to be highly
        protected against unauthorized access.

    b. Disadvantages of DBMS

    The disadvantages of the database approach are summarized as follows:

    1. Complexity: The provision of the functionality that is expected of a good
       DBMS makes the DBMS an extremely complex piece of software. Database
      designers, developers, database administrators and end-users must
      understand this functionality to take full advantage of it.
      Failure to understand the system can lead to bad design decisions, which can
      have serious consequences for an organization.

    2. Size: The complexity and breadth of functionality makes the DBMS an
    extremely large piece of software, occupying many megabytes of disk
    space and requiring substantial amounts of memory to run efficiently.

    3. Performance: Typically, a File Based system is written for a specific
    application, such as invoicing. As a result, performance is generally very
    good.

    However, the DBMS is written for general purpose, to cater for many applications
    rather than just one. The effect is that some applications may not run as fast as
    they used to.

    4. Higher impact of a failure: The centralization of resources increases
       the vulnerability of the system. Since all users and applications rely on
       the availability of the DBMS, the failure of any component can bring
       operations to a halt.

    5. Cost of DBMS: The cost of DBMS varies significantly, depending on
        the environment and functionality provided. There is also the regular
        maintenance costs.

    6. Additional Hardware costs: The disk storage requirements for the DBMS
       and the database may necessitate the purchase of additional storage
       space.

    Furthermore, to achieve the required performance it may be necessary to
    purchase a specicalised computer (server), dedicated to running the DBMS.
    The procurement of additional hardware results in further expenditure.

    7. Cost of Conversion: In some situations, the cost of the DBMS and extra
        hardware may be insignificant compared to the cost of converting existing
        applications to run on the new DBMS and hardware.

    This cost also includes the cost of training staff to use these new systems
    and possibly the employment of specialist staff to help with conversion and
    running of the system.

    This cost is one of the main reasons why some organizations feel tied to their

    current systems and cannot switch to modern database technology.

    Application activity 4.4

    1. Compare Database Management System and traditional File processing system
    Check the DBMS existing in computers of the school computer lab. If they are more
    than one, discuss the similarities and differences of them.

    4.4 Database access levels and users

    Activity 4.3

    Activity 4.3

    Observe and interpret the following figure.

    4.4.1. Database access levels

    A major purpose of a database system is to provide users with an abstract view
    of the data. That is, the system hides certain details of how the data are stored
    and maintained. There are three-levels that form the basis of modern database
    architectures:

    The internal level has an internal schema, which describes the physical storage
    structure of the database. The internal schema uses a physical data model and
    describes the complete details of data storage and access paths for the database.
    The conceptual level has a conceptual schema, which describes the structure of
    the whole database for a community of users.

    The conceptual schema hides the details of physical storage structures and
    concentrates on describing entities, data types, relationships, user operations,
    and constraints. Usually, a representational data model is used to describe the

    conceptual schema when a database system is implemented. This implementation
    conceptual schema is often based on a conceptual schema design in a high-level
    data model.

    The external or view level: The external view level is closest to the users. It is
    concerned with the way the data is viewed by individual users. A user can either
    be an application programmer or an end-user. The external level consists of many
    different external views of database. At the view level, computer users see a set of
    application programs that hide details of the data types.

    The purpose of the three-level architecture is to separate the user application and
    the physical database. Different users need different views of the same data.

    For example users should not have to deal directly with the physical database
    storage details. While the database administrator should be able to change the
    database storage structure or storage device without affecting other user’s views.

    4.4.2 Database users

    When considering users of a Database system, there are three broad classes to
    consider:

    a. Database administrator (DBA):

    Responsible for authorizing access to the database, for coordinating and
    monitoring its use, acquiring software and hardware resources, controlling its use
    and monitoring efficiency of operations.

    b. The database designer:

    Responsible to define the content, the structure, the constraints, and functions or
    transactions against the database. They must communicate with the end-users
    and understand their needs.

    c. The end-user:

    End-users, They use the data for queries, reports and some of them update the
    database content.

    Application Activity 4.5

    From the above figure, explain different access level and right form your school
    hierarchy such as headmaster, DOS, teachers, students, visitors.

         a. Assign each user from the hierarchy what is supposed to do. Example:
             Everything happening in your school is hidden from the visitors.

        b. What is responsibility of DBA?

    4.4.3. Data Independence

    Activity 4.4

    The modification of an application used to access a database does not modify the
    database itself.

    In groups, discuss this assertion

    .
    Data Independence: The ability to modify a scheme definition in one level without
    affecting a scheme definition in a higher level is called data independence.
    There are two kinds of data independence:

    a. Logical data independence

    The ability to modify the conceptual scheme without causing application programs
    to be rewritten.
    Immunity of external schemas to changes in the conceptual schema usually done
    when logical structure of database is altered.

    b. Physical data independence

    The ability to modify the internal scheme without having to change the conceptual
    or external schemas. Modifications at this level are usually to improve performance.

    Application activity 4.6

    1. Discuss about logical independence and physical independence

    2. Compare data dependence and data independence in database 4.5.4.
        Data models

    4.4.4. Database models

    Activity 4.5

    Search and summarize found information on Data Models focusing on:

    a. Common data models

    b. Definition of common data models

    A data model is a collection of concepts and rules for the description of the structure
    of the database. Structure of the database means the data types, the constraints
    and the relationships for the description or storage of data respectively.
    The most often used data models arenHierarchical model network model and

    Relational model

        i. Hierarchical Model

    The hierarchical model organizes its data using a tree structure. The root of the
    tree is the parent followed by child nodes. A child node cannot have more than
    one parent, though a parent can have many child nodes.

    ii. Network Model

    In the network model, entities are organized in a graph, in which some entities
    can be accessed through several paths.

    iii. Relational Model

    In this model, data is organized in two-dimensional tables called relations.
    The tables or relation are related to each other.
    A relational database is a collection of relational tables.
    The following is a graphical representation of entities and their relationships in a
    database structure.

    Notice that since more than three decades, the most used database model is the
    Relational models. This justifies the fact that most of the currently used DBMS are
    all relational. They are hence called relational Database Management Systems
    (RDBMS).

    The database systems in their differences and similarities all serve to manage
    databases. The tables bellow present in summary the Database models Time
    frame and description, the Database Models Physical Structure, the Database
    models Structural Changes, the Database models Relationships, the Database
    models Advantages, the Database models Disadvantages, the Database models
    Examples and the Database models Status Today.

    Database models Comparison








    Application Activity 4.7

    In groups, do a research on Relational Database Management Systems. Present the
    report in class using presentation software.

    END OF UNIT ASSESSMENT

    1. What is the purpose of managing information?

    2. Give the difference between File Processing System and Database
         Management System approach.

    3. Discuss data independence and explain its importance in database
       environment.

    4. Discuss the uses of databases in business environment.

  • UNIT 5: DATABASE DESIGN

    INTRODUCTORY ACTIVITY

    Consider the Company AMAHORO Ltd with departments like Accounting and Finance,
    Human Resource and ICT. Each department has its own employees who are each
    identified by Id, First Name, Surname, Salary, telephone number and Address.

    Suppose that this Company uses the file approach to keep information of its employees,
    where each department has its own file to store necessary information. The payroll file
    is managed in Accounting and Finance departments and a record of an employee’s
    salary is described by Employee Id, First name, Surname and Salary Amount.

    Assume that a new column for the date of recruitment is to be added to the payroll and
    there is a request in Accounting and Finance departments to retrieve all the employees’
    details whose salaries are greater than 100,000 FRW. One employee finds that his/her
    first name was not correctly written on the payroll.

    Since each department has own separate file, it is difficulty to the Human Resource
    Manager to access all the files and make any modification any time he/she wants.

    1. Discuss whether the approach described above is well designed?

    2. Describe the difficulties each department may encounter?

    3. Discuss and Suggest the CEO of this Company the best and efficient
       approach to be used for overcoming all difficulties.

    5.1 INTRODUCTION

    Sometimes ago, organizations usually stored information in a way which was with
    many risks of being lost, damaged, corrupted and not well organized. It was kept
    inTraditional File Processing (TFP) which presented many disadvantages.

    Nowadays, well-designed database arises to overcome those problems and saves the
    time in the long run for the user. It is facilitated by a Database Management Systems
    (DBMS). The design of such database presents 3 main levels called “Database design
    levels”. These levels help to make easy the understanding and the management of a
    database. Later on, it will not be very difficult for the software developer to use that
    database.

    ACTIVITY 5.1

    Read the following scenario and give answers to the asked questions

    Your school needs to keep information securely of its teachers, students, combinations
    and courses. Each teacher is characterized by its identity number, first name, second
    name, salary, qualification, address, telephone number and email.
    The Combination is identified by its Id and Name. The student identified by its Id, First
    Name, Surname, Address, School fees, Contact Number, Combination Id, Class and
    Course is identified by the Course Id, Title, Combination,
    From the above,

    1. Discuss the data types for the attributes identifying entity Teacher,
        Combination, Student and Subject.

    2. Describe the relationships between entities: Teacher, Combination,
        Student and Subject?

    5.1.1 The conceptual level

    The conceptual levelis concerned with concept(abstract), an idea of what something
    is or how it works; something formed in the mind; a mental image.

    There exist different models used for the conceptual level to represent all the data
    elements likely to belong to the database but the most used is the Entity- Relationship
    Model (ERM) It uses the main concepts like entities, attributes and relationships.

    An entity represents a real-world object such as an employee or a project and has
    attributes that represent properties such as EmpId, FirstName, Surname, Address
    and Birthdate. A relationship represents an association or a link among entities.

    For example, when an employee works on many projects, a relationship exists
    between the employee and each project.

    If an employee is identified by EmpId, FirstName, Surname, Address and Birthdate
    while a project is identified by its ProjectId and ProjectName, the diagram
    representing the Entity Relationship is the following.
    5.1.2 The logical level

    The logical level makes it possible to create relational structures enabling us to put
    into practice the conceptualization by imagining a relational Database Management
    System (DBMS). It is characterized by clear and sound reasoning. At this level there
    exist different models like network data models and hierarchical data models and
    relational model. Currently the mostly used is the Relational model. In the case of
    database having Employee and Project entities the relational model is represented
    by the following tables.
    5.1.3 Physical level

    The physical level is concerned with how data will be encoded and stored. It
    consists of the practical application (Database Management Systems - DBMS) of
    all the preceding theories by using computers together with its software to create
    a database. It deals with storage and processing performance, volumetric (time &
    space), partitioning and distribution.

    The most known development tools to use are MS Access, MySQL (My Structured
    Query Language), SQL (Structured Query Language) and NoSQL.
    Application Activity 5.1

    Galleries keep information about artists, their identification, their names, birth address,
    age, and art style. For each piece of artwork/product, the artist, the production year, its
    title, its type of art (e.g., painting, filmmaking, photograph, crafts, sculpture, drawings,
    etc), and its price in FRW must be stored. Pieces of artwork are also classified into
    groups of various kinds, for example, Rwandan art, 19th-century Art(old testament,
    the French art,Haloween,etc), works by Pablo Picasso; a given piece may belong to
    more than one group.Each group is described by an id and name.

    Finally, galleries keep information about customers. For each customer, galleries keep
    that person’s unique identification, full name, and address, total amount of FRW spent
    in the gallery, the artists and groups of art that the customers tend to appreciate.

    Draw conceptual, logical and physical levels for the above described database.
    Example: SCHOOLS Database

    • A View for registrar office
    Course info (coursid:string,enrollment:integer)

    • The conceptual schema:
    Students(studid: string, name: string, login:string, age: integer, gpa:real)

    Courses(coursid: string, ccoursname:string, courcredits:integer)

    Enrolled(sstudid:string, coursid:string, grade:string)

    • The physical schema:

    Relations stored as unordered files.

    Index on first column of Students.

    5.2. DATABASE DESIGN STEPS

    Learning Activity 5.2.

    Read the following scenario and give answers to the asked questions
    At Groupe Scolaire Kinazi, the management of students’ information is not
    computerized. The Headteacher is looking for a solution so that the database of
    students can be managed digitally and hence speed up the production of transcripts
    and the search of information when they are requested for. If you are given the task to
    design that database, how are you going to proceed?

    1. Discuss the different steps to use so that you can succeed the
        assignment.

    2. Discuss the financial savings made by the school when using
       computerized application instead of manual system.

    The most important thing to do to start designing a database is to think ahead.
    When a case that needs a database creation is presented, before to switch on the
    computer, it is better to think about the type of information to work with and the
    types of questions that the database should answer, what information needs to
    be stored and what specifically are the links between them. The next phases are
    to verify all requirements specifications, to represent the data with diagram, and
    to plan the database, here are three rules of database design: Rule 1-Plan; Rule
    2-Plan; Rule3-Plan.

    When data is more complex, there are more needs to plan. Even the simplest
    database should be thought through on paper before being created in any tool such
    as Microsoft Access, SQL, MySQL, etc.

    A well-designed database performs well and adapts to future needs by giving users
    access to essential information. Poor planning often results in a database that fails

    to meet overlooked needs.

    In planning the database, regardless of its size and complexity the following basic
    steps are used:

    1. Investigate the information.

    2. Identify the objects.

    3. Model the objects.

    4. Identify the types of information for each object.

    5. Identify the relationships between objects.

    6. Database optimization through normalization.

    7. Data entry and manipulation

    5.2.1. Investigate information

    Before creating a database, there is a need of good understanding of the problem
    that the database is expected to solve. If the database is to replace the traditional
    method, file based approach method, then the existing system will give most of the
    information needed.

    During investing information, there is a need to work with everyone involved in the
    existing system to see what is needed from the new database. Gathering techniques
    include collect copies of customer information, management reports, and any other
    documents that are part of the existing system, because these will be useful in
    designing the database and the interfaces.

    5.2.2. Identifying the important entities and their attributes

    During the process of gathering/investigating information, the key objects or
    entities that will be managed by the database must be identified. The object can be
    a tangible thing, such as a person (for example student, employee, and patient) or a
    product, or it can be a more intangible item, such as a department in an institution,
    a Combination in a school. Each distinct item in the database should have a
    corresponding table for which column titles are attributes of the entity

    5.2.3. Identifying the Relationship Between entities

    One of the strengths of an E-R database is the ability to relate or associate information
    about various items in the database.

    Isolated types of information can be stored separately, but the database can combine
    data when it is required. Identifying the relationship between entities in the design
    process requires looking at the entities, determining how they are logically related,
    and adding relational columns that establish a link from one table to another.

    5.2.4. Modeling the objects

    As the objects in the system and their attributes are identified, they are recorded in
    a way that represents the system visually. They are recorded using Relational model
    and Entity Relational model

    5.2.5. Identifying the types of information for each object

    After identifying the primary objects/entities in the database as candidates for
    tables, the next step is to identify the types of information that must be stored for
    each object.

    These are the columns in the table of the object.

    Fields/columns should be kept simple, the more atomic your fields the more flexible
    will be your database.

    For example, in a database of names and addresses, you would keep each part of
    the person’s name as a separate field.

    The columns in a database table contain a few common types of information:

    Raw data columns

    These columns store tangible pieces of information, such as names.

    Categorical columns

    These columns group the data and store a limited selection of data such as true/
    false, married/single/divorced/widowed, Male/Female, etc.

    Identifier columns

    These columns provide a mechanism to identify each item stored in the database
    table. These columns frequently have an id or number in their name, for example,
    EmployeeId, StudentId, PersonIdNo and InvoiceNumber. The identifier column is the
    primary component.

    Relational or referential columns

    These columns establish a link between information in one entity and related
    information in another entity.

    For example, an entity that tracks sales transactions will generally have a link to the
    customer’s entity so that the complete customer information can be associated with
    the sales transaction.

    5.2.6. Database optimization through normalization

    One of the most important step to consider when designing a database is database
    definition. If tables are not set up properly, it can cause a lot of headaches down
    the road the time of extracting/retrieving required data. Understanding the rules
    of normalization enforces redundancy elimination and inconsistent dependency in
    database designs.

    5.2.7. Data entry and manipulation

    The goal of data entry is to create data that are valid and well organized to assure
    their quality during extraction. Well stored data leads to data consistency.

    Application activity 5.2.

    Discuss the benefits of following database design steps?

    5.3. RELATIONAL MODEL

    Learning Activity 5.3.

    Read the following scenario and give answers to the asked questions
    Suppose that School wants to develop an information system in which student studies
    in one of the combination and learns different subjects. The system will record details
    concerning student, combination and subject.

          1. Which properties would you expect to find in each student object?

          2. Arrange those properties in tabular form of mxn dimension

    5.3.1. Introduction

    The relational data model was introduced by C. F. Codd in 1970. Currently, it is the
    most widely used data model. It describes the world as “a collection of inter-related
    relations (or tables).”

         a. Relation

    A relation, also known as a table or file, is a subset of the Cartesian product of a list
    of domains characterized by a name. You can also think of it this way: an attribute is
    used to define the record and a record contains a set of attributes.

    The steps below outline the logic between a relation and its domains.

    1. Given n domains are denoted by D1, D2 Dn

    2. And r is a relation defined on these domains

    3. hen r C D1×D2×…×Dn

    The following are the key component to know when we are talking about relation:
    Relation, Tuple, Attribute, Cardinality, Degree, Primary key, Domain

    b. Equivalent Database Concepts

    • Relation <=> Table

    • Tuple <=> Row or record

    • Attribute <=> Column or field

    • Cardinality <=> Number of rows

    • Degree <=> Number of columns

    • Primary key <=> Unique identifier

    • Domain <=> Pool of legal values

    c. Table

    Data is stored in rows and columns. Each Row is known as record and the data items
    are known as fields. Tables contain data about one type of item, person or event, for
    example:

    • a table of patients, a table of a student, a table of teacher, a table of books and
    a table of doctor’s appointment

    For a book the fields could include:

      • Title, Author, ISBN, Publication house

    Column

    A database stores pieces of information or facts in an organized way. The principal
    storage units are called columns or fields or attributes. These house the basic
    components of data into which your content can be broken down.

    Records

    Each row represents a group of related data values, such as a customer or an
    employee. A row, or record, is also known as a tuple

    Cell

    The link/intersection between column and record is known as cell. It also needs to
    be available so that they can be reconstituted into their whole form, the basis of all

    databases.

    A simple table below gives us the clearest picture of how records and fields work
    together in a database storage project.

     d. Null value

    In many situations every row and column will contain data, but there cases where it
    makes sense for some columns to not contain a value.
    In our example StudentId cannot be null because it is unique but Sex can be null
    because it is optional field

    e. Degree

    The degree is the number of attributes in a table. In our example above in Figure 5.4
    the degree is 6.

    f. Domain

    A domain is the original sets of atomic values used to model data. A domain is a set
    of acceptable values that a column is allowed to contain.

    For example:

    • The domain of Marital Status has a set of possibilities: Married, Single, Divorced,
        Widowed.

    • The domain of Shift has the set of all possible days: {Monday, Tuesday,
       Wednesday, Thursday, Friday, Saturday and Sunday}.

    • The domain of Salary is the set of all floating-point numbers greater than 0 and
       less than 200,000 FRW.

    • The domain of First Name and Surname is the set of character strings that
    represents names of people.

    g. Datatype

    Each field in a record has its own data type. The data types in the fields can be text,
    alphanumeric, numeric, and Boolean or date/time.

    Table 5.1: Datatype example

    Application Activity 5.3.

    1. Suppose that a hospital wants to develop system which manages
    doctors and patients.

    Patients are treated in a ward by the doctors assigned to them. Each patient will be
    assigned a single doctor. What fields would you expect to find in each record for a
    hospital patient and doctor

    2. The following table describes information about employees, study it
       and answer the following questions :


    a. Using correct terminology, identify and describe all the components of
        employee table.

    b. What is the possible domain for field EmpId?

    c. How many records are shown?

    d. How many attributes are shown?

    e. Explain the datatype for each field.

    5.3.2 Queries in design view

    Learning activity 5.4.

    Microsoft Access is a database management system from Microsoft that deals with
    relational model and it is consisted of the following different views:

    a. Layout view

    b. Backstage view

    c. Design view

    d. Datasheet view

    Which of the view above contains command buttons that execute operations on entire
    databases? Explain its advantages.

    Data in a Microsoft Access database is stored in various interlinked tables. A database
    also has forms for data entry though you could enter data directly in tables and
    queries for manipulating your data and permitting information to be retrieved from
    a table. It also allows filtering so only the required records and fields are seen.

    Steps for creating database in Microsoft Access

    • Open Microsoft Access

    • Click on Blank database in the task pane

    • Name your database file (say Company) and click the Create button to create
       the database.


    Steps for creating a table in Microsoft Access-Design View

    1. Open an created database in access DBMS

    2. Click on create tab from menu bar

    3. In table group click on table design icon

    4. Fill field names, data type and their descriptions

    Data in an Access table is stored in various fields. Those fields have different properties
    such as fieldname, size and data types as shown in the figure below:

    Steps for creating relationship between created tables

    1. Open a created database in access DBMS

    2. Click on database tools tab from menu bar

    3. In relationships group click on relationships icon then the relationships
         panel will be displayed

    4. Select a table name and click on add button

    5. Repeat step 4 to all table you want to use

    6. Click on design tab from menu bar

    7. In tools panel click on edit relationship icon

    8. On opened window click on create new button

    9. Select the table names and their columns that you want to join

    10. Click on ok button

    11. Repeat 8, 9, and 10 to all pair table to be joined

    After creating a table, enter the data. Note that there are various methods to create
    tables in Access, such as by using Table Wizard, Datasheet view or by importing
    tables, but this Unit restricts only to Design view.


    Steps for creating a query using design view-Query by example

    Creation of a query in design view has three rows, one to sort the fields, the other
    to specify whether or not to display a field, and the last to specify some criteria to
    select the records.

    1. Click on Create tab of menu from bar

    2. In queries grout click on query Design icon

    3. Select tables to use then click on Add button

    4. In Query Type group select a query commend to be used, Example Select

    5. In query panel select the table names and field names you want to select
        in different tables

    6. Check in show row ender the select item if you want to display them on
        output at run time

    7. Rename the created query

    8. In Result group of menu bar click on Run icon

    After the above steps you will get a table containing the selected items as shown in
    the examples below:

    Query 1: Company leader wants to display onlyEmpId, Fullname (sorted is ascending
    order) and salary for all employees.

    1. Select EmpId, EmpId, FullName, Salary and check them

    2. Select Sort by Ascending on FullName

    Output:

    Query2: The CEO wants to see only EmpId and FullNames where Salary is less or
    equal to 240000.
    Select EmpId, EmpId , FullName and check them
    Set criteria and uncheck Salary field


    Query 3: The following search condition was entered using a query design view
    (Query by example) grid:

    What will be displayed?
    Output:


    5.3.3 Dynamic queries using parameter

    A parameter is a piece of information you supply to a query right as you run it.

    Creating a parameter query

    Creating a parameter is similar to adding a normal criterion to a query:

    1. Create a select query, and then open the query Design view.

    2. In the Criteria row of the field you want to apply a parameter to, enter the
          text that you want to display in the parameter box, enclosed in square
        brackets.
      For example, [Enter the Doj:]

      3. Repeat step 2 for each field you want to add parameters to.
    When you run the query, the prompt appears without the square brackets.

    Fill in the value you’re looking for, and then click OK.

    Specify parameter data types

    To specify the data type for parameters in a query:

    1. With the query open in Design view, on the Design tab, in the Show/Hide
        group, click Parameters.

    2. In the Query Parameters box, in the Parameter column, enter the prompt
        for each parameter you want to specify a data type for.
        Make sure that each parameter matches the prompt that you used in the Criteria
        row of the query design grid.

    3. In the Data Type column, select the data type for each parameter.


    Application Activity 5.4.

    The database WORLD is composed of one table called WORLDCITIES Figure 5.14.
    which stores information about World Cities. Use it to answer asked questions
    1. The query-design view grid below selects all Cities from America where
    Population is greater than 8 million.


    Figure 5.13 QBE grid to display Name of city located in America having population >8M

    Show what would be the output.

    2. Copy and Complete the query design view grid below to select and
       show Name_of_city where Population is greater than to 13 and Area is
       equal to 1590.



    5.4. ENTITY-RELATIONSHIP MODEL

    5.4.1. Introduction

    Learning Activity 5.5.

    A School needs to store information about Teacher (identified by TeacherId, FirstName,
    Surname, Salary, Qualification, Address, Contact); Combination (identified by
    CombinationId, CombinationName),Student (identified by StudentId, FirstName,
    Surname, Address, Schoolfees, ContactNumber) and Subject (identified by subjectId,
    SubjectTitle).

    Discribe the logical relationships between objects Teacher-Student, Teacher-
    Combination, Student-Combination and Teacher-Subject??

    The entity relationship (ER) data model has existed for over 35 years. It is well suited
    to data modelling for use with databases because it is fairly abstract and is easy to
    discuss and explain. ER models are readily translated to relations. ER models, also
    called an ER schema, are represented by ER diagrams.
    ER modelling is based on two concepts:

    • Entities, defined as tables that hold specific information (data)

    • Relationships, defined as the associations or interactions between entities

    5.4.2. Entity Relationship Diagram

    The ER diagram is used to represent the conceptual database schema. In ER diagram:
    Entity, Attributes and Relationships form the components of ER Diagram and there
    are defined symbols and shapes to represent each one of them.

    1. Entity

    A rectangle represents an entity set.

    2. Relationships between Entities
        A diamond represents a relationship.

    3. Entity Types

    • Entity types ->boxes

    • Weak entity type -> double box


    Entity types are similar to classes; they describe potential objects (entities) that will
    appear in the database. Weak entity types describe dependent entities, entities that
    depend on other entities for identity.

    4. Attribute

    An ellipse represents an attribute (Property).



    5. Link between attribute and entity set

    Lines represent linking of attributes (properties) to entity sets.



    5.4.4. Entities and entity sets

    An entity set is a set of entities of the same type that share the same properties. A
    noun is used to represent an entity set. An entity is an instance of an entity set.

    For example, an entity can be:

    • Concrete (TEACHER or STUDENT)

    • Insubstantial (GRADE)

    • An occurrence (EXAM)

    5.4.5. Attributes

    A characteristic of an entity, for example First name, Last name and Age. An attribute
    is a data item that describes a property of an entity set. Attributes determine, explain,
    or categorize an entity set. Attributes have values, which can be of different data
    types such as numbers, character strings, dates, images, sounds, and so on. In a
    physical model, an attribute is a named column in a table. Each table has a list of
    attributes (or columns).

    The types of attributes are:

    Simple (atomic) attribute – This type of attribute has a single component. It is called
    single-valued attribute. For example, the Gender attribute has a single component
    with two values.

    In the COMPANY database, an example of this would be: Name = {John} ; Age = {23}
    Composite attribute – A composite attribute consists of many components.

    For example, the Name attribute has the components Last name and First name. So
    this would be written as → Name = {KAGABO+Peter}

    Address may consist of Province and District, Number, Avenue. So this would be
    written as → Address = {KG +‘14’ + ‘Av’}



    Single valued attribute – This type of attribute has one value for one entity. For
    example, the Title attribute has a single value for each teacher.

    Multi-valued attribute – A multi-valued attribute has many values for one entity.

    An example of a multivalued attribute from the COMPANY database, as seen in
    Figure below, are the degrees of an employee: BSc, MSc., PhD.

    Derived attribute – A derived attribute has its value computed from another attribute
    or attributes.

    A derived attribute is not a part of a table from a database, but is shown for clarity or
    included for design purposes even though it adds no semantic information; it also
    provides clues for application programmers.

    An example of this can be seen in Figure below. Age can be derived from the attribute
    Birthdate

    In this situation, Birthdate is called a stored attribute, which is physically saved to the
    database.



    Unstable attributes - This type of attribute have values that always change. For
    example, the salary of employee.

    Mandatory attributes - Mandatory attributes must have a value. For example, in
    most businesses that track personal information, Name is required.

    Optional attributes - Optional attributes may have a value or be left null; For
    example, address of employee

    Unique identifier - This type of attribute distinguishes one entity from another.

    For example, in a company, you can distinguish between one employee and another
    using a EmployeeID.

    5.4.6. Keys
    An important constraint on an entity is the key. The key is an attribute or a group
    of attributes whose values can be used to uniquely identify an individual entity in
    an entity set. In the case of Logical Model you use a special approach for unique
    identifier.The equivalent concept for unique identifier within Logical Model is a key.

    A key is a field or a set of fields that has/have a unique value for each record in
    the relation. You need a key to ensure that you do not meet redundancies within a
    relation There are several types of keys each having slightly different characteristics:

    Super key-is defined as a set of attributes within a table that can uniquely identify
    each record within a table. Super Key is a superset of Candidate key.

    Candidate key – A candidate key is an attribute or set of attributes that uniquely
    identifies a record in a relation. A candidate key is unique and minimal.

    It is unique because no two rows in a table may have the same value at any time. It is
    minimal because every column is necessary in order to attain uniqueness.

    From our Company database example, if the entity is Employee(SerialNo,EmpId,
    First Name, Surname, Address, Contact, Birthdate, Salary, Depid), possible candidate
    keys are:

    EmpId,

    • SerialNo

    FirstName and Surname – assuming there is no one else in the company with
    the same full name

    Surname and Depid – assuming two people with the same Surname don’t
    work in the same

    Department

    Composite keys – these keys have multiple attributes.
    Using the example from the candidate key section, possible composite keys are:

    • First Name and Surname

    • Surname and Depid

    Primary key – A primary key is one of the candidate keys from a relation. Every
    relation must have a primary key. A primary key shall be at least: - Stable. The value
    of a primary key must not change or become null throughout the life of the entity.

    The primary key is indicated in the ER model by underlining the attribute.

    For example, consider an employee record; using the Age field as the primary key
    would not be appropriate because the value of the primary key must not change
    over time.

    It should be Minimal. The primary key should be composed of the minimum number
    of fields to ensure the occurrences are unique.

    In this case Employee (EmpId, First Name, Surname, Address, Contact, Birthdate,
    Salary, Depid), EmpId is primary key

    Secondary key

    A secondary key is an attribute used strictly for retrieval purposes (can be composite),
    for example: Phone and Surname.
    Alternate key – An alternate key is any candidate key that is not chosen to be the

    primary key. It may become the primary key if the selected primary key is not
    appropriate.

    Simple keys – these keys have a single attribute.

    Foreignkeys – these keys exist usually when there are two or more relations. An attribute
    from one relation has to exist in the other(s) relation. A foreign key is a field (or
    fields) that points to the primary key of another table. The purpose of the foreign key
    is to ensure referential integrity of the data. In other words, only values that are supposed
    to appear in the database are permitted
    In the Company database example below, Depid is the foreign key
    (EmpId, First Name, Surname, Address, Contact, Birthdate, Salary, Depid)

    Attributes and Keys

    • Key attributes must be unique for each entity

    • Keys are used to identify particular entities

    • Partial keys are only partially unique used for weak entity types



    Entity Types and Attributes

    All regular entity types must have a key attribute or set of key attributes, Weak entity
    types must have partial keys, Weak entities get part of their key (and part of their
    identity) from some related entity.


    Nulls

    A null is a special symbol, independent of data type, which means either unknown
    or inapplicable. It does not mean zero or blank.

    Features of null include:

    • No data entry

    • Not permitted in the primary key

    • Should be avoided in other attributes

    • It can represent

    an unknown attribute value

    1. a known, but missing, attribute value

    2. a “not applicable” condition

    Example of null

    Employee Salary table

    In this case commission can be left null

    Relationship sets

    A relationship set is a set of relationships between two or more sets of entities, and
    are regularly represented using a verb.

    A relationship is an instance of a relationship set and establishes an association
    between entities that are related. These relationships represent something important
    in the model. Example: an employee works on a project.

    A relationship set always exists between two entity sets (or one entity set relating
    to itself ). You need to read a relationship set in double sense, from one entity set to
    the other.

    Relationships representation

    Relationships => diamonds
    Identifying relationship => double diamond

    Relationships indicate a meaningful connection between two entity types,
    Relationships may have attributes, but they cannot have key attributes. Identifying
    relationships connect a weak entity type to some other entity type indicates where
    the weak entity gets a key to complete its own partial key

    5.4.7. Degree of a relationship

    The degree of a relationship refers to the number of associated entities. The degree of
    a relationship can broadly be classified into unary, binary, and ternary relationship.

    5.4.7.1. Unary Relationship


    The unary relationship is known as recursive relationship.
    In the unary relationship the number of associated entities is one. An entity is related
    to itself is known as recursive relation.
    An example is shown by the following figure:
    Roles and Recursive Relations

    When an entity set appears in more than one relationship, it is useful to add labels to
    the connecting lines. These labels are called roles.
    In this example, labels “Husband” and “wife” are referred to as roles.
    5.4.7.2 Binary Relationship

    In a binary relationship, two entities are involved. Consider the example where each
    staff will be assigned to a particular department. Here the two entities are STAFF and
    DEPARTMENT.


    5.4.7.3. Ternary Relationship

    In a ternary relationship, three entities are simultaneously involved. Ternary
    relationships are required when binary relationships are not sufficient to accurately
    describe the semantics of an association among three entities.

    Example

    Consider the example of employee assigned a project.
    Here we are considering three entities EMPLOYEE, PROJECT, and LOCATION. The
    relationship is “assigned-to.” Many employees will be assigned to one project hence
    it is an example of one-to-many relationship.

    5.4.7.4. Quaternary Relationships

    Quaternary relationships involve four entities. The example of quaternary relationship
    is “A professor teaches a course to students using slides.” Here the four entities are
    PROFESSOR, SLIDES, COURSE, and STUDENT.
    The relationships between the entities are “Teaches.

    The degree of relationship, which determines how many instances of an entity relate
    to a single instance of another entity is called Cardinality.

    5.4.8. Classifications or types of Relationships

    Based on cardinality, the different types of relationships that can exist between
    entities are:

    5.4.8.1. One-to one (1:1)

    A single instance of an entity can relate to only one instance of the other entity.It
    is the relationship of one entity to only one other entity, and vice versa. It should
    be rare in any relational database design. In fact, it could indicate that two entities
    actually belong in the same table. An example from our Company database is one
    employee is associated with one spouse, and one spouse is associated with one
    employee.

    Other Examples:

    • A person can have only one passport.

    • The relationship between the President and the country is an example of oneto-
       one relationship. For a particular country at a given time, there will be only
       one President. In general, a country will not have more than one President at
       a given time hence the relationship between the country and the President is
       an example of one-to-one relationship.
    5.4.8.2. One-to-many (1: M)

    An instance of one entity can relate to multiple instance of another instance.

    The relationship that associates one record of entity A to more than one record of
    entity B is called one-to-many relationship.

    Example of one-to-many relationship is a country having states.

    For one country there can be more than one state hence it is an example of oneto-
    many relationship. Another example of one-to-many relationship is parent–child
    relationship. For one parent there can be more than one child. Hence it is an example
    of one-to-many relationship.

    For Example,

    • A class has many students.

    • The relationship between EMPLOYEE and DEPARTMENT is an example of
    many-to-one relationship. There may be many EMPLOYEES working in one
    DEPARTMENT. Hence relationship between EMPLOYEE and DEPARTMENT is
    many-to-one relationship.

    5.4.8.3. Many-to-One Relationship Type (M: 1)

    The relationship between EMPLOYEE and DEPARTMENT is an example of many-to-one
    relationship. There may be many EMPLOYEES working in one DEPARTMENT. Hence
    relationship between EMPLOYEE and DEPARTMENT is many-to-one relationship


    5.4.8.4. Many-to-many (M: M):

    Multiple instances of an entity can relate to multiple instances of another entity.
    For our company database. The relationship between employee and department
    is many-to-many relationship.

    Other examples are:

    • A customer can purchase more than one book.

    • The relationship between TEACHER entity and STUDENT entity is an example
      of many-to-many relationship. Many one teacher teaches many students and
      one student is taught by many teachers.
      Employee and project, many employees can work on many projects


    Participation and Cardinality

    Participation and cardinality define constraints on relationships; Participation
    indicates whether an entity is required to take part in a relationship, Cardinality ratios
    and structural constraints place limits on the number of entities that may participate
    in a relationship.

    Participation Constraints

    • Total participation → double or thick line indicates required participation

    • Partial participation →thin line indicates optional participation


    Participation Constraint

    Arrowheads can be used to indicate an upper bound of 1 for participation

    Cardinality Ratios: a cardinality ratios specify the maximum number of relationship
    instances that an entity may participate in.

    Cardinality Ratios: a cardinality ratios specify the maximum number of relationship
    instances that an entity may participate in.



    Structural Constraints

    Structural constraints specify the minimum and maximum number of relationship
    instances that an entity may participate in.


    An employee must work for exactly 1 department. A department must have at least
    4 employees.

    Participation and Cardinality

    There’s generally numerous ways to express a relationship constraint.


    Equivalent Notations

    An employee can manage at most one department.
    A department must have exactly one manager.

    Equivalent Notations

    • An employee must work for exactly one department.

    • A department must have at least one employee.



    Application Activity 5.5

    Given an ER diagrams below

    Write the degree, cardinality, participation and Constraints of each relationship in
    ER diagram

    Write the names of all: weak entities, composite attributes, multivalued attributes,
    composite keys and Partial Key Attribute, derivative attribute, identity relationship.



    Relationships representation

    1. Consider a database used to record information about the marks that
    students get in the different exams of different subject studying in Math-
    Computer Science-Economics combination.

    STUDENT entity is described by StudentId, StudentName and School; SUBJECT_
    STUDYING is identified by SSId, SSName, SSClass and SSRoom and EXAM entity is
    described by EId, EName, ETime and ERoom.

    Construct an E-R diagram that models STUDENT, SUBJECT_STUDYING and EXAM
    as entities that uses ternary relationship.

    5.5. Database optimization through normalization

    Learning Activity 5.6.

    Let consider the database with table CUSTOMER identified by CustomerName,
    Address, TelephoneNumber, CreditLimit, ItemOrdered,Quantity and Price.
    This can easily be implemented in a relational database as follow:


    However, a customer may order several items and each customer in the
    database may order a different number of items. This situation makes it difficult
    to implement the data in a relational database, since we do not know how many
    order entries to allow.

    1. How many order entries our database design would allow every
    customer?

    2. Is this structure simple?

    3. If this database structure is complex, identify the anomalies it has and suggest
        the solution to the database designer to make it simple.

    5.5.1. Introduction

    Another method for designing a relational database is to use a process commonly
    known as normalisation. The goal is to generate a set of relation schemas that
    allows us to store information without unnecessary redundancy, yet also allows
    us to retrieve information easily. The approach is to design schemas that are in an
    appropriate normal form. Therefore, normalisation is a part of the database design
    process. Normalisation is a series of steps designed to remove repeating groups
    and unwanted functional dependencies. Normalisation is a design technique for
    constructing a set of table designs from a list of data items. . It is also used to avoid
    insertion, deletion and updating anomalies. Therefore it used to improve on existing
    table designs.

    5.5.2. Normal Forms

    Normalization theory defines six normal forms (NF). Each normal form involves a set
    of dependency properties that a schema must satisfy and each normal form gives
    guarantees about the presence and/or absence of update anomalies. To correct
    update anomalies in a database, you must convert tables to various types of normal
    forms.

    The most common normal forms are First Normal Form (1NF), Second Normal Form
    (2NF), Third Normal Form(3NF) and Fourth Normal Form(4NF).

    a. First Normal Form

    A relation (table) that contains a repeating group (multiple entries for a single record)
    is called unnormalised relation. Removing repeating groups is the starting point in
    the quest to create tables that are as free of problems as possible. The conversion
    to first normal form (lNF) requires splitting the data into two groups. Tables without
    repeating group are said to 1NF.

    A relation is in first normal form if and only if the domain of each attribute contains
    only atomic (indivisible) values, and the value of each attribute contains only a single
    value from that domain

    Example:

    A database has been designed to store data about sellers and the products they
    have sold.
    The following facts help to define the structure of the database:

    • each seller works in a particular shop

    • each seller has a unique Surname

    • each shop has one or more sellers

    • each product which is sold is manufactured by one company only

    • each seller can sell any of the products

    • the number of products that each seller has sold is recorded


    This table is not in 1NF because:

    1. SHOPSALES table has repeated group of attributes

    (ProductName, Manufacturer)

    (ProductName, NumberofProducts),

    (NumberofProducts, Manufacturer)

    2. each seller has a number of products

    3. SurName and ShopName would need to be repeated for each record

    The following table is in 1NF because it does not contain repeating groups


    b. Second Normal Form (2NF)

    For the second normal form, the relation must first be in 1NF. The relation is
    automatically in 2NF if, and only if, the Primary Key comprises a single attribute.

    To move to 2NF, a table must first be in 1NF.

    The database is changed to the following design:

    SELLER (SurName, ShopName)

    PRODUCTSSOLD (SurName, ProductName, NumberofProducts, Manufacturer)



    Table SELLER is in Second Normal Form because attribute ShopName depends on
    primary key SurName; the same on PRODUCTSSOLD where NumberofProducts
    and Manufacture attributes depends on composite primary key SurName,
    ProductName. The link between these two tables is: primary key of SELLER table is
    FirstName, links to FirstName in PRODUCTSSOLD table, FirstName in SalesProducts
    table is foreign key

    c. Third Normal Form (3NF)

    To be in third normal form, the relation must be in second normal form. Also
    all transitive dependencies must be removed; a non-key attribute may not be
    functionally dependent on another non-key attribute.

    In our case on table PRODUCTSSOLD, Manufacturer attribute is dependent on
    ProductName, which is not the primary key of the PRODUCTSSOLD table therefore
    there is no key dependency.

    Process for 3NF:

    1. Eliminate all dependent attributes in transitive relationship(s) from each of
        the tables that have transitive relationship.

    2. Create new table(s) with removed dependency.

    3. Check new table(s) and modified table(s) to make sure that each table
       does not contain contains inappropriate dependencies.

    See the three new tables below.

    SELLERS (SurName, Shop)

    PRODUCTSSOLD (SurName, ProductName, NumberofProducts)

    PRODUCTS (ProductName, Manufacturer)


    Table: PRODUCTSSOLDM1


    d. Boyce-Codd Normal Form (BCNF)

    When a table has more than one candidate key, anomalies may result even though
    the relation is in 3NF. Boyce-Codd normal form is a special case of 3NF. A relation
    is in BCNF if, and only if, every determinant is a candidate key.

    Example

    Consider the following table STUDENT
    The following facts help to define the structure of the database:

    1. Each Student may major in several Combinations.

    2. For each Combination, a given Student has only one ClassTeacher.

    3. Each Combination has several Advisors.

    4. Each ClassTeacher advises only one Combination.

    5. Each ClassTeacher advises several Students in one Combination.

    The functional dependencies for this table are:

    1. StudentId, Combination→ClassTeacher

    2. ClassTeacher →Combination

    Anomalies for this table include:

    • Delete→Student deletes ClassTeacher inforamtion

    • Insert→a new ClassTeacher needs a Student

    • Update →inconsistencies or contradiction

    Because no single attribute which is a candidate key, primary key can be

    StudentId, Combination, Student_id,ClassTeacher.

    To reduce STUDENT table to BCNF, there is creation of two tables:

    • STUDENTTEACHER (Studentid, ClassTeacher)

    • TEACHERCOMBINATION(ClassTeacher, Combinationr)

    e. Fourth Normal Form (4NF)

    Fourth normal form eliminates independent many to one relationships between
    columns.
    A relation is in Fourth Normal Form:

    • A relation must first be in Boyce-Codd Normal Form.
    • Given relation may not contain more than one multivalued attribute.

    The multi valued dependency X→Y holds in a relation R if whenever there is two
    tuples of R that same in all the attributes of X, then we can swap their Y components
    and get two new tuples that are also in R.


    Primary key→{StudentId , Subject , Clubs}

    • Many StudentId have same Subject.

    • Many StudentId have same Clubs.

    Thus violates 4NF.
    To convert to 4NF, the table STUDENTCLUB is changed to the following design:
    STUDENTSUBJECT {StudentId, Subject}



    Is this normalised table? If not,
    convert it to 1NF, 2NF and 3NF.

    2. Consider the following table SUBJECT that contains multivalued
        dependency thus it is in 3NF, use it to answer asked questions


    i. Identify functional dependencies exist in this tabale above

    ii. Eliminate those dependencies.

    END UNIT ASSESSMENT

    Question 1.

    The database below is composed of two tables. Use it to answer asked questions


    i. What is primary key for each table and give reasons.

    ii. Identify the foreign key in the BOOKS table.

    iii. Identify the candidate keys in both tables.

    iv. Identify the relationship between BORROWERS and BOOKS tables
        and draw the E-R model.

    v. Does the BOOKS table exhibit referential integrity? Why or why not?

    Question 2.

    Write an ER diagram for Banking System. Assume your own entities (minimum 5),
    attributes and relation. Mention the cardinality ratio.

    Question 3.

    A picture gallery owner has decided to set up a database to keep information
    about the pictures he has for sale. The database table, PICTURE, will contain the
    following fields:

    PictureTitle; PictureArtist; PictureDescription; CatalogueNumber; PictureSize (in
    MB); PicturePrice; ArrivedDate (date picture arrived at gallery); Status(whether
    picture is already sold)


    PictureTitle; PictureArtist; PictureDescription; CatalogueNumber; PictureSize (in MB);
    PicturePrice; ArrivedDate (date picture arrived at gallery); Status(whether picture is
    already sold)

    i. State what data type you would choose for each field.

    ii. State which field you would choose for the primary key.

    iii. Complete the query-by-example grid below to select and show the

    CatalogueNumber, PictureTitle and PicturePrice of all unsold pictures
     by the artist ‘GATOTO’.




  • UNIT 6: POINTERS AND STRUCTURE IN C++

    INTRODUCTORY ACTIVITY

    The Groupe Scolaire Nderonziza which is located in District Gakenke, Sector Amahoro,
    Cell Bwiza and Village Rumuri is a twelve-year basic education school. It has 4 blocks
    of 3 equal classrooms each. Each classroom has 10 meters of length and can contain a
    maximum of 30 students. Each classroom is labelled with a name made of the name of
    block and the name of the level as showed in the next figure.

    After analyzing this figure, respond to the following questions.

    1. Describe the role of each label of a classroom?

    2. Discuss the way of knowing the content of each classroom?

    3. If you are asked to describe the entity student, what are its attributes?

    4. In C++ Programming language, how are you going to declare the variable
        student?

    5. Suppose that at the beginning of the next year there are 60 new students
         who are enrolled at that school in S4. If the schools need to maintain the
         quality of teaching and learning by keeping a maximum of 30 students
         per classroom, what will happen for the 30 students who don’t have
         space in S4?

    6. In C++ programming language, how to create that space?

    6.1 Pointers in C++

    ACTIVITY 6.1

    1. The student called Kayiranga of Computer Science Senior 5 has a class
         work and wants to borrow a C++ programming language book and a
        computer from his classmate Iradukunda. Kayiranga needs to use those
        materials which are on the desk of Iradukunda to submit the work on
        time while Iradukunda was absent.
       Discuss

    a. What could Kayiranga do if he takes those materials without informing
    Iradukunda?

    b. What could happen to Iradukunda when he comes back?

    3. On The list, the students of Senior 5 are arranged in ascending order
        according to their names. From one name of a student, how to reach the
        next student?

    a. How to get to the student number 5 while you are on student number 2?

    b. How to get to the student number 8 while you are on student number 15?

    6.1.1 Definition of Pointers

    A pointer is a variable which contains the address in memory of another variable.
    There can be a pointer to any variable type. The unary or monadic operator & gives
    the ``address of a variable’’. The indirection or dereference operator * gives the
    ``contents of an object pointed to by a pointer’’.

    C++ gives the power to manipulate the data in the computer’s memory directly. The
    space in the memory can be assigned and de-assigned. This is done using pointer
    variables. Pointer variables are variables that points to a specific address in the
    memory pointed to by another variable.

    6.1.2 Dereference operators

    The asterisk sign (*) in the cout statements is called the dereference operator. If the
    dereference operator is used, the “value pointed by” a pointer is got.

    The statement:

    cout << *ptr; means to print the content of the memory space pointed by ptr.

    6.1.3 Reference operator

    The ampersand sign (&) is called the reference operator. If the reference operator
    is used, it will get the “address of” a variable. The ptr = &x; means that it stores the
    address of the variable x in the pointer ptr.

    6.1.4 Declaring pointer variables

    A pointer is declared by using the * (asterisk) operator before an identifier. It is
    necessary to initialize the pointer before you can use a pointer in for instance a cout
    statement. Due to the ability of a pointer to directly refer to the value that it points
    to, it becomes necessary to specify in its declaration which data type a pointer is
    going to point to. It is not the same thing to point to a char as to point to an int or a
    float.

    Pointer declaration Syntax:

    data_type *pt_name;

    Where data_type is the data type of the value that the pointer is intended to point to.

    The following are three declarations of pointers and all of them are pointers and will
    occupy the same amount of space in memory:

    6.1.5 Initialization of Pointer Variable

    Pointers can be initialized to point to specific locations at the very moment they are
    defined,You need to initialize a pointer by assigning it a valid address.

    6.1.6 Graphical representation of pointers for referencing memory allocation.

    Consider the following,

    int jim,tom,*blaise;
    jim = 10;
    tom= jim;
    blaise = &jim;

    The following is graphical representation of the value contained in each variable
    after the execution of this, are shown in the following diagram:

    First, we have assigned the value 10 to jim (a variable
    whose address in memory we have assumed to be 501).
    The second statement copied to tom the content of variable jim which is 10. the
    third statement copies to blaise not the value contained in jim but a reference to it (its
    address, which we have assumed to be 501). The reason is that in this third assignment
    operation we have preceded the identifier jim with the reference operator (&), so
    we were no longer referring to the value of jim but to its reference (its address in
    memory).

    1.1.7 Incrementing a Pointer

    Incrementing a pointer is generally used in array because we have contiguous
    memory in array and we know the contents of next memory location. Incrementing
    pointer variable depends upon data type of the Pointer variable
    Three Rules should be used to increment pointer.

    Address + 1 = Address

    Address++ = Address

    ++Address = Address

    The following program increments the variable pointer to access each succeeding
     element of the array –

    #include <iostream>

    6.1.8 Decrementing a Pointer

    As shown in example below, the program decrementing a pointer, which decreases
    its value by the number of bytes of its data type

    #include <iostream>
    using namespace std;
    const int MAX = 3;

    int main () {
    int var[MAX] = {10, 100, 200};
    int *ptr;
    // let us have address of the last element in pointer.
    ptr = &var[MAX-1];
    for (int i = MAX; i > 0; i--) {
    cout << “Address of var[“ << i << “] = “;
    cout << ptr << endl;
    cout << “Value of var[“ << i << “] = “;
    cout << *ptr << endl;
    // point to the previous location
    ptr--;
    }
    getchar();
    return 0;
    }

    6.1.9 Arrays and pointers

    The name of an array is a pointer to the first element in the array.

    int a[10];

    int *aptr = a;

    a // is equivalent to &a[0]

    aptr = a // is equivalent to aptr = &a[0];

    aptr+5 // is equivalent to &a[5]

    *(aptr+5)

    // is equivalent to a[5]

    Exemple :
    #include <iostream>

    using namespace std;

    int main()
    {
    float arr[10];

    float *ptr;

    cout << “Displaying address using arrays: “ << endl;

    for (int i = 0; i < 10; ++i)
    {
    cout << “&arr[“ << i << “] = “ << &arr[i] << endl;
    }
    // ptr = &arr[0]

    ptr = arr;

    cout<<”\n Displaying address using pointers: “<< endl;

    for (int i = 0; i < 10; ++i)

    { cout << “ptr + “ << i << “ = “<< ptr + i << endl;
    }
    getchar();

    return 0;}

    Different pointer ptr is used for displaying the address of array elements arr. Pointers
    are the variables that hold address. Not only can pointers store address of a single
    variable, it can also store address of cells of an array.

    6.1.10 Comparison of pointers

    Pointers may be compared by using relational operators, such as ==, <, and >.

    The following program incrementing the variable pointer so long as the address to
    which it points is either less than or equal to the address of the last element of the
    array, which is &var[MAX - 1].

    6.1.11 Subtracting pointers

    Differencing means subtracting two Pointers. Subtraction gives the Total number of
    objects between them. Subtraction indicates “How apart the two Pointers are?”

    Example:

    #include<iostream>

    using namespace std;

    int main()

    {
    int num , *ptr1 ,*ptr2 ;

    ptr1 = &num ;

    ptr2 = ptr1 + 2 ;

    cout << “ the difference of two pointers is: “ << ptr2 - ptr1 << endl;

    getchar ();

    return 0;

    }

    6.1.12 Assignment of pointers

    In pointer assignment, the pointer is associated with a target. If the target is undefined
    or disassociated, the pointer acquires the same status as the target

    pointer-object => target ,

    6.1.13 Pointers and function in C++

    A function pointer is a variable that stores the address of a function that can later be
    called through that function pointer.

    Example:

    #include<iostream>

    using namespace std;

    void swapping (int *ptr_a, int *ptr_b)

    Activity1:

    a. What is the pointer in C++

    b. Explain the use of Address Operator (&) and operator (*).

    Activity 2:

    Given the following declarations, which of the following statements are not valid?

    int i;

    int *pi;

    double d;

    double *pd;

    a. i=&pi; b.*pi=&i; c. pd=&pi; d. pd=i; e. pi=&i;

    Activity3:

    What is the error in each of the following expressions?

    6.2. Memory allocation

    ACTIVITY 6.2

    Public bonded warehouse known as MAGERWA (Magazin Generaux Rwandais) is a
    Rwandan company where all goods from abroad are stored before being distributed in
    the country. When an importer brings his/her goods to MAGERWA, he/she is allocated
    a space where to put those goods for checking and is charged the space per square
    meter (m2) per day. When he/she withdraws his/her goods from MAGERWA, the
    occupied space is given to other customers for use.

    Discuss: What would happen to the MAGERWA store if all customers failed to withdraw
    their goods on time?

    6.2.1 Definition

    Memory allocation means reserving memory for specific purposes. It is a process
    by which computer programs and services are assigned with physical or virtual
    memory space, the process of reserving a partial or complete portion of computer
    memory for the execution of programs and processes. Once the program has
    finished its operation, the memory is released and allocated to another program
    or merged within the primary memory. Programs and services are assigned with a
    specific memory as per their requirements when they are executed

    6.2.2 Dynamic memory allocation in C++

    Up to this level, all memories needed in programs were determined before the
    program execution by defining the variables where it is reserved for. But there may
    be cases where the memory needed in a program can only be determined during
    runtime.

    When a memory is dynamically allocated, the operating system is asked to reserve
    some of that memory for that program’s use. If it can fulfill this request, it will return
    the address of that memory to the current application. From that point forward, the
    application can use this memory as it wishes. When the application is done with
    the memory, it can return the memory back to the operating system to be given to
    another program. This allows to obtain more memory when required and release it
    when not necessary.

    C++ integrates the operators new and delete for allocating dynamic memory. With
    the functions malloc, calloc, realloc and free are available in C++ and can also be
    used to allocate and deallocate dynamic memory.

    A. Operators:

    i. Operator new and new[]

    Dynamic memory is allocated using operator new. New is followed by a data type
    specifier and, if a sequence of more than one element is required, the number of
    these are within brackets []. It returns a pointer to the beginning of the new block of
    memory allocated.

    Its syntax is:
    pointer = new type
    pointer = new type [number_of_elements]

    The first expression is used to allocate memory to contain one single element of
    type type. The second one is used to allocate a block (an array) of elements of type
    type, where number_of_elements is an integer value representing the amount of
    these. For example:

    int * mem;
    mem= new int[6];

    There is a substantial difference between declaring a normal array and allocating
    dynamic memory for a block of memory using new. The most important
    difference is that the size of a regular array needs to be a constant expression,
    and thus its size has to be determined at the moment of designing the program,
    before it is run, whereas the dynamic memory allocation performed by new
    allows to assign memory during runtime using any variable value as size.
    The dynamic memory requested by a program is allocated by the system from the
    memory heap (unused memory of the program). However, computer memory is a
    limited resource, and it can be exhausted. Therefore, there are no guarantees that
    all requests to allocate memory using operator new are going to be granted by the
    system.

    ii. Operators delete and delete[]

    In most cases, memory allocated dynamically is only needed during specific periods
    of time within a program; once it is no longer needed, it can be freed so that the
    memory becomes available again for other requests of dynamic memory. This is the
    purpose of operator delete, whose syntax is:

    delete pointer;

    delete[] pointer;

    The first statement releases the memory of a single element allocated using new,
    and the second one releases the memory allocated for arrays of elements using

    new and a size in brackets ([]).
    The value passed as argument to delete shall be either a pointer to a memory block
    previously allocated with new, or a null pointer (in the case of a null pointer, delete
    produces no effect).

    b. Functions

             Malloc (): void* malloc (size_t size);

    Allocate memory block. Allocates requested size of bytes of memory and returns
    a pointer to the beginning of the block (first byte of allocated space). Simply pass
    in how big you want your memory to be (in bytes), and you get a pointer to that
    memory back. The content of the newly allocated block of memory is not initialized,
    remaining with indeterminate values. If it fails it returns NULL. It is routine used to
    allocate a single block of memory.

                   Calloc (): void* calloc (size_t num, size_t size);

    Allocate and zero-initialize array. Allocates space for an array element, initializes to
    zero and then returns a pointer to memory. The calloc() takes two integer arguments
    and multiplied together to specify how much memory to allocate. This is routine
    used to allocate arrays of memory.

                  Free (): void free (void* ptr);

    Deallocate memory block (the previously allocated space). A block of memory
    previously allocated by a call to malloc, calloc or realloc is deallocated, making it
    available again for further allocations.

                  Realloc (): void* realloc (void* ptr, size_t size);

    Reallocate memory block, Change the size of previously allocated space pointed to
    by ptr. The function may move the memory block to a new location (whose address
    is returned by the function).

    Notice: In the above program:

    Malloc () function dynamically allocates initial value of the size maximum 10
    characters (e.g the size of HelloWord has 9 characters) otherwise it returns null and
    is copied to str variable which has address in memory.

    Realloc() function :reallocate the content of str concatenating with .com and change
    the size from 10 to 15 but it keeps the existing address which is 0x22ff44.

    Free(): the memory size of (10) characters that has been reallocated with realloc () is
    released after using free() because it is no longer needed.

    6.2.3 Static memory (or Compile Time) allocation

    The memory for your variables is allocated when the program starts, the size is fixed
    when the program is created

    Statically allocated variables have their storage allocated and initialized before main
    starts running and are not deallocated until main has terminated. Statically allocated

    local variables are not re-initialized on every call to the function in which they are
    declared. A statically allocated variable thus has the occasionally useful property of
    maintaining its value even when none of the functions that access the variable are
    active.

    6.2.4 Advantages of dynamic memory allocation over static memory allocation

    An advantage is that the program determines how much memory it needs at run time
    and allocate exactly the right amount of storage and released when it’s no longer needed.

    • Dynamic Memory Allocation

         * Memory allocated “on the fly” during run time

         * Dynamically allocated space usually placed in a program segment known
          as the heap or the free store

        * Exact amount of space or number of items does not have to be known by
          the compiler in advance.

        * For dynamic memory allocation, pointers are crucial

    • Static (or Compile Time) Allocation

        * Memory for named variables is allocated by the compiler

        * Exact size and type of storage must be known at compile time

        * For standard array declarations, this is why the size has to be constant

    Application activity 6.2

    Activity 1:

    Explain the memory allocation and compare dynamic memory over static memory
    allocation.

    6.3 C++ Structures

    ACTIVITY 6.3

    The company Urukundo Ltd specialized in production of Milk Powder has a group
    of 20 employees and its management is not computerized. Each employee is
    identified by the attributes first name, second name, age, degree and salary. The
    programmer of that company wants to write a program in C++ programming
    language that will allow to constitute a file containing the information of each
    employee.

    1. What should be the data type of each attribute?

    2. Is it easy to enter the value of each attribute one by one? What should
        be the solution?

    3. If employee is considered as a single entity, how will it be declared in
        the program?

    6.3.1 Introduction to C++ structure

    Structure is a collection of variables of different data types under a single name.
    These data elements, known as members, can have different types. To store some
    information about a student: Name, Age and student ID. Creation of different
    variables name, Age, ID needed to store this information separately.

    6.3.2 How to declare a structure in C++ programming?

    The struct keyword defines a structure type followed by an identifier (name of the
    structure).

    Data structures can be declared in C++ using the following syntax:

    struct type_name {

    member_type1 member_name1;

    member_type2 member_name2;

    member_type3 member_name3;

    . } object_names;

    Where:

    type_name is a name for the structure type, object_name can be a set of valid
    identifiers for objects that have the type of this structure. Within braces {}, there is a
    list with the data members, each one is specified with a type and a valid identifier as
    its name.

    6.3.3 Initializing structure in C++ programming

    Just like any variable, we can specify the initial value of a structure at the time of its
    definition.

    Example of Initialization of structure:

    6.3.4 Calculate Memory consumption by structure

    To generate the program below, padding must be added to the structs to satisfy this
    alignment criteria. It creates two structs; both contain 3 values of the same types
    and of the same name. It then prints out the sizes of these structs (in bytes).

    Note: Output may vary depending on the systems

    The C++ standard defines that struct members must be arranged in memory in the
    same order that they are defined within their access level. Different types must have
    certain memory alignment requirements; long (on a 64-bit platform) uses 8 bytes of
    memory and must start at a memory location divisible by 8 char, on the other hand,
    only uses 1 byte of memory and can start at any memory address.

    6.3.5 Accessing members of a structure

    We need to specify both the structure name (name of the variable) and the member
    name when accessing information stored in a structure. There are two types of
    operators used for accessing members of a structure:

    1. Member operator (.) or Dot Operator

    structure_variable_name.member_name

    For Example:
    We can access the member age of employee structure variable employee_one as:
    struct employee
    {
    char name[50];

    int age;

    float salary;

    char department[30];

    } employee_one = {“paul”, 25, 150000.5, “ICT”};

    int age = employee_one.age;

    2. Structure pointer operator (->) or Arrow Operator (->)

    Structure pointer operator or Arrow operator is used to access members of structure
    using pointer variable. When we have pointer to a structure variable, then we can
    access member variable by using pointer variable followed by an arrow operator
    and then the name of the member variable.

    structure_pointer->member_name;

    For example:

    6.3.6 Global use of structure

    As defined, a structure is a compound data type that contains different members
    of different types, structs are simpler to be managed by the programmer and the
    compiler,a better example of using a global variable, and a situation where global
    variables are completely necessary, is when passing a structure to a function. In
    that case, you must declare the structure as global so that all functions can access
    variables of that structure type.

    6.3.7 Pointer to structure

    Just like other variables we can use pointers to access information stored in a
    structure. Structures can also be pointed by pointers and store pointers. The rules
    are the same as for any fundamental data type. The pointer must be declared as a
    pointer to the structure.

    6.3.8 Nesting structure

    Structures can be nested within other structures in C++ programming. Structures
    can also be nested so that a valid element of a structure can also be another structure.
    When a structure contains another structure, it is called nested structure. For
    example, we have two structures named Address and Student. To make Address
    nested to Student, we have to define Address structure before and outside Student
    structure and create an object of Address structure inside Student structure.

    Syntax for structure within structure or nested structure

    struct structure1
    {
    - - - - - - - - - -
    - - - - - - - - - -
    };
    struct structure2
    {
    - - - - - - - - - -
    - - - - - - - - - -
    struct structure1 obj;
    };

    Example:




    6.3.9 Array of structure

    Arrays of structure are good for storing information of a single entity. By declaring
    an array of structures, you specify the number of reserved structures inside array
    brackets when you declare the structure variable.

    Example:

    Consider learning activity 6.3 example:

    #include <iostream>

    #include <conio.h>

    #include<stdio.h>

    #include<string.h>

    using namespace std;

    struct Employee

    Application activity 6.3

    1.
    a. Define a structure in C++
    b. Given a structure definition,
    struct Employee {
    string emName;
    string emSex;
    string emAddress;
    }; Employee Emp;
    A member of the structure can be accessed by which one of the following statements?:

                       a. Employee.emName;

                        b. Emp.emName;

                         c. Emp->emName;

    2. Store Information of students and Display It Using Structure by creating an
    array having 4 elements of structure student. Each of the element stores the
    information of a student.

    For example, st[0] stores the information of the first student, st[1] for the
    second and so on.

    3. What is the output of the following program?

    END UNIT ASSESSMENT


  • UNIT 7: OBJECT ORIENTED PROGRAMMING IN C++

    Key Unit Competence:

    To be able to explain common concepts of Object Oriented Programming (OOP) and
    implement them in C++.

    INTRODUCTORY ACTIVITY

    Human beings can be grouped into males and females. Each of them has two legs, two
    hands, two eyes, a nose, a heart, and so on. There are body parts that are common to
    males and females, but there are specific body parts for males and not for Females, and
    vice versa.
    Both Males and Females perform some common functions like walking, eating, seeing,
    talking, hearing etc. But there are some specific functions for each group of Human
    Beings.

    After reading the above, do the following.

    1. Categorize human beings into two main groups

    2. What are the body parts that all human beings have in common?

    3. List the parts that are specific for females and males.

    4. What all human beings can do in common? What are specific functions
         only for each gender?

    5. Based on database concepts, write down the properties of the entities
       human being, male and female. Design on papers a Diagram of entities
       found in the above scenario.

    6. Add to each entity the functions raised in question 3, 4 and 5. Which
        entity depends on the other one?

    7. Do you need to repeat the properties and functions of human being
        entity to male entity and to female entity? Explain your answer.

    8. After considering the question above, design a diagram of the new
        entities.

    9. Discuss your answer

    7.1. Introduction to Object Oriented Programming (OOP)

    Activity 7.1

    Compare the programming paradigms that you have learnt so far.

    1. Which one can help you to create a program for the “Introductory
        activity”?

    2. Search and write an essay on the concepts and principles of that new
        programming paradigm.

    7.1.1 Definition of Object Oriented Programming(oop)

    Object-oriented programming (OOP) refers to a type of computer programming (software
    design) in which programmers define not only the data type of a data structure, but also
    the types of operations (functions) that can be applied to the data structure.
    In this way, the data structure becomes an object that includes both data and functions. In
    addition, programmers can create relationships between one object and another.

    7.1.2 Basic Concepts of Object Oriented Programming

    The main concepts and principles used within Object Oriented Programming are:

    • Objects

    • Classes

    • Abstraction

    • Encapsulation

    • Inheritance

    • Polymorphism

    • Exception Handling

    Definitions of OOP concepts

                    a. Object

    An objects is the basic unit of OOP. It is an instance of class, which has data members and
    use various member functions to perform tasks.

                   b. Class

    A class is basically a blueprint of an object. It can also be defined as user defined data type
    but it also contains functions in it. It declares and defines what data variables the object will
    have and what operations can be performed on the class’s object.

                    c. Encapsulation

    Encapsulation means that the internal representation of an object is generally hidden from
    view outside of the object’s definition. Typically, only the object’s own methods can directly
    inspect or manipulate its fields. It can also be said data binding. Encapsulation is all about
    binding the data variables and functions together in class.

                   d. Abstraction

    Data abstraction and encapsulation are closely tied together, because a simple definition
    of data abstraction is the development of classes, objects, types in terms of their interfaces
    and functionality, instead of their implementation details. Abstraction denotes a model, a
    view, or some other focused representation for an actual item.
    In C++, classes can provide methods to the outside world to access & use the data variables,
    keeping the variables hidden from direct access, or classes can even declare everything
    accessible to everyone, or maybe just to the classes inheriting it. This can be done using
    access specifiers.

                e. Inheritance

    Inheritance as the key feature of Object-Oriented Programming is a way to reuse code
    of existing objects, or to establish a subtype from an existing object, or both, depending
    upon programming language support. In classical inheritance where objects are defined
    by classes, classes can inherit attributes and behavior from pre-existing classes called base
    classes, super classes, parent classes or ancestor classes. The resulting classes are known as
    derived classes, subclasses or child classes. The relationships of classes through inheritance
    gives rise to a hierarchy.
    The derived class inherits all the features from the base class and can have additional
    features of its own.

                 f. Polymorphism

    It is a feature, which lets programmers create functions with same name but different
    arguments, which will perform different actions. That means, functions with same name, but
    functioning in different ways. Or, it also allows users to redefine a function and provide it with
    a completely new definition.

                g. Exception Handling

    Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced
    at runtime (during the running of the program).

    Graphically the principles of Object Oriented Paradigm can be represented like this.


    Advantages of Object Oriented Programming

    One of the principal advantages of Object-Oriented Programming techniques over procedural
    programming techniques is that they enable programmers to create modules that do
    not need to be changed when a new type of object is added. A programmer can simply
    create a new object that inherits many of its features from existing objects. This makes
    object-oriented programs easier to modify.
    So, Object Oriented Programming has great advantages over other programming styles.

    1. Code Reuse and Recycling: Objects created for Object Oriented
       Programming can easily be reused in other programs.

    2. Data Redundancy: Inheritance is the good feature for data redundancy. If
        you need a same functionality in multiple classes, you can write a common
        class for the same functionality and inherit that class to sub class.

    3. Data hiding: Implementation details are hidden from other modules and
        other modules has a clearly defined interface.

    4. Design Benefits: Large programs are very difficult to write. Object
       Oriented Programming force designers to go through an extensive
       planning phase, which makes for better designs with less flaws. In
      addition, once a program reaches a certain size, Object Oriented Programs
      are actually easier to program than non-Object Oriented ones.

    5. Software Maintenance: An Object Oriented Program is much easier to
       modify and maintain than a non-Object Oriented Program. So although a
      lot of work is spent before the program is written, less work is needed to
     maintain it over time.

    Application Activity 7.1

    1. The following are the principles of OOP: Object, Class, Encapsulation,
        inheritance and Polymorphism. Explain them one by one.

    2. What are the advantages of OOP?

    3. Name the features that are added to standard C++.

    7.2 Class definition in C++

    Activity 7.2

    Observe the C++ program below and answer the following questions:

    #include<iostream>

    Using namespace std;

    class Test

    {

    int a;

    float b;

    public:

    void number1()

    { a = 2;

    return a;}

    float number2()

    {
    b = 3.5;
    return b;
    }
    };

    int main()
    {

    test m1;

    cout <<”First number is: “<< m1.number1()<<’\n’;

    cout <<”Second number is: “<< m1.number2()<<’\n’;

    return0;

    }

    From the program above, answer the following questions:

    1. What are new key words in the above program?

    2. Describe the structure of the part starting with the word class.

    3. List the data members contained in the class “Test”

    4. What are the functions found in that class?

    5. What is the role of the variable m1?

    7.2.1 Definition of a class

    A class is defined in C++ using keyword class followed by the name of class.
    The body of class is defined inside the curly brackets and terminated by a semicolon at the
    end.

    7.2.2 Syntax



    Here, the class is named Test. This class has two data members: data_1 and data_2 and two
    member functions: function_1() and function_2().
    A Class is an expanded concept of data structures, like data structures, it can contain data
    members, but it can also contain functions as members. Where class_name is a valid identifier
    for the class, object_names is an optional list of names for objects of this class. The body
    of the declaration can contain members, which can either be data or function declarations,
    and optionally access specifiers.

    Classes have the same format as plain data structures, except that they can also include
    functions and have these new things called access specifiers (data hiding). An access specifier
    is one of the following three keywords: private, public or protected.
    Access specifiers are used to identify access rights for the data and member functions of the
    class. There are three main types of access specifiers in C++ programming language:

    A private member within a class denotes that only members of the same class
      have accessibility. The private member is inaccessible from outside the class.

    Public members are accessible from outside the class.

    A protected access specifier is a stage between private and public access. If
    member functions defined in a class are protected, they cannot be accessed
    from outside the class but can be accessed from the derived class.
    When defining access specifiers, the programmer must use the keywords: private, public or
    protected when needed, followed by a colon and then define the data and member functions
    under it.

    class AddNumbers

    {
    private:
    int x,y;
    public:
    void sum()
    {
    ………
    ………
    }
    };

    In the code above, the member x and y are defined as private access specifiers. The member
    function sum is defined as a public access specifier.
    General structure for defining a class is:

    Generally, in class, all members (data) would be declared as private and the member functions
    would be declared as public. If no access specifiers are identified for members of a
    class, the members are defaulted to private access (Private is the default access level for
    specifiers).

    class AddNumbers
    {
    int a,b;

    public:

    void sum()
    {
    ………
    ………
    }
    };

    In this example, for members a and b of the class AddNumbers there are no access specifiers
    identified. This means that by default a and b are private members of class AddNumbers.
    You can have functions inside a class. These functions can be either under public or private,
    and their syntaxes are the same. For example, if you have a function to display information
    of an account called display, and other classes should be able to access that function, the
    following line would be added under the public area:

    void display (accountno);
    And use the following syntax to implement the function:
    void BankAccount::display (int accountno)
    {
    ……………;
    ………….;
    }

    The computer accesses an object through the use of one of the object’s methods. The
    method performs some action to the data in the object and returns this value to the

    computer. Classes of objects can also be further grouped into hierarchies, in which objects
    of one class can inherit methods from another class. The structure provided in objectoriented
    languages makes them very useful for complicated programming tasks.
    7.2.3 Defining member functions inside or outside the class definition
    Member functions of a class can be defined either inside or outside the class definition.
    In both cases, the function body remains the same, however, the function header is
    different.

    7.2.3 .I Inside the Class

    A member function of a class can be defined inside the class. However, when a member
    function is defined inside the class, the class name and the scope resolution operator are
    not specified in the function header. Moreover, the member functions defined inside a class
    definition are by default inline functions.
    To understand the concept of defining a member function inside a class, consider this example.

    In this example, the member function putdata() is defined inside the class book. Hence,
    putdata()is by default an inline function.
    Note that the functions defined outside the class can be explicitly made inline by prefixing
    the keyword inline before the return type of the function in the function header. For example,
    consider the definition of the function getdata().
    inline void student ::getdata ()
    {
    body of the function
    }

    7.2.3.2 Outside the Class

    Defining a member function outside a class requires the function declaration (function prototype)
    to be provided inside the class definition. The member function is declared inside
    the class like a normal function. This declaration informs the compiler that the function is a
    member of the class and that it has been defined outside the class. After a member function
    is declared inside the class, it must be defined (outside the class) in the program.

    The definition of member function outside the class differs from normal function definition,
    as the function name in the function header is preceded by the class name and the scope
    resolution operator (: smile. The scope resolution operator informs the compiler what class the
    member belongs to.

    Here is the syntax for defining a member function outside the class:

    Return_type class_name :: function_name (parameter_list)
    {
    // This is the body of the function
    }

    To understand the concept of defining a member function outside a class, consider this
      example.

    Example

     Let us re-write the program which converts the degree from Fahrenheit to Celsius and displays
     the corresponding degrees on the screen. By creating the method outside the class,
     we have:

    Note that the member functions of the class can access all the data members and other
    member functions of the same class (private, public or protected) directly by using their
    names. In addition, different classes can use the same function name.

    Application Activity 7.2

    The below piece of code is for class declaration, analyze it and answer the following questions:

    7.3 Object in C++

    Activity 7.3

    Your District wants to create a program that will help to know its primary and secondary
    schools. Create the class “school” with the following attributes and functions:
    Decide on the types of attributes

    a. Attributes:

         1. Name of the school

         2. Code of the school

        3. Number of student in your school

        4. Number of teachers

        5. reading the attributes

        6. printing the attributes

    B (i) Write a program in C++ that reads and prints the list of schools available in your
        District.

    (ii) complete the table below with the following list:

         1. school

         2. School name

         3. Code of the school

        4. Combinations

        5. Number of students

        6. Number of teachers

         7. Read_school ()

         8. Print_school()

    The first characteristic of an object language is to place at your disposal the objects.
    An object can be regarded as an additional structure of information, a type of super-variable.
    Indeed, we know that a variable is a place in primary memory, characterized by an address
    – a name - and a type (integer, double, character, Boolean, etc).

    In a variable, we can store one and only one information.
    Even if an indexed variable is used - a table - the various memory spaces thus defined will
    store all obligatorily information of the same type.

    7.3.1 Definition:

    An object is an instantiation of a class. In terms of variables, a class would be the type, and
    an object would be the variable. So, an object is a group of variables of various types. It
    thus usually gathers tens of very different information from/to each other within the same
    structure, thus making this information easier to handle. By analogy with equation of Wirth,
    we could say that the equation of the Object Oriented Programming (OOP) is: methods+-
    data=objects

    With the difference of what occurs with a table, the various variables of the same object
    are not indicated by an index, but by a name which is proper for them. In fact, these names
    which characterize the various variables within an object are called properties of the object.
    As consequence, any property of object obeys strictly the rules which apply to the variables
    in any language (type, size, rules of assignment…).
    It will be also said that several objects which have the same properties are of the same type,
    or for better explanation, of the same class.

    Example

    let us say that you want to make a program which will record or process the data on the
    books in a library or bookshop, take an object of everyday usage: “A book”.
    The properties of a book are:
    its size (number of the pages), the name of the author, date of publication, printing company,
    its price, its name (title), if a person can borrow it or not, etc.
    You can easily find the type of each one of these properties:

    • The title and the name of author are the properties of the character type.

    • The size (a number of pages) and the price are the properties of the numerical
    type.
    The situation “if one can borrow it from the library or not” is a Boolean property.

    7.3.2 Creating single object

    When a class is defined, only the specifications for the object is defined, the memory or
    storage is not allocated. To use the data and access functions defined in the class, you need
    to create objects.

    7.3.2.1 Syntax to define Object in C++

    className objectVariableName;
    You can create objects of Test class (defined in above example) as follows:

    Here, two objects o1 and o2 of Test class are created.
    In the above class Test, data1 and data2 are data members and function1() and function2()
    are member functions

    Example: Class and Object

    Number: 12
    Enter data: 23.3
    You entered 23.3
    In this program, two data members data1 and data2 and two memberfunctions insertIntegerData()
    and insertFloatData() are defined under Test class.
    Two objects o1 and o2 of the same class are declared.
    The insertIntegerData() function is called for the o1 object using:
    o1.insertIntegerData(12);
    This sets the value of data1 for object o1 to 12.
    Then, the insertFloatData() function for object o2 is called and the return value from the
    function is stored in variable secondDataOfObject2 using:
    secondDataOfObject2 = o2.insertFloatData();
    In this program, data2 of o1 and data1 of o2 are not used and contains garbage value.

    7.3.2.2 Creating array of objects


    7.3.3. Passing object to function

    As it is known, we can pass (give) any type of arguments within the member function which
    can have any numbers of arguments. In C++ programming language, it is also possible to
    pass an object as an argument within the member function of class.
    This is useful, when we want to initialize all data members of an object with another object,
    we can pass objects and assign the values of supplied object to the current object. For complex
    or large projects, we need to use objects as an argument or parameter.
    Syntax:

  • UNIT8: Introduction to Visual basic

    KeyUnitCompetency.

    To be able to describe a Visual Basic Integrated Development (VB-IDE) and write a program in Visual Basic.

    INTRODUCTORY ACTIVITY

    Read the bellow scenario:
    ABC hotel provides different services to its customers such as business center, room services, restaurant and others. For the room services, front desk office receives clients and information is collected as shown below:

    Observe the above picture and answer the following questions:

    1. What do you think of the above figure?

    2. Explain why ABC hotel needs to collect data of each client

    3. Investigate why the figure hold these words such :Add new ,Display and Exit

    4. Which programming language would use to design the above figure?

    5. Can you try to design the above figure?

    In programming, the above scenario requires specific programming language that enables us to enter data using forms and save the data in database to receive them whether is a need. This unit will enable to build a simple desktop application for a real life situation.

    8.1. Understanding Visual Basic.

    LEARNING ACTIVITY. 8.1

    1. Click on start button, All programs, Microsoft Visual basic 6.0, Microsoft visual basic 6.0. What is the name of the window that has opened?

    2. Make double click on standard EXE. What do you observe?

    3. Differentiate desktop and web applications.

    8.1.0. General introduction

    VISUAL BASIC is a high level and Event-driven Programming Language which evolved from the earlier Desk Opening System (DOS) version called BASIC. (BASIC means: Beginners’ All-purpose Symbolic Instruction Code). Visual basic for DOS and Visual Basic for Windows were introduced in 1991 and
    evolved through the years to give Visual basic 3.0(in 1993), Visual basic 4.0 (in 1995) Visual basic 5.0 (in 1996) and now we use Visual basic 6.0 version released in 1998.

    Visual basic 6.0 has the following advantages:

    • It is easier for the user to minimize code writing.

    • The user will become more familiar with visual approach for other visual languages.

    • It provides Input box and Output box as interactive windows with user.

    • It is very easy program language compare with other.

    8.1.1. Definition of terms

    d. Graphical User Interface.

    A graphical user interface (GUI) is an interface through which a user interacts with electronic devices such as computers, hand-held devices and other appliances. GUI representations are manipulated by a pointing device such as a mouse, trackball, stylus, or a finger on a touch screen.

    The need for GUI became apparent because the first human/computer text interface was through keyboard text creation by what is called a prompt (or DOS prompt). Commands were typed on a keyboard at the DOS prompt to initiate responses from a computer. The use of these commands and the need for exact spelling made this interface difficult to use and inefficient.

    A GUI uses a combination of technologies and devices to provide a platform that user can interact with, for the tasks of gathering and producing information. Graphical user interface (GUI) is different from command line interface (CLI) or command language interpreter as command line interface (CLI) enables users to type commands in a terminal or console window to interact with an operating system. Users respond to a visual prompt by typing a command on a specified line (MLI), and receive a response back from the system. Users type a command or series of commands for each task they want to perform.

    e. Desktop application

    A desktop application is a computer program that runs locally on a computer device, such as desktop or laptop computer, in contrast to a web application, which is delivered to a local device over the Internet through browser from a remote server. Different user environments can impact whether a desktop or a web application is the best solution for your needs.

    Difference between desktop and web applications.

    Desktop applications

    • They must be developed for and installed on a particular operating system.

    • Have strict hardware requirements that must be met to ensure that they function correctly.

    • Updates to the applications must be applied by the user directly to their installation, and may require hardware upgrades or other changes in order to work.

    Web applications

    • A web application is any computer program that performs a specific function by using a web browser.

    • The user accesses the application using the web browser and works with resources available over the internet, including storage and CPU processing power.

    • This approach allows for “thin clients” (machines with limited hardware capabilities) to provide access to complex applications delivered from a centralized infrastructure.

    f. Event oriented programming.

    Event oriented programming is a paradigm in which the flow of program is determined by events, such as user actions (mouse clicks, key presses), sensor outputs or messages from other programs is common used in graphical user interfaces and other applications like Web applications, JavaScript, C#.
    Other types of programming paradigm are: C, C++
    • Procedural programming used by Basic, Fortran and COBAL
    • Declarative programming used by Prolog

    Event oriented programming using Visual Basic

    Visual Basic is Event oriented programming because of the following

    • The programmer needs to write code that performs some tasks in response to certain events.

    • Has events that occur by mouse clicking and moving or keyboard stokes (Some of the events are load, click, double click, drag and drop, pressing the keys and more.)

    • Focus on the use of Graphical User Interface.

    • The events usually comply but not limited to the user’s inputs.

    8.1.2. The Features of Visual Basic

    Visual Basic has the following features:

    1. Data Access Features: this allows programmers to develop database front end applications and server side components for most popular database formats including MS SQL and other Databases.

    2. Active X Technologies: that allows programmers to use the functionality provided by other applications, such as MS Office and other windows applications.

    3. Internet capabilities make it easy to provide access to documents and applications across internet server applications.

    4. Your finished application is a true executable (.exe) file that uses a visual Basic Virtual Machine that you can freely distribute.

    8.1.3 Standard EXE Visual Basic Application

    Using Visual Basic one can develop one of these main projects as indicated in the
    screen below:
    1. Standard Exe project is a typical application in which can use the database
    manipulation.

    A standard exe application is one that is created using Standard EXE project. It is the most widely used Project type using VB6. Standard EXE application is normally the most widely used among the available Project types in Visual Basic. Stand-alone

    programs have an .EXE file extension. A standard EXE application is normally used
    when you want to develop a stand-alone application. Examples include calculators,
    text editors, and other similar applications.

    8.1.4. Starting VB 6.0

    Opening application of visual basic 6.0

    On start up, Visual basic 6.0 will display a dialog box, and one can choose to start a new project, open a new existing project, or select a list of recently opened programs.


    Application activities (8.1)

    1. With examples, discuss the difference between the following:

    a. Graphical User Interface and Command User Interface.

    b. Desktop application and Online application.

    2. State the process followed to start up Visual basic 6.0.

    8.2 Visual Basic Standard EXE Integrated Development Environment(VB-IDE)

    Learning Activity 8.2

    1. Observe the figure and name the objects labeled A, B, C, D, E and F

    a) Visual basic Integrated Development Environment describes the interface
    and environment that we use to create our applications in VB.

    It is called integrated because we can access virtually all of the development tools
    that we need from one screen called interface. The IDE is also commonly referred to
    as the design environment, or the program.

    Project description in standard exe. Project window.

    To design a form window in Visual basic integrated development environment, first
    install Microsoft visual basic 6.0 into PC, and follow the following in order to use it.
    Start>all program> Microsoft visual basic 6.0> Dialog Box >Standard EXE> formwindow
    appear.From the New Project window we can select new, existing and recent
    project.The Standard EXE Project looks like this:

    This is the main IDE window of Visual Basic. The following are components of the standard exe.windows.

    8.2.1 Tool Box

    Items of tool box are used to design the application interface. These items are
    called Controls and are shown in the image below.

    8.2.2 Form window

    The form window is the window or background, where the user can design his form using various controls from the toolbox

    Each standard form has a code window in which the user can write to direct the behavior of a control. You open the code window by double clicking on a form or a control. If you double click a form, you will be taken to a procedure for the form, but once the code window is open, you can go to any procedure for any object on the selected form.

    The codes are of two Categories:

    Declaration is written before any procedure in the code window.
    Statements. The user selects the required event then code statements are written inside these event procedures.

    8.2.4 Project explorer

    Contains forms related to your application, it also contains code modules and classes.

    8.2.5 Properties Window

    Properties are the attribute of controls. Every object has properties, for example a Pen, has its Color, Metal Type, Ink Color, Type etc. In the same manner every control in VB has many properties which are applied by using the property fields in property box . Some properties are read only, which means the values of such properties can’t change using code, while others are Read and Write. You can move Property window any side of VB IDE Window, can appeal using tool bar or by Pressing F4.

    It is also possible to change the properties at runtime to give special effects such as change of color, shape, animation effect and so on.

    8.2.6 Form Layout Window

    The Form Layout window is a visual design tool which is used to control the placement of the forms in the windows environment when they are executed especially when you have more than one form in your program, To position a form in the Form Layout window, simply drag the miniature form to the desired location in the window.

    8.2.7 Menu Bar

    This is where you can select actions to perform on all your project files and to access help. When a project is open extra menus of project, build and data, are shown in addition to the default menu selection of File, edit, View, Debug, tools, window and Help.

    Application activities 8.2

    1. Name five items on VB toolbox.

    2. List two boxes that make up Visual Basic IDE?

    8.3 Visual basic controls

    a) Uses of properties window

    Learning activities (8.3.1)

    1. Design a form and call it “NDI UMUNYARWANDA” and have the three labels with three textbox. As well as the properties of label are:

    Name: lblfirstname, lbllastname, and lblnationarity respectively.

    Appearance: run time with 3D effects.

    Caption: First Name, last Name and Nationality. Respectively

    Font: (font face Bold, font style Time New roman, size 14 and effects)

    Forecolor: It returns foreground color of a label

    Height: 1000.

    Width: 2000

    Backcolor: Active border.

    Borderstyle: Fixed Single-With border)

    Backstyle: Opaque

    • And the textbox as

    Name: txtfirstname, txtlastname, and txtnationarity respectively.

    Caption: Null in all

    Font: (font face Bold, font style Time New roman, size 14 and effects)

    Height: 730.

    Width: 3000

    8.3.1 Definition of form.

    Form is the shape, visual appearance, or configuration of an object. In a wider sense, the form is the way something is or happens. Form may also refer to: Form (document), a document (printed or electronic) with spaces in which to write or enter data.

    8.3.2 How to design a form in Visual Basic

    To design a form in visual basic use the controls which are available in the Tool Box in the left side of the project window. Use the following steps for each control that you want to add on the form:

    Step 1: In the Tool Box, choose a control that you want andClick on it.

    Step 2: Drag and draw a control in the form using mouse.

    Step 3: Change state for Specific control like size etc.

    8.3.3 properties Window

    Definition of Properties Window.

    Properties Window is used to change the state of each control using particular properties associated with each control.

    How to use Properties Window.

    Before writing an event procedure for the control to response to a user’s input, you have to set certain properties for the control to determine its appearance and how it will work with the event procedure. You can set the properties of the controls in the properties window or at runtime.

    Consider the following picture



    Figure 8.15 above is a typical properties window for a form. You can rename the form caption to any name that you like best. In the properties window, the item appears at the top part is the object currently selected (in Figure 8.15, the object selected is Form1). At the bottom part, the items listed in the left column represent the names of various properties associated with the selected object while the items listed in the right column represent the states of the properties. Properties can be set by highlighting the items in the right column then change them by typing or selecting the options available. For example, in order to change the caption, just highlight Form1 under the name Caption and change it to other names. You may also try to alter the appearance of the form by setting it to 3D or flat. Other things you can do
    are to change its foreground and background color, change the font type and font
    size, enable or disable minimize and maximize buttons and etc.

    Application activity 8.3.1

    Q1. Which property used to change state of a control?

    a) Design a form using a control.

    Learning activities (8.3.2)

    Observe the figure below:
    Using the toolbox design the above form.


    A control: is a tool you use to create objects on a Visual Basic form. You select controls from the toolbox and use the mouse to draw objects on a form. You use most controls to create user interface elements, such as command buttons, image boxes, and list boxes.

    • Properties of a control.

    Before writing an event procedure for the control to respond to an event, you have to set certain properties for the control to determine its appearance and how it will work with the event procedure. You can set the properties of the controls in the properties window or at design time. Other things you can do are to change its foreground and background color, change the font type and font size, enable or disable minimize and maximize buttons etc. Here are the important points about setting up control properties:

    • Caption Property of a control should be clearly defined so that a user knows what to do with control

    • Use a meaningful name for property as it is easier to write and read the event procedure and easier to debug or modify the program later.

    • One more important property is whether to make the control enabled or not.

    • You should also consider making the control visible or invisible at design time, or when should it become visible or invisible.

    8.3.4 Common controls used in Visual Basic:


    a .Form
    Form is used when you start Visual Basic, a default form (Form1) with a standard grid (a window consisting of regularly spaced dots) appears in a pane called the Formwindow. You can use the Form window grid to create the user interface and to line up interface elements.

    Steps to create Form

    Step 1: Click Project on menu and choose Add form from the list of options


    Step 2: Click Form and click Open

    Step 3: Set the Properties for a form

    Name: Enter the name of the form. It returns the name used to identify form.

    Enabled: form controls can be enabled or disabled on initial execution with the enabled property.

    Appearance: It sets whether or not object is painted at run time with 3D effects.

    Caption: Enter the caption associated with the form. It sets the text displayed as the title of the form.

    Backcolor: Choose background color of textbox .It sets the background color used to display textbox.

    Borderstyle: Choose border style of the form

    Fillcolor: It sets the colour used to fill in shapes, circles and boxes.

    Fillstyle: It returns the fill style of a shape

    Backstyle: Choose background style; Opaque or transparent

    Font: It returns the font of a form.

    Scaleheight: It sets the number of units for the vertical measurement of form.

    Scaleleft: It returns the horizontal coordinates for the left edge of form.

    • Visible shows or hide a control on a form. It sets value that determines whether an object is visible or hidden


    The label is a very useful control for Visual Basic, as it is not only used to provide instructions and guides to the users, it can also be used to display outputs. One of its most important properties is Caption. Using the syntax label.Caption, it can display text and numeric data. You can change its caption in the properties window and also at runtime.

    The following are the steps to add a label on the form.

    Step 1: Click on the label icon on the toolbox

    Step 2: Drag and drop a label control in the form

    Step 3: Set Properties for label

    Name: Enter the name of the label control. It returns the name used to identify object.

    Alignment: It returns/sets the alignment of a label

    Appearance: It sets whether or not object is painted at run time with 3D effects.

    Caption: Enter the caption associated with the label. It sets the text displayed on the form.

    Font: It returns the font of object (font face, font style, size and effects)

    Forecolor: It returns foreground color of a label

    Height: Enter the height of the label.

    Backcolor: Choose background color. It sets the background color used to display label.

    Borderstyle: Choose border style of the label(None-no border or Fixed Single- With border)

    Backstyle: Choose background style; Opaque or transparent

    c. Text Box


    The text box is the standard control that is used to receive input from the user as
    well as to display the output. It can handle string (text) and numeric data but not
    images or pictures. String in a text box can be converted to a numeric data by using
    the function Val(text).
    . Steps to add Textbox
    Step 1: Click on the Textbox icon    on the toolbox

    Step 2: Drag and drop a Textbox control in the form

    Step 3: Set Properties for Textbox such as Name, alignment, appearance, backcolor etc.

    d. Frame


    If you want to create a group of controls that work together, you must first create a frame for the controls. (To do this, use Frame, a Visual Basic toolbox control.) Next, place your controls inside the frame so that they can be processed as a group in your program code and moved as a group along with the frame

    Steps to add Frame:

    Step 1: Click on the Frame icon  on the toolbox

    Step 2: Drag and drop a Frame control in the form

    Step 3: Set Properties for Frame: on this step, you set preferred properties


    e. Radio Buttons/ Option Buttons

    The Option Box control lets the user selects one of the choices. However, two or more Option Boxes must work together because as one of the Option Boxes is selected, the other Option Boxes will be unselected. In fact, only one Option Box can be selected at one time. In computer terminology we call this ‘mutual exclusion’. Therefore, two option box controls are said to be mutually exclusive of each other. When an option box is selected, its value is set to “True” and when it is unselected; its value is set to “False”.

    Steps to add Option Button

    Step 1: Click on the OptionButton   icon on the toolbox

    Step 2: Drag and drop aOptionButton control in the form

    Step 3: Set Properties for Option Button

    f. Check box control

    The Check Box control lets the user to select or unselect an option. When the Check Box is checked, its value is set to 1 and when it is unchecked, the value is set to 0. You can include the statements Check1.Value=1 to mark the Check Box and Check1. Value=0 unmark the Check Box, and use them to initiate certain actions. For example, the program will change the background color of the form to red when the check box is unchecked and it will change to blue when the check box is checked.

    Steps to add CheckBox

    Step 1: Click on the CheckBox  icon on the toolbox

    Step 2: Drag and drop a CheckBox control in the form

    Step 3: Set Properties for CheckBox

    g. Command button

    Command button is a very important control as it is used to execute commands. It displays an illusion that the button is pressed when the user clicks on it. The most common event associated with the command button is the Click event.

    h. List Box
    The function of the List Box is to present a list of items where the user can click and select the items from the list. In order to add items to the list, we can use the AddItem method.

    List Box contains a list of options from which user can choose. In windows the
    Font List box is an example of the use of a list box. The Selected item in a ListBox is

    given by the Textproperty. The sorted property determines whether the items in the
    list box will be sorted or not.

    Adding items to list

    a) Change property list from properties window: Open the list properties window
    and choose list property. Write a list of items to appear in the list box

    i. Combo Box

    The function of the Combo Box is also to present a list of items where the user can click and select the items from the list. However, the user needs to click on the small arrowhead on the right of the combo box to see the items which are presented in a drop-down list. In order to add items to the list, you can also use the AddItem method.

    j. Picture Box

    The Picture Box is one of the controls that used to handle graphics. You can load a picture at design phase by clicking on the picture item in the properties window and select the picture from the selected folder. You can also load the picture at runtime using the LoadPicture method. For example, the statement will load the picture grape.gif into the picture box.

    Picture1.Picture=LoadPicture(“C:\Images\grape.gif”)

    Picture Box is a control used to display images on a VB page. The Picture Box control also supports few functionality of generating advanced drawing.

    k. Image box

    The Image Box is another control that handles images and pictures. It functions almost identically to the picture box. However, there is one major difference, the image in an Image Box is stretchable, which means it can be resized. This feature is not available in the Picture Box. The syntax is as follows:

    l. Timer

    When we need to perform tasks at regular interval we can use Timer . Open a new project and place a timer object on your form. Then locate a label at the center of theform and adjust the size as shown in the figure below. For such a program a better look will beestablished by sizing your form as a pop up window.

    m. File System Controls

    File System Controls are set of controls which help us to add file handling capabilities to our program. They are used together to provide an interface for accessing and exploring drives, folders and files. File system controls can be drive list box, directory list box and file list box.

    1) Drive List Box: The Drive ListBox is for displaying a list of drives available in
    your computer. When you place this control on the form and run the program, you will be able to select different drives from your computer.

    2) Directory List Box: is for displaying the list of directories or folders in a selected drive. When you place this control into the form and run the program, you will be able to select different directories from a selected drive in your computer.

    3) File List Box: This control displays a list of files in the current folder.
    These are important controls even though there are plenty of controls used in VB.

    g. ADO

    ADO (ActiveX Data Objects)is the preferred method for accessing non-Jet tables. ADO and DAO are interchangeable for most things and you are unlikely to experience real timing differences with the two methods. There are some things that ADO cannot do with an Access database that DAO can do.DAO is native to Jet, and on several operations, it might perform a bit faster on Jet than ADO. DAO will contain some methods and properties that are only relevant to Jet, not other databases.

    h. DAO

    DAO(Data Access Objects) was the first object-oriented interface that exposed the Microsoft Jet database engine (used by Microsoft Access) and allowed Visual Basic developers to directly connect to Access tables as well as other databases - through Open Database Connectivity (ODBC).

    3. Design a form “Rectangle” that contains a round rectangle.

    4. What is the most common Event associated with the Command Button?

    8.4. Planning and Developing a Visual Basic program.8

    8.4.1 The process of Planning and Developing a Visual Basic program

    Learning activity 8.4.1
    Consider and observe the following form that contains different controls and help a
    school to calculate the monthly interest according to the borrowed money per month.

    1. What is the role of each control on the form.

    2. Which cause the command button named calculate to find and display           the interest

    3. What happen if you do not find the simple interest?

    4. What can you do if run a program and you are informed that the program contains errors?

    Developing a VB program is mainly done in three steps namely setting up user interface, defining the properties, and creating code.

    a. Draw the interface

    At this step, you will be using the object to design the interface of your application; the controls will be taken from the tool box by dragging it from there to the form designer.

    b. Set properties

    At this stage, you will be setting up properties for your form and controls. Those properties are set from the properties window.

    c. Write the event code.

    Coding is to be done in the code window and you get there by double clicking the object you want to code. Now we double click on the form1, the source code Window for the form1 appears:

    Private Sub Form_Load()
    End Sub

    You just have to write your code between two statements. In order to display the
    output, you have to add Form1.show

    Example 8.4.1: VB application to display the message: “welcome to the world of
    programming:”

    Private sub Form_load()

    Form1.show

    Print”welcome to the world of programming”

    End sub.

    Procedure:

    • Put the pointer on the form 1, right button, properties, go to name and replace form1 by frmvolumecylinder.

    • Go to caption; and replace form1 by Volume of cylinder

    • Go now to toolbox, then choose label (3 times) and if toolbox is not there, go to view then choose toolbox

    • Click once on the label one, right button; properties and replace label1 name by lblradius and the caption by the “Radius

    • Click on the label2, properties and replace the label2 name by lblheight and the caption by “Height”

    • Click on label3, properties and replace the name by lblarea and caption by “Volume”.

    • Then go to toolbox, choose now the textbox (3 times) starting by the first, go to properties and remove.

    • Go to text name and replace the text1, text2 and text3 by txtradius, txtheight and txtvolume respectively.

    • Go back to toolbox and choose command buttons (3 times)

    • Go to properties and replace names command1, command2 and command3 by cmdcalculate, cmdnew and cmdexit respectively captions by Calculate,Newcalculation and Exit.

    Command “Calculate”

    Double click on command button “Calculate” to write the code to calculate the
    area when you click on it at running time.

    Codes:

    Private Sub cmdcalculate_Click()
    txtvolume.Text = 3.14 * Val(txtradius.Text ^ 2) * Val(txtheight.Text)
    End Sub

    Command “New Calculation”

    Double click on the command New calculation to write the code to let you make other calculation when click on it.

    Codes:

    Private Sub cmdnew_Click()
    txtradius.Text = “”
    txtheight.Text = “”
    txtvolume.Text = “”
    End Sub

    Command “Exit”

    And finally Exit command to write the code to end the program when you click
    on it.

    Codes:

    Private Sub cmdexit_Click()
    Unload Me
    End Sub

    Application activity 8.4.1


    1. A. Design a form like above using all possible control and its proportional properties.

    2. Coding a program.

    8.4.2. Debugging Your Code and Handling Errors

    Application activities 8.4.2

    UMWARI is a student in senior five, once planning and developing a visual basic program but in running stage it does not run correctly.

    a. Is it possible to correct it? Explain.

    b. Give appropriate term of correct the challenges faces.

    c. Identify why program does not runand the possible solutions.

    8.4.2 Debugging your Code and Handling Errors

    A. Program error: is a result of bad code in some program involved in producing the erroneous result

    B. Handling errors

    Error handling should be used to process only exceptional situations, despite the fact
    that there is nothing to prevent that programmer from using errors as an alternate
    form of program control.

    These errors can be grouped into three categories:

    • Syntax errors

    • Run-time errors

    • Logic errors

    Syntax errors are grammatical errors in the formulation of statements and are picked up by the interpreter while you are typing in the code (providing the syntax checking option - under environment options - is set to yes).

    Run-time errors these are errors that cannot be detected until the program is running. The syntax of the statements is correct, but once executed they cause a error situation to arise. Examples of run-time errors are attempted division by zero or trying to access a non-existent object.

    Logic errors these are errors that cause the program to behave incorrectly. They generally arise through failure on the part of the programmer to arrive at a correct algorithm for the task. Typical problems might be incorrect ordering of statements, failure to initialise or re-initialise a variable, assignment to an incorrect variable, use of ‘<’ instead of ‘<=’, use of ‘and’ instead of ‘or’, or omission
    of a crucial step in the processing. Logic errors may hide in a program even when it appears to work - they may only surface under certain conditions. This is why careful testing is so important.

    c. Debugging

    Debugging is a process by which you find and resolve errors in your code. To debug code in Visual Basic, consider the ideas suggested below. These techniques can also be applied in different sequences.

    • Print the code, if you find it easier to read code on paper instead of softcopy.

    • Run the application to find trouble spots:

    From the Run menu, choose ‘Start’ to begin running the application. Run until an error stops execution, or halt execution manually when you suspect an error by choosing ‘Break’ from the Run menu. Resolve all compile errors and run-time errors. From the Run menu, choose ‘Continue’ to continue running the application. Once bugs are found try out bug fixes and then make edits by testing individual lines of new or debugged code in the Debug window. Search and replace code

    for all occurrences of an error, checking other procedures, forms, or modules with related code. From the Run menu, choose ‘Restart’ to reset application variables and properties and restart the application from the beginning.

    Debugging tools.

    These are tools designed to help in stopping the execution of a program at specific points, detecting run-time and logic errors and understanding the behavior of errorfree code.

    8.4.4 Building an executable file

    You can make an executable file (.exe) from Visual Basic using the following procedure.
    To make an executable file in Visual Basic

    1. From the File menu, choose Make projectname .exe where projectname is the application name for the project.

    2. Type a file name, or browse through the directories and select an existing file name to overwrite an existing executable with a newer version.

    3. By clicking the Options button, you can also specify a number of versionspecific details about the executable file in the Project Properties dialog box.

    4. If you want to modify the version number of the project, set the appropriate Major, Minor, and Revision numbers. Selecting Auto Increment will automatically step the Revision number each time you run the Make projectname .exe command for this project.

    5. To specify a new name for the application, under Application, type a new
    name in the Title box. If you want to specify a new icon, choose one from
    the list.

    6. You can also enter version-specific commentary on a variety of issues under the Version Information box (comments, company name, trademark and copyright information, and so on) by selecting a topic from the list box and entering information in the text box.

    7. Choose OK to close the Project Properties dialog box, and then choose OK in the Make appname .exe dialog box to compile and link the executable file. You can run the executable file like any other Windows-based application: doubleclick the icon for the executable file.

    8.4.5. Deploying a VB Project

    The Visual Basic Package and Deployment Wizard makes it easy for you to create the necessary cab files and setup programs for your application. Like other wizards, the Package and Deployment Wizard prompts you for information so that it can create any exact configuration.

    There are three ways of starting the Package and Deployment Wizard:

    • Run it from within Visual Basic as an add-in. If run the wizard as an add-in, first set the necessary references in the Add-In Manager to load the wizard. When the wizard as an add-in, Visual Basic work with the project currently open. If work with another project, either open that project before starting the add-in, or use the wizard as a stand-alone component.

    • As a stand-alone component from outside the development environment. Run the wizards as a stand-alone component, prompted choose the project on which working with.

    • Start it in silent mode by launching it from a command prompt. “Running the Wizard in Silent Mode” in this topic for more information. After you start the wizard, a series of screens prompt you for information about your project and let you choose options for the package. Each screen explains how it is
    to be used, including which information is optional, and what information must be  entered before move to the next screen. If it display information on screen, press F1 or click the Help button.

    Note: Save and compile project before running the Package and Deployment Wizard. In most cases, the Package and Deployment Wizard create a package that is ready for deployment. However, if customize packaging process further or provide functionality not supported by the Package and Deployment Wizard, modify the Setup Toolkit Project.

    To start the Package and Deployment Wizard from within Visual Basic

    1. Open the project you want to package or deploy using the wizard. Note If you are working in a project group or have multiple projects loaded, make sure that the project you want to package or deploy is the current project before starting the wizard.

    2. Use the Add-In Manager to load the Package and Deployment Wizard, if necessary: Select Add-In Manager from the Add-Ins menu, select Package and Deployment Wizard from the list, then click OK.

    4. On the main screen, select one of the following options:

    • If you want to create a standard package, Internet package, or dependency file for the project, click Package.

    • If you want to deploy the project, click Deploy.

    • If you want to view, edit, or delete scripts, click Manage Scripts.

    For an introduction to these options, see “The Package and Deployment Wizard.”

    5. Proceed through the wizard screens.

    To start the Package and Deployment Wizard as a stand-alone component

    1. If the project you want to package is open, save it and close Visual Basic.

    2. Click the Start button, and then click Package and Deployment Wizard from the Visual Basic submenu.

    3. In the Project list on the initial screen, choose the project you want to package.

    Note You can click Browse if your project is not in the list.

    4. On the main screen, select one of the following options:

    • If you want to create a standard package, Internet package, or dependency file for the project, click Package.

    • If you want to deploy the project, click Deploy.

    • If you want to view, edit, or delete scripts, click Manage Scripts.

    5. Proceed through the wizard screens.

    Running the Wizard in Silent Mode

    Using scripts, you may package and deploy your project files in silent mode. In silent mode, the wizard runs without your having to attend it to make choices and move through screens. The wizard packages and deploys your project using the settings contained in a script.

    Silent mode is especially useful if you are packaging and deploying as part of a batch process. For example, early in the development of your project, you may use the Package and Deployment Wizard to package your project and deploy it to a test location. You can later create a batch file to perform the same packaging and deployment steps periodically as you update your project.

    To package and deploy in silent mode

    1. Open MS-DOS prompt.

    2. Type the name of the wizard executable, pdcmdln.exe, followed by the path and file name of Visual Basic project, and the appropriate command line arguments.

    3. PDCmdLn.exe C:\Project1\Project1.vbp /p “Internet Package”

    4. /d Deployment1 /l “C:\Project1\Silent Mode.log”

    Note: Can perform packaging and deployment in a single silent session by specifying both the /p and the /d arguments, as shown in the example above. Otherwise, use either /p or /d.

    Note Any file or script name that includes spaces should be enclosed in quotation marks, as shown in the example above.

    Application activities 8.4.2

    1. Describe three types of errors made in Visual basic.

    2. Define the term debugging.

    3. Design a simple calculator which makes addition, division, multiplication and subtraction of two numbers.

    4. Hirwa Eric is a programmer, when he attempts to run his VB code, it generates an error.

    a. Explain why this program generate an error?

    b. Give the strategies Eric must follow in order to solve this problem.

    8.5 WORKING WITH MENUS AND DIALOG BOXES

    Learning activities 8.5

    Observe the following organization structure of a girls’ school and answer the following questions:

    1. As a student of S5 how many levels you pass through in order to reach to head teacher?

    2. Why is it necessary to pass at each level?

    3. Design the above organizational structure into a VB form window use of menus.

    Windows applications provide groups of related commands in Menus. These commands depends on the application, but some-such as Open and Save are frequently found in applications. Menus are intrinsic controls. Visual Basic provides an easy way to create menus with the modal Menu Editor dialog. The below dialog is displayed when the Menu Editor is selected in the Tool Menu. The Menu Editor command is grayed unless the form is visible. And also you can display the Menu Editor window by right clicking on the Form and selecting Menu Editor.

    8.5.1 Multiple Document Interface (MDI).

    The Multiple Document Interface (MDI) is another class of the form that allows you to open Windows within a parent container window to simplify the exchange of information among documents, all under the same roof.

    Applications such as Microsoft office Word and Microsoft office excel are the best examples of MDI, where many documents can be opened simultaneously within the main document.

    To use windows applications that can open multiple documents at the same time and allow the user to switch among them with a mouse-click. Each document is displayed in its own window and all document windows have the same behavior.

    The main Form, or MDI form, isn’t duplicated, but it acts as a container for all the windows, and it is called the parent Window.

    The windows in which the individual documents are displayed are called Child
    windows.

    An MDI application must have at least two Form, the parent form and one or more child forms.

    Each of those forms has certain properties. These can be many child forms contained within the parent form, but there can be only one parent form. The parent form may not contain any controls, while the parent form is open in design mode, the icons on the toolbox are not displayed, but you can’t place any
    controls on the form.

    To create an MDI application, at least two forms are needed in the application: One is the parent or container form and the second is the child form or the form contained within the parent. A single child is required for the simple MDI Projects.

    Procedures:

    • Select New project from the file menu

    • In the case you already have a form ,then in the properties window set the name property to frmchild and its caption to MDI_Child

    • Right-click on the forms folder in the project window

    • Click on add from the MDI form to create the MDI Parent form.

    • Select MDI form from the Add MDI form dialog

    • In the Properties window set the name property to frmMDI and the caption property to MDI_Parent.

    • On the project menu, select project1.properties, set the startup object list to

    frmMDI. In the Case you omit this; the application will start with the child form.

    Select the frmchild from the project Explorer

    Set the form’s MDI child property to true in the properties window. This will cause this form, which is the child, to rest inside the MDI Parent container.

    • Save project as from the file menu and save the form as MDI.frm and project as MDI.vbp

    8.5.2 Creating Menus

    Menus, which are located on the menu bar of a form, contain a list of related commands. When you click a menu title in a Windows-based program, a list of menu commands should always appear in a well-organized list.

    Most menu commands run immediately after they are clicked. For example, when the user clicks the Edit menu Copy command, Windows immediately copies information to the Clipboard. However, if ellipsis points (…) follow the menu command, Visual Basic displays a dialog box that requests more information before the command is carried out.

    This section includes the following topics:

    • Using the Menu Editor

    • Adding Access and Shortcut Keys

    • Processing Menu Choices

    8.5.3 Using The Menu Editor

    The Menu Editor is a Visual Basic dialog box that manages menus in your programs. With the Menu Editor, you can:

    • Add new menus

    • Modify and reorder existing menus

    • Delete old menus

    • Add special effects to your menus, such as access keys, check marks, and keyboard shortcuts.

    See the Figure below for Menu editor Window:

    Creating Menu Command Lists

    To build lists of menu commands, you first need to create the menus and then add them to the program menu bar.

    To create a list of menu commands on a form

    4. Click the form itself (not an object on the form).

    5. On the Visual Basic toolbar, click the Menu Editor icon, or select Menu Editor from the Tools menu.

    6. In the Caption text box, type the menu caption (the name that will appear on the menu bar), and then press TAB.

    7. In the Name text box, type the menu name (the name the menu has in the program code). By convention, programmers use the mnu object name prefix to identify both menus and menu commands.

    8. To add the menu to your program menu bar, click next. The Menu Editor clears the dialog box for the next menu item. As you build your menus, the structure of the menus and commands appear at the bottom of the dialog box.

    9. In the Caption text box, type the caption of your first menu command.

    10. Press tab, and then type the object name of the command in the Name text box.

    11. With this first command highlighted in the menu list box, click the right arrow button in the Menu Editor. In the Menu list box, the command moves one indent (four spaces) to the right. Click the right arrow button in the Menu Editor Dialog box to move items to the right, and click the left arrow button to move items to the left.

    12. Click Next, and then continue to add commands to your menu.

    The position of list box items determines what they are:


    To add more menus

    1. When you’re ready to add another menu, click the left arrow button to make the menu flush left in the Menu list box.

    2. To add another menu and menu commands, repeat Steps 3 through 9 in the preceding procedure.

    3. When you’re finished entering menus and commands, click OK to close the Menu Editor. (Don’t accidentally click Cancel or all your menu work will be lost.) The Menu Editor closes, and your form appears in the programming environment with the menus you created.

    Adding Event Procedures After you add menus to your form, you can use event procedures to process the menu commands. Clicking a menu command on the form in the programming environment displays the event procedure that runs when the menu command is chosen. You’ll learn how to create event procedures that process menu selections in Processing Menu Choices.

    8.5.4 Adding Access and Shortcut Keys.

    Visual Basic makes it easy to provide access key and shortcut key support for menus
    and menu commands.

    Access and Shortcut Keys

    The access key for a command is the letter the user can press to execute the command when the menu is open. The shortcut key is the key combination the user can press to run the command without opening the menu. Here’s a quick look at how to add access and shortcut keys to existing menu items:

    • Add an access key to a menu item Start the Menu Editor. Prefix the access key letter in the menu item caption with an ampersand (&).

    • Add a shortcut key to a menu command and Start the Menu Editor. Highlight the  command in the menu list box. Pick a key combination from the Shortcut drop-down list box.

    Creating Access and Shortcut Keys

    You can create access keys and shortcut keys either when you first create your menu commands or at a later time.

    The following illustration shows the menu commands associated with two menus,
    File and Clock. Each menu item has an access key ampersand character, and the
    Time and Date commands are assigned shortcut keys. See figure below.

    Figure 8.39 Menu Editor Window showing how to create shortcut keys

    8.5.5 Processing Menu Choices

    After you place menu items on the menu bar, they become objects in the program. To make the menu objects do meaningful work, you need to write event procedures for them. Typically, menu event procedures:

    • Contain program statements that display or process information on a form.

    • Modify one or more object properties.

    For example, the event procedure for a command named Time might use the Time keyword to display the current system time in a text box. Processing the selected command might require additional information (you might need to open a file on disk, for example). If so, you can display a dialog box to receive user input by using a common dialog box. You’ll learn this technique in the next section.

    Disabling a Menu Command

    In a typical Windows application, not all menu commands are available at the same time. In a typical Edit menu, for example, the Paste command is available only when there is data on the Clipboard. When a command is disabled, it appears in dimmed (gray) type on the menu bar. You can disable a menu item by:

    • Clearing the Enabled check box for that menu item in the Menu Editor.

    • Using program code to set the item’s Enable property to False. (When you’re ready to use the menu command again, set its Enable property to True.).

    Application activity 8.5

    Design a program which have five menus (Home,Insert,Page Layout, review and View) and sub_menu in home ( File, open and Edit) and the open File option display form1.

    You should be able to open the above form using shortcut(Ctrl+F).

  • UNIT 9: VARIABLES, OPERATORS, EXPRESSIONS AND CONTROL STRUCTURES.

    Key Unit Competency

    To be able to use variables, operators, expressions and control structures in a Visual Basic program.

    INTRODUCTORY ACTIVITY

    The Visual Basic program below asks the user to enter the names, year of birth and the sex and displays the following messages: “Good Morning Sir, you are .... years old” if the sex is Male and “Good morning Madam, you are ...years old” Analyze the following VB

    source code and answer corresponding questions:

    Private Sub Command1_Click()

    Dim names, sex As String

    Dim year As Integer

    names = Text1.Text

    sex = Text2.Text

    year = Val(Text3.Text)m = 2018 - year

    If sex = “Male” Then

    Print “Good morning Sir , you are”; m; “ years old “

    ElseIf sex = “Female” Then

    Print “Good morning Madam ,you are”; m; “ years old “Else

    Print sex; “ sex does not exist!”End If

    End Sub

    1. List the variables used in the source code above

    2. What is the type of Visual Basic Data used in this source code?

    3. Describe operators used in the source code

    4. What is the control structure used in the source code?

    5. Draw the corresponding interface and give an output of the above source code

    9.1. Types of Visual Basic Data

    ACTIVITY 9.1

    In every program, a programmer declares variables with their data types.

    1. Explain why the declaration of variables is important during the writing of programs

    2. What are the data types used in programs?

    3. Discuss the storage size and range of values of data types used in programs.There exist many types of variables, but the most used in Visual Basic are:

    • An elementary data type, such as Boolean, Long, or Decimal

    • A composite data type, such as an array or structure

    • An object type, or class, defined either in current application or in another application All the above types are grouped in two major data types: numeric data type and non-numeric data type.

    9.1.1 Numeric data types

    Numeric data types are types of data that consist of numbers, which can be computed mathematically with various standard operators such as add, minus, multiply, divide among others.


    9.1.2 Non-numeric data types

    Non- numeric data types are types of data that cannot be manipulated mathematically using standard arithmetic operators. The non- numeric data types comprise of text or string data types, the Date data types, the Boolean data types, Object data type and Variant data type.

    Suffixes for literal

    Literals are values that you assign to data. In some cases, we need to add a suffix behind a literal so that VB can handle the calculation more accurately. For example, we can use num=1.3089# for a Double.

    In some cases, a literal can be forced to a particular data type; for example, when assigning a particularly large integral literal value to a variable of type decimal, the following example produces an error:

    Dim myDecimal as Decimal

    myDecimal = 100000000000000000000 ‘ This causes a compiler error. The error results from the representation of the literal. The Decimal data type can hold a value this large, but the literal is implicitly represented as a Long, which cannot.To make the previous example work, you can append the D type character to the literal, which causes it to be represented as a Decimal:

    Dim MyDecimal AsDecimal = 100000000000000000000DSo, a suffix needs to be added behind a literal so that VB can handle the calculation more accurately. If a suffix is not added behind a literal, it generates a syntax error. For example, num = 2.3807# is used for Double data type. The Table 9.3 below shows Visual Basic Data Types and their suffixes or Appended type char-acter

    Note: String literals are normally enclosed within double quotations while date and time literals are enclosed within two # sign. Strings can contain any characters, including num-bers. The following table summarizes the data types with their enclosing characters and appended type charactersTable 9.4: data types with their enclosing characters and appended type characters

    APPLICATION ACTIVITY 9.1

    1. What would happen if a programmer uses one of VB keywords (reserved words) as a variable identifier?

    2. In a program, if a user declares an integer variable and enters a string like “book”, explain the nature of the results produced by such a program

    3. Study the following VB source code, draw its corresponding interface and then give an output.

    Private Sub Form_Load()

    Form1.Show

    Name1 = “ UWIHANGANYE”

    phone = “ +250783297650”

    Jour = #7/29/1996#

    BithTime = #7:20:00 PM#

    Text1.Text = Name1

    Text2.Text = phone

    Text3.Text = Jour

    Text4.Text = BithTime

    End Sub

    9.2 Variables

    ACTIVITY 9.2

    1. Outline different rules of naming a variable in Visual Basic

    2. Explain general format of variable declaration

    3. Explain general format of variable initialization

    4. Draw interface and write a VB program which asks a user for entering a radius of a circle to display the area of a circle after running the program as shown in figure 9.1. Consider pi as the constant whose numeric value 22/7.


    A variable is a name assigned to a data storage location. It can also be defined as area allocated by the computer memory to hold data. Variables are used in Visual Basic to store various kinds of data during program execution.

    9.2.1 Variable name

    In Visual Basic Program, each variable must be given a name. To name a variable in Visual Basic, there is a set of rules to be followed.The rules used in naming variables in Visual Basic are:

    • No more than 40 characters

    • Variables must include letters, numbers and underscores egg. No punctuation, spaces or other characters are permitted.

    • A variable name must begin with a letter

    • The name cannot be a reserved word (words needed by Visual Basic).

    For example, End is a reserved word in Visual Basic and therefore should not be used as a variable name.Examples of valid and invalid variable names are displayed in the table below:

    9.2.2 Variable declaration

    They are three ways for declaration of a variable.

    1. Default Declaration

    If the variables are not implicitly or explicitly declared, they are assigned the variant (a var-iable that can hold data of any size or format) type by default. The variant data type is a special type used by visual basic that contains numeric, string or date data.For example: the following VB program finds the sum of two given numbers:

    Private Sub Command1_Click()

    Dim n1, n2, sum As Variant

    n1 = Val(Text1.Text)

    n2 = Val(Text2.Text)

    n3 = n1 + n2Text3.Text = n3

    End Sub

    2. Implicit Declaration

    To implicitly declare a variable, use the corresponding suffix. For example:

    declaration way, Visual Basic will take care of ensuring consistency in upper and lower case letters used in variable names.

    To explicitly declare a variable, its scope has to be firstly determined. There are four levels of scope are procedural level, static, form and module level, and last global level

    These levels of scope progress from the narrowest (block) to the widest (namespace), where narrowest scope means the smallest set of code that can refer to the element without qual-ification.

    a) Procedure level

    With procedure level, variable are declared using the Dim statement Example:

    Dim MyName As String

    Dim MyInt As Integer

    This is given to variables declared using the Dim reserved word within a block of statemet

    Here, the variable can only exist and be used within the If ... Then ... Else statement. It is a local variable visible only inside the block where it has been declared.

    b) Procedure level scope, static

    In procedure level ,static, variables declared in this manner do not retain their value once a procedure terminate, within a procedure level, static variables are declared using the Dim statement

    For example:

    Private Sub End_click()

    Static age As Integer

    Static MyName As string

    end sub

    Note that

    Dim can only exist and be used within the procedure or function. It is a local variable in that procedure or function.

    • Procedure level variables declared in this manner do not retain their value once a pro-cedure terminates.

    • To make a procedure level variable retain its value upon existing the procedure, replace the Dim keyword with Static

    c) Form(module) level scope

    The variable is declared in the General Declarations section at the start of the module. Form (module) level variables retain their values and are available to all procedures within that form.

    Module level variables are declared in the declarations part of the general object in the form’s (module’s) code window. The Dim keyword is used.

    Example1: Dim MyDate as Date

    Example 2: a program which requires three numbers entered from keyboard then calcu-lates their sum and average.

    Requirements to perform the asked question;Design interface containing five Text box with their corresponding labels and four com-mands representing sum, agerage clear and exit respectively least but not last assign prop-erties to each control and last attach code

    VB Source code can look as follows :





    d) Global level scope

    This is given to variables declared using the public reserved word within a code module. The variable is declared in the General Declarations section at the start of the module. Glob-al level variables retain their value and are available to all procedures within an application.It is advisable to keep all global variables in one module. Use the Global or public keyword.

    Examples: Global MyInt as Integer or Public MyInt as Integer
    Notice that several variables can be declared in one statement without having to repeat the data type. In the following statements, the variables i, j, and k are declared as type Integer, l and m as Long, and x and y as Single:

    Dim i, j, k As Integer
    ‘All three variables in the preceding statement are declared as Integer.
    Dim l, m As Long, x, y As Single
    ‘In the preceding statement, l and m areLong, x and y are Single.

    Variable initialization

    Once a variable is declared, it does not have a defined value, hence it cannot be used until it is initialized by assigning it a value.
    Thus, variable initialization is the process of providing or assigning value to the variable
    Where Variablename is the descriptive name of the variable, = is the assignment operator and value is the value that a variable will contain.


    9.2.4 Declaring Constants

    constants is value in memory that does not change during program execution. For example, in mathematics, pi is a constant whose numeric value is 22/7.The declaration of a constant goes immediately with its initialization.

    Syntax: Const constant name As data type = value





    9.3 Scope of a variable

    Learning Activity 9.1
    As any other programming language, Visual Basic application acts on data stored in variables. Using internet and library textbooks, discuss different scopes of variables.

    APPLICATION ACTIVITY 9.2

    1. Study the given VB source code of a program that requires a positive integer and displays its factorial. To avoid possible memory overflow, replace the “fact” variable data type with an appropriate data type whose size can hold a large value.




    2. Write a VB program that asks to enter a radius of a sphere and display its volume. Declare Pi as a constant variable and assign to it 22/7 value.
    3. Write a VB program that requests the user to enter 2 numbers and displays their sum, difference and product.

    The scope of a declared element is the set of all code that can refer to it without qualifying its name. It is an area of influence and lifetime for a variable. This means a period of existence dependent on where and how the variable is declared. An element can have scope at one of the following levels:


    In Microsoft Visual Basic for Applications, the three scopes available for variables are private, module, and public.

    9.3.1 Private (Local) Scope

    A local variable with private scope is recognized only within the procedure in which it is declared. A local variable can be declared with a Dim or Static statement.
    • When a local variable is declared with the Dim statement, the variable remains in existence only as long as the procedure in which it is declared is running. Usually, when the procedure is finished running, the values of the procedure’s local variables are not preserved, and the memory allocated to those variables is released.
    • A local variable declared with the Static statement remains in existant the entire time Visual Basic is running. Local variable retains its value after the module has finished executing.

    9.3.2 Module (Global) Scope

    A variable that is recognized among all of the procedures on a module sheet is called a “module-level” variable. A module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules. A module-level variable re-mains in existence while Visual Basic is running until the module in which it is declared is edited. Module-level variables can be declared with a Dim or Private statement at the top of the module above the first procedure definition.




    9.3.3 Public scope

    Public variables have the broadest scope of all variables. A public variable, like a module-lev-el variable, is declared at the top of the module, above the first procedure definition. A pub-lic variable cannot be declared within a procedure. A public variable is always declared with a “Public” statement. A public variable may be declared in any module sheet.


    APPLICATION ACTIVITY 9.3

    Write a Visual Basic program which computes the sum and average of the three given integers using keyboard.To achieve this, follow the instructions below:
    i. The program uses two different procedures addition () and moyenne ()
    ii. Declare the 3 variables as local variables in addition () procedure
    iii. Declare sum as global variable to hold the sum calculated by addition() procedure
    iv. The moyenne () procedure calculates the average of three given integers and display it.

    9.4 Operators and expressions in Visual Basic

    ACTIVITY 9.4
    1. Enumerate the various operators used in C++ programming language
    2. What is the value of the following expression if x=10 and y=5?
    3. Evaluate the following expression if A=10, B=5, C=0 and D=22(A AND B)OR(C OR D) AND A

    In programming context, an operator is a symbol or a keyword that instructs a compiler to evaluate mathematical or logical expressions.A Visual Basic expression is a combination of operators and operands.
    For example, in the expression: energy = mass * light_speed ^2
    • Energy, mass ,light_speed and 2 are the operands while
    • = is the assignment operator, * is multiplication operator and ^ the exponentiation arithmetic operator.

    9.4.1 Arithmetic operators

    The most common operators in Visual Basic are the arithmetic operators. Table 9.4 below gives a summary of arithmetic operators supported in Visual Basic.


    Note that:
    • Parentheses () can change the precedence
    • To concatenate two strings, use the & symbol or the + symbol: txtSample.Text=”My country“+“is”+ “Rwanda” myname=”John” & “Mugabo”

    9.4.2 Relational (Comparison) operators

    Normally, they are used to compare data values and then the result helps to decide what action to take. The result of comparison operation is a Boolean value (True or False).


    AND: An expression has a true value if both operands are true, and false value elsewhere
    OR: An expression has a true value if at least one of the operand is true and false elsewhere.
    Xor: An expression has a true value if both operand are different and has a false value if both operands are the same.
    NOT: Negates Boolean operand


    The following example of VB program illustrates the Not ,And,Or,and Xor operators




    Note that The AndAlso Operator is very similar to the And operator, in that it also performs logical conjunction on two Boolean expressions. The key difference between the two is that AndAlso exhibits short-circuiting behavior. If the first expression in an AndAlso expression evaluates to False, then the second expression is not evaluated because it cannot alter the final result, thus AndAlso returns False.
    Similarly, the OrElse Operator performs short-circuiting logical disjunction on two Boolean expressions. If the first expression in an OrElse expression evaluates to, then the second expression is not evaluated because it cannot alter the final result, and OrElse returns True.

    9.4.3 Bitwise operators

    Bitwise operations evaluate two integral values in binary (base 2) form. They compare the bits at corresponding positions and then assign values based on the comparison. Bitwise operators are similar to logical operators only that they are specifically used to manipulate binary digits.


    Example:
    Consider the expression below:
    x = 5 Or 6
    5 in binary form = 1016
    in binary form = 110101
    And 110 = 100

    The bitwise And operator compares the binary representations, one binary position (bit) at a time. If both bits at a given position are 1, then a 1 is placed in that position in the result. If either bit is 0, then a 0 is placed in that position in the result. The result is treated as decimal. The value 100 is the binary representation of 4, so x = 4.
    The bitwise Or operator takes a 1 and assigns to the result bit if either or both of the compared bits is 1.


    Example: Consider the expression below:
    x = 5 Or 6
    101 (5 in binary form)
    110 (6 in binary form)
    111 (The result, in binary form)

    The result is treated as decimal. The value 111 is the binary representation of 7, so x =7.
    • Bitwise Not takes a single operand and inverts all the bits, including the sign bit, and assigns that value to the result. This means that for signed positive numbers, Not always returns a negative value, and for negative numbers, Not always returns a positive or zero value.

    Example: Dim x As Integer
    x = Not 5101 (5 in binary form) , its negation is 010The result is treated as decimal. The value 010 is the binary representation of 2, so x =2.
    Bitwise Xor assigns a 1 to the result bit if exactly one of the compared bits (not both) is 1.

    Example:Dim x As Integer
    x = 5 Xor 6101 (5 in binary form)
    110 (6 in binary form)
    011 (The result, in binary form)The result is treated as decimal. The value 011 is the binary representation of 3, so x =3.

    • The AndAlso and OrElse operators do not support bitwise operations.The following example of VB program illustrates the use of bitwise operators



    9.4.4 Precedence of operators

    When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence.
    Precedence Rules:
    When expressions contain operators from more than one category, they are evaluated ac-cording to the following rules:
    • The arithmetic and concatenation operators have greater precedence than the comparison, logical, and bitwise operators.
    • All comparison operators have equal precedence, and all have greater pre-cedence than the logical and bitwise operators, but lower precedence than the arithmetic and concatenation operators.
    • The logical and bitwise operators have lower precedence than the arithme-tic, concatenation, and comparison operators.
    • Operators with equal precedence are evaluated left to right in the order in which they appear in the expression
    Just like in BODMAS, the order of precedence can be changed by use of parenthesis.




    Note that:
    • The string concatenation operator (&) is not an arithmetic operator, but in precedence it is grouped with the arithmetic operators.
    • When operators of equal precedence appear together in an expression, for example multiplication and division, the compiler evaluates each opera-tion as it encounters it from left to right. The following example illustrates this.


    APPLICATION ACTIVITY 9.4
    1. Study the following program and determine the output after its execution


    2. Perform bitwise And, Or and Xor on the following variables
    a. S = 25, T = 31
    b. X = 50, Y = 18

    9.5. Decision structures in Visual Basic

    Learning Activity 9.5
    1. Discuss the use of decision control structures (If...Then, If... Then... Else, Nested If ... Then.... Else ...Statements) in Visual Basic programming
    2. Using Visual Basic, write a program that prompts a user to enter a student’s score in Mathematics. If the score is above 45%, the program should display “Pass” otherwise it should display “Fail”

    To implement an application in visual basic, you need several coding structures to control the program flow. The control structures are used to control the flow of execution of a pro-gram they are used in a program to repeat a set of operations (looping control structures), and for making decisions according to the conditions when a program is executing (deci-sion control structures). A decision structure will test a condition and then perform opera-tions depending on whether yes or not the condition is met (True or false).

    9.5.1 Types of decision control structures

    Decision control structures also known as selection control statements are conditional logic used when there is one or more options or alternatives to chose from. There are four types of decision control structures namely if...then, if...then else, nested if ....then else, and select case

    A. If ..... Then statement


    B. If .....Then ....Else statement
    The If...Then...Else selection structure allows the programmer to specify that different ac-tions are to be performed when the condition is True than when the condition is False. If the condition is true, the first part of the if ...then is executed. However if the condition is false the block of the else statements is executed

    The syntax of the If ...Then ...Else conditional statement is as follows:




    C. Nested If ....Else statement
    Nested If...Then...Else statement test for multiple cases by placing If...Then...Else selection structures inside If...Then...Else structures
    The syntax of the Nested If ...Else




    In using branching statements, be aware that each IF and Else If in a block is tested sequen-tially. The first time an If test is met, the code associated with that condition is executed and the If block is exited. If a later condition is also True, it will never be considered.
    Example:
    Write a program to read marks (per cent) of university students and put these students into classes according to their marks. Classes with their corresponding marks:
    • From 80 to 100: First class honours
    • From 70 to 79: Upper second class honours
    • From 50 to 69: Lower second class honours
    • From 40 to 49: Pass
    • Below 40: Fail

    Solution:





    APPLICATION ACTIVITY 9.5
    1. Create a simple program which will ask a user to input a value.
    • If the value is 1 it should display the text “The day is Monday”
    • If the value is 2 it should display the text “The day is Tuesday”
    • Do this for all the days of the week.
    • Use the Nested If...Then ...Else structure to achieve the above.
    2. Write a VB program that would enable the user to enter student marks in three subjects. The program should calculate mean marks and determine whether the student has passed if the pass mark is 50%
    3. Observe the following interfaces and write a visual basic program using various mathematical functions like sqrt, sqr, sin, cos, tan.\





    Hint: Once the user enters any value in the first Textbox and selects any option, the output will be displayed in second TextBox, if the user enters a negative number and selects the sqrt option he/she will be informed that the square root of a negative number does not exist and once he or she does not select any option he/she will be informed to select any of available option.

    D. Select case statement

    Learning Activity 9.6

    1. Discuss the use of Select case statement as decision control in Visual Basic programming
    2. Create a simple program which will ask a user to input a value.
    • If the value is 1 it should display the text “The month is January”
    • If the value is 2 it should display the text “The month is February”
    • If the value is 3 it should display the text “The month is March”
    • If the value is 4 it should display the text “The month is April”
    • Do the same for all months of a year
    • Use the Select case statement to achieve the above

    Select...Case structure is an alternative to nested If...Then...Else for selectively executing a single block of statements from among multiple block of statements. If the “case” matches the condition is selected and all instructions within the matching case are executed. Select...case is more convenient to use than the If...Else...End If.The general format is:


    Each possible value of the item is checked using a Case statement followed by one or more Visual Basic statements that will be carried out if there is a match for that value. The final part of the structure is usually a Case Else statement to be executed if none of the above values match. This is useful for informing the user that he /she is out of cases.

    Example 1: A Visual Basic program that displays the Grade according to the marks entered by students:











    Example 2: Application to assign grade (comment) to students depending upon the marks they’ve got.











    APPLICATION ACTIVITY 9.6

    1. Write a VB program that displays the comment according to the entered student’s grade 


    2. Write a VB program that allows a user to enter two floating point number from the keyboard and it requests a user to enter his/her preference in order to perform one operation from (addition, subtraction, multiplication and division) operation’s menu. The program will display the result of an operation.

    Interface of your program should be similar to the following:


    9.6 Repetition structures

    Learing Activity 9.7
    3. With an example, explain the use of the following loops in Visual Basic programming:
    • Do While Loop
    • Do Until.... Loop
    • While loop
    • For loop
    4. Write a program that prints the numbers divisible by 5 and 3 in the range from 1 to 205. Using Do ... Loop While, write an application that prints not divisible by 5 in the range from 1 to 10

    Repetitions also known as iterations or loops are structures that allow a statement or group of statements to be carried out repeatedly while some conditions remain true (or for a specified number of times)
    They are two basic iteration structures:
    a. Pre-test iterations: in these loops, the condition to be met occurs at the beginning of the loop and the code will not run at all if the condition is never met. This can be implemented using: For ... Next, Do While .... Loop, Do Until ... Loop and While ... Wend loop
    b.Post –test iterations: in these loops, the condition to be met is at the end of the loop so that the code always runs at least once. This can be implemented using the: Do ... Loop While, Do ... Loop Until
    Visual Basic supports two types of loops which are indeterminate loops and determinate loop

    9.6.1 Indeterminate loops

    These are loops which repeat until a predetermined goal is achieved. Repeating until some initial conditions change. The Indeterminate loops supported in VB are the following:

    i. Do While ... Loop



    When Visual Basic executes this Do While ... Loop, it first tests condition. If condition is False, it skips past all the statements. If it’s True, Visual Basic executes the statements and then goes back to the Do while statement and tests the condition again. Consequently, the loop can execute any number of times, as long as condition is True. The statements never execute if initially is False.

    Example: a visual basic program to find the sum of number from 0 to 100


    ii. Do Until ... Loop

    Unlike the Do While...Loop and While...end loop structures, the Do Until... Loop structure tests a condition for falsity. Statements in the body of a Do Until...Loop are executed re-peatedly as long as the loop-continuation test evaluates to False. The general format is:



    ii. While .... Wend

    A While...Wend statement behaves like Do While...Loop statement. It executes a set of VB statements till the condition evaluates to true.



    iv. Do ... Loop While

    The Do...Loop While statement first executes the statements and then test the condition after each  execution.


    The programs executes the statements between Do and Loop While structure in any case. Then it determines whether the number is less than 20. If so, the program again executes the statements between Do and Loop While, else exits the Loop.

    v. Do ... Loop Until

    The general format is:


    Figure 9.21: Loop results

    APPLICATION ACTIVITY 9.8

    1. By using:
    • Do While.... Loop
    • While ...Wend loop
    • Do ... Loop Until

    Write a VB program that computes the sum of even numbers from 0 to 50.2. Write a VB program that displays the product of even numbers and product of odd numbers between 1 to 15 numbers.

    9.6.2 Determinate loop

    ACTIVITY 9.9
    1. Give and explain the syntax of for... Next loop in VB2. Write a program that reads a number from user and displays the table of that number.
    2 X 1 = 2
    2 X 2 = 4
    2 X 3 = 6

    . . . . .
    2 X 9 = 18
    2 X 10 = 20

    This loop repeats a set of operations a fixed number of times. The common used terminate loop is For ....next loop.



    In this syntax statement, For, To, and Next are required keywords, and the assignment oper-ator is required. First, you replace variable with the name of a numeric variable that keeps track of the current loop count. Next, you replace start and end with numeric values that represent the starting and stopping points for the loop.
    The line or lines between the For and Next statements are the instructions that repeat each time the loop executes.For...Next loop structure handles all the details of counter-controlled repetition
    Example 1: Suppose you want to print the numbers from 1 to 10.The following lines of codes can be used in procedure.



    Example 2: VB application to display the multiplication tables of 5

    User interface:




    Creating Loops with a Custom Counter

    You can create a loop with a counter pattern other than 1, 2, 3, 4, and so on. First, you specify a different start value in the loop. Then, you use the Step keyword to increment the counter at different intervals. In this case the syntax for a For...Next loop looks like the following:
    For counter = initial To End Step [Increment]

    One or more VB statements

    Next [counter]

    The arguments counter, start, end, and increment are all numeric. The increment argu-ment can be either positive or negative. If increment is positive, start must be less than or equal to end or the statements in the loop will not execute. If increment is negative, start must be greater than or equal to end for the body of the loop to execute. If step isn’t set, then increment defaults to 1.


    The VB source code above prints this sequence of numbers: 1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49
    Specifying Decimal Values You can also specify decimal values in a loop. For example:
    For i = 1 To 2.5
    Step 0.1
    Print i
    Next i
    The program above prints this sequence of numbers as follow:


    Note that:The exit statement allows you to exit directly from For Loop and Do Loop. Exit For can appear as many times as needed inside a For loop, and Exit Do can appear as many times as needed inside a Do loop (the Exit Do statement works with all versions of the Do Loop syntax).

    Sometimes the user might want to get out from the loop before the whole repetitive pro-cess is executed; the command to use is Exit For to exit a For.....Next Loop or Exit Do to exit a Do... Loop, and you can place the Exit For or Exit Do statement within the loop.The exit keyword in loop control statement is used as break Jump control statement in other programming languages to terminate prematurely the loop.

    a) Exit For
    The format is:
    For counter= start To end step (increment)
    Statements
    Exit for
    Statement
    Next counter




    Nested Loops
    • The nested loops are the loops that are placed inside each other.
    • The most inner loop will be executed first, then the outer ones.
    • Nested loops are very useful when there is a requirement to generate differ-ent kinds of patterns as output.


    For Each loop
    The For Each loop is a scope that defines a list of statements that are to be repeated for all items specified within a certain collection/array of items.
    The For Each loop, as compared to the For loop, can’t be used to iterate from a range of values specified with a starting and ending value.

    Syntax of a For Each Loop:

    For each variable in Items
    Vb codes
    Next variable
    Where:Variable is the iterating variable which is used to iterate through the elements of the col-lection or array
    Items: a collection or array of items
    Next: closing statement for the loop. Optionally you can specify the Iterator variable



    APPLICATION ACTIVITY 9.9
    1. Study the following program in Visual Basic and write its output:


    2. Write a VB program to display the following sequence of numbers 100,80,60,40,20,0
    3. Write a VB application that prints the numbers divisible by 5 or 3 but not both in the range from 1 to 20

    END UNIT ASSESSMENT

    1. Write a VB program to calculate the values of the following arithmetic operation if the user inputs two numbers M and N into two separate text boxes
    a. M^Nb.
    b.M\Nc.
    b.M Mod N
    2. Build an application to calculate the volume of the cylinder
    3. Differentiate nested if to switch case decision control structures
    4. Write a VB application that prints the numbers divisible by 5 or 3 in the range from 1 to 20
    5. Write a VB program that displays odd numbers between 1 to 30 numbers
    6. Design an application to compute the sum of the first “N” natural numbers.
    7. Draw an interface and write a VB application to check if a given number is prime or not.



  • UNIT 10: INTRODUCTION TO JAVA

    Key Unit Competency:
    to be able to create, build and run a java console program

    Introductory activity

    1. Explain the following terms in computer programming:

    a) Computer Programming           b) Programming language

    c) High-level language                 d) Low-level language

    e) Programming paradigms

    2. Discuss the following OOP concepts:

    a) Abstraction               c) Encapsulation

    b) Polymorphism          d) Inheritance

    3. Explain the following concepts in programming

    a) Compile and run program

    b) Programming Environment        c) Basic Syntax      d) Data Types

    d) Variables                                     e) Keywords           f ) Basic Operators

    g) Decision Making         h) Loops

    10.1. Concepts of Java Programming

    Learning Activity 10.1

    1. Define a java in Programming language

    2. Discuss on invention and advantages of java.

    10.1.1. Definition

    Java is a computer programming language. It enables programmers to write computer instructions using English-based commands instead of having to write in numeric codes. It is known as a high-level language because it can be read and written easily by humans

    10.1.2. Invention

    Java is a general purpose, high-level programming language developed by Sun Microsystems. The Java programming language was developed by a small team of engineers, known as the Green Team, who initiated the language in 1991. The Java language was originally called OAK, and at the time it was designed for handheld devices and set-top boxes. OAK was unsuccessful and in 1995 Sun Microsystems changed the name to Java, which has built-in support to create programs with a Graphical User Interface (GUI), utilizes the Internet, creates client-server solutions, and modified the language to take advantage of the burgeoning (developing quickly) World Wide Web. The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications. The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is
    guaranteed to be Write Once, Run Anywhere. A variant of Java programs called applets can be embedded inside a web page and execute on the computer that is viewing the page, automatically and in a secure environment.

    10.1.3. Advantages of Java

    Application Activity 10.1.

    Discuss the difference between Java Programming and C/C++ programming languages in
    terms of advantages.

    10.2. Platforms of JAVA Program

    Learning Activity 10.2.

    Search and discuss about the following in Java Environment:

    1. Platform and Platform independent

    2. Java Virtual Machine (JVM)

    3. Java Runtime Environment (JRE) vs. Java Development Kit (JDK)

    10.2.1 JRE & JDK & JVM

    The Java platform is the name given to the computing platform from Oracle that helps users to run and develop Java applications. The platform does not just enable a user to run and develop a Java application, but also features a wide variety of tools that can help developers work efficiently with the Java programming language.

    The platform consists of two essential pieces of software:

    Java Runtime Environment (JRE): Thisis the environment within which
    the java virtual machine runs. JRE contains Java virtual Machine (JVM),
    class libraries, and other files excluding development tools such as compiler
    and debugger. Note: The JRE takes care of running the Java code on
    multiple platforms, however as developers, we are interested in writing
    pure code in Java which can then be converted into Java byte-code for
    mass deployment
    Java Development Kit (JDK), which is needed to develop those Java applications and applets( a small dynamic Java program that can be transferred via the Internet and run by a Java-compatible Web browser). If you have installed the JDK, you should know that it comes equipped with a JRE as well. JDK contains everything that JRE has along with development tools Such as compiler debugger etc.

    • The Java platform consists of the Java Application Programming Interfaces (APIs) and the Java Virtual Machine (JVM). Java APIs are libraries of compiled code that you can use in your programs.

    • They let the programmers add ready-made and customizable functionality to save them programming time.

    • Any program uses Java API to print a line of text to the console.

    • The console printing capability is provided in the API ready for programmers to use; programmers supply the text to be printed. Java programs are run (or interpreted) by another program called the Java VM, for the native operating system. Any computer system with the Java VM installed
    can run Java programs regardless of the computer system on which the
    applications were originally developed. For example, a Java program developed on a Personal Computer (PC) with the Windows NT operating system should run equally well without modification on
    Macntosh computer running Mac OSx operating system, and vice versa.

    Application activity 10.2.

    Discuss the difference between JVM vs JRE vs JDK

    10.3 Write, Compile and run a java Program

    Learning Activity 10.3.

    1. Using internet, Search and install step by step the environment of java.

    2. Observe and interpret the following picture:

    10.3.1 Create a java program

    Before writing and running the simple Java program, there is a needto install and to configure
    the Java platform. Which is available free of charge from the Java web site.(for example
    NetBeans IDE 8.0 or NetBeans IDE 8.2 )
    The first application, HelloWorldApp, will simply display the greeting “Hello World!” To create
    this program, the following steps must be respected

    Create an IDE (Integrated Development Environment) project: Creating an IDE project means creating an environment in which to build and run the applications. Using IDE projects eliminates configuration issues normally associated with developing on the command line. Build or running an application can be done by choosing a single menu item within the IDE.

    a) Launch the NetBeans IDE.

    • On Microsoft Windows systems, use the NetBeans IDE item in the Start menu.

    • On Solaris OS and Linux systems, execute the IDE launcher script by
    navigating to the IDE’s bin directory and typing. /netbeans.

    • On Mac OS X systems, click the NetBeans IDE application icon.


    In the New Project wizard, expand the Java category and select Java Application as shown
    in the following figure:

    In the Name and Location page of the wizard, do the following (as shown in the figure
    below):

    • In the Project Name field, type HelloWorldApp.

    • In the Create Main Class field, type helloworldapp.HelloWorldApp.

    • Then click the button Finish in the figure below.

    The project is created and opened in the IDE. In the next figure, there are the main components
    of the environment
    • The Projects window, which contains a tree view of the components of the project, including source files, libraries that the code depends on, and so on.

    • The Source Editor window with a file called HelloWorldApp.java open.

    • The Navigator window, used to quickly navigate between elements within the selected class.

    Add Code to the Generated Source File: A source file contains code, written in the Java
    programming language, that programmers can understand. As part of creating an IDE project,
    a skeleton source file is automatically generated and the source file is then modified to add the “Hello World!” message. When this project was created, the Create Main Class checkbox was left selected in the New Project wizard. The IDE has therefore created a skeleton class for the programmer. The «Hello World!» message is added to the skeleton code by replacing the line:
    // TODO code application logic here
    With the line:

    These four lines are a code comment and are not affecting how the program runs. Later
    sections of this unit explain the use and format of code comments.
    Notice that Java programming is case sensitive. It means that “a” is different from “A”, helloWorldApp
    is also different fromHelloWorldApp.

    After adding the code, the remaining action is to Save the changes by choosing
    File | Save.

    The file should look something like the following:

    10.4. Compile the Source File into a .class File

    The IDE invokes the Java programming language compiler (javac), which takes the source
    file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as byte codes.To compile the source file, choose Run | Build Project (Hello World App) from the IDE›s main menu. The Output window opens and displays output similar to what is seen in the following figure:

    program is successfully compiled. If the build output concludes with the statement BUILD
    FAILED, there is probably a syntax error in the code. Errors are reported in the Output window as hyperlinked text. To navigate to the source of an error, double-click such a hyperlink. After fixing the error, once again choose Run | Build Project.

    10.5 Running the Program

    The IDE invokes the Java application launcher tool(java), which uses the Java virtual machine
    to run your application. From the IDE’s menu bar, choose Run | Run Main Project.
    The result is displayed in the next figure.

    10.5.1 Syntax of a java program
    class class_name
    {
    public static void main(String[] args)
    {
    // java code goes here
    }
    }
    Explanation of the syntax

    i. class : class keyword is used to declare classes in Java

    ii. public : It is an access specifier. Public means this function is visible to all.

    iii. static : static is again a keyword used to make a function static. To execute a static function you do not have to create an Object of the class. The main() method here is called by JVM, without creating any object for class.

    iv. void : It is the return type, meaning this function will not return anything.

    v. main : main() method is the most important method in a Java program. This is the method which is executed, hence all the logic must be inside the main() method. If a java class is not having a main() method, it causes compilation error.

    vi. String[] args : This represents an array whose type is String and name is args. We will discuss more about array in Java Array section.

    Application activity 10.3

    1. Type The program prints “Hello World!”, then compile and run it.

    2. Add a print statement to display the sentence “How are you?” Compile and run the program again.

    3. Add a comment to the program (anywhere), recompile, and run it again. The new comment should not affect the result.

    4. Write a program in Java that after compilation and execution will display the messages: “Unity and Peace are the engines of development in Rwanda” and “Rwanda is a Knowledge Based Society”.

    10.5.2 Variables and Data types in Java

    Learning activity 10.4.

    1. Discuss about data type in term of Definition and Classification

    2. Using internet search a variable in java and how is declared.

    3. Given two integer x= 5; y= 4; write a java program which is calculate and display the sum of these two integers.

    The declaration of variables necessitates always specifying their types. Variables cannot exist without types and vice versa. One of the most powerful features of a programming language is the ability to define, declare and to manipulate variables.
    For example, String message;
    This statement is a declaration, because it declares that the variable named message is of type String. Each variable has a type that determines what kind of values it can store

    A. Data type

    Data type is a classification of data which tells the compiler or interpreter how
    the programmer intends to use the data. Most programming languages support
    various types of data, for example: real, integer or Boolean.

    Classification of Java Data type

    i. Primitive Java Data Types

    There are eight primitive data types supported by Java and are predefined by the language
    and named by a keyword. They are presented in the following table.

    ii. Reference Data types or Objects

    Reference variables are created using defined constructors of the classes. They are used to
    access objects. These variables are declared to be of a specific type that cannot be changed.
    For example, employee, puppy, etc.

    • Class objects and various types of array variables come under reference data type.

    • Default value of any reference variable is null.

    • A reference variable can be used to refer any object of the declared type or any compatible type.

    Example: Animal animal = new Animal(“giraffe”);

    B. Variable in Java

    A variable is a storage location (like a house, a pigeon hole, a letter box) that stores a piece
    of data for processing. It is called variable because you can change the value stored inside.
    More precisely, a variable is a named storage location, that stores a value of a particular
    data type.

    The syntax for declaration of variable is as follow:
    data_type variable_name;

    Examples

    To declare an integer variable named x, simply type:
    int x
    String message = “Hello!”;
    int hour = 11;
    int minute = 59;
    Normally, the used names for variables should help to guess what will be the different values
    to assign to them.
    Example
    String firstName, lastName;
    int hour, minute;
    Sometimes a variable is initialized by assigned to it for the first time value before it can be used or it a variable can be assigned assign a value later, as in the previous example. It is also possible to declare and initialize on the same line.

    Printing variables

    The value of a variable can be displayed by using the functions print or println. The following
    statements declare a variable named firstLine, assign it the value “Hello, again!”, and

    The output of this program is: The current time is 11:59.

    Application activity 10.4

    Write a program where you declare the variables firstname, lastname, age, level
    and com bination. This program should display like this: John Ntwali is 18
    years old and in senior 5 of MPC

    10.5.3 Types of Variables in Java

    Learning activity 10.5

    1. Is a variable declared visible always in all parts of the program? Explain
    why and give the different types.

    2. Discuss about Java Expression.

    In terms of visibility of variables in a program, there are three types of in Java namely local variable, instance variable and class variable.
    1. Local Variables

    This type of variable has the following characteristics:
    • Local variables are declared in methods, constructors, or blocks.

    Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.

    • Access modifiers cannot be used for local variables.

    • Local variables are visible only within the declared method, constructor, or block.

    • Local variables are implemented at stack level internally.

    • There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use. Example: Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.

    2. Instance Variables

    The variables defined within a class or method is called instance variables because each instance
    of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another. An instance variable can be declared public or private or default (no modifier).To avoid that the variable’s value is changed out-side its class, it should be declared as private. Public variables can be accessed and changed from outside of the class. The syntax is shown below given below:

    private int doors;

    Whereby:

    “private” is an access modifier
    “int” is data type
    doors is an identifier
    These variables belong to the instance of a class, thus an object. And every instance of thatclass (object) has it’s own copy of that variable. Changes made to the variable don’t reflect in other instances of that class.

    3. Class or static variables

    These are also known as static member variables and there›s only one copy of that variable that is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.
    Public class Product{
    Public static int Barcode;
    }

    10.5.4 Java keywords

    Keywords are words that have already been defined for Java compiler. They have special meaning for the compiler. Java Keywords must be in your information because you cannot use them as a variable, class or a method name. Java keywords are categorized as datatypes and access modifiers

    A. Data types

    All predefined datatypes in java are keywords eg. int, char, bool, double, float, and String

    B. Java access modifiers

    Modifiers are keywords that are added to change meaning of a definition. In Java, modifiers are categorized into two types,

    • Access control modifier

    • Non Access Modifier

    1) Access control modifier

    Java language has four access modifiers to control access levels for classes, variable methods
    and constructors.

    • Default : Default has scope only inside the same package

    • Public : Public has scope that is visible everywhere

    • Protected : Protected has scope within the package and all sub classes

    • Private : Private has scope only within the classes

    2) Non-access Modifier

    Non-access modifiers do not change the accessibility of variables and methods, but they do
    provide them special properties. Non-access modifiers are of 5 types,

    • Final

    • Static

    • Transient

    • Synchronized

    • Volatile
    1) Final: Final modifier is used to declare a field as final i.e. it prevents its content from being modified. Final field must be initialized when it is declared. Final keyword can be used with a variable, a method or a class.

    2) Static Modifier: Static Modifiers are used to create class variable and class methods which can be accessed without instance of a class.

    3) Synchronized modifier: When a method is synchronized it can be accessed by only one thread at a time.

    4) Volatile modifier: Volatile modifier tells the compiler that the volatile variable can be changed unexpectedly by other parts of the program. Volatile variables are used in case of multithreading program. volatile keyword cannot be used with a method or a class. It canbe only used with a variable.

    5) Transient modifier: When an instance variable is declared as transient, then its value
    doesn’t persist when an object is serialized

    10.5.6 Java Expressions

    Expressions are essential building blocks of any Java program, usually created to produce
    a new value, although sometimes an expression simply assigns a value to a variable.
    Expressions are built using values, variables, operators and method calls.

    Types of Expressions

    While an expression frequently produces a result, it doesn’t always. There are three types of
    expressions in Java:

    • Those that produce a value, i.e. the result of (1 + 1), Expressions that produce a value use a wide range of Java arithmetic, comparison or conditional operators.
    For example, arithmetic operators include +, *, /, <, >, ++ and %.

    • Those that assign a variable, for example v = 10

    • Those that have no result but might have a “side effect” because an expression can include a wide range of elements such as method invocations or increment operators that modify the state (i.e. memory) of a program. Example: This program here contains plenty of expressions

    Application Activity 10.5

    Look at the following three groups of statements and predict the outputs

    10.6. Elements of Java source file

    Learning Activity 10.6.


    1. Refer to the numbers in above figure; explain the different parts of this program.

    2. Following the above figure, write a program with a class that has more than one property.

  • Unit11: OOP AND JAVA

    Unit11: OOP AND JAVA

    Key Unit Competency: To be able to use objects to manipulate data in Java program

    Introductory Activity

     

    Observe the above picture and answer the following questions.

                  1. Briefly, discuss the object oriented programming paradigm.

                   2. Find defined classes.

                   3. What are the data members for each class?

                   4. What are the member functions for each class?

                   5. What do you understand by instance of a class?

                   6. Create 2 instances of student class

                   7. Using Java, declare Student class in Java?

    11.1. Classes vs Objects in Java

    Learning Activity 11.1

    Write the above program in your computer and run it. After analyzing the result, answer the following questions:

                  1. Give the output of the program?

                  2. What are new keywords in the above program?

                  3. Describe the structure of the part starting with the word class.

                  4. List the data members contained in the class “student”

                  5. What are the functions found in the above program?

                  6. What is the role played by the keyword new in the above program?

    11.1.1 Class in Java

               a. Definition

    A class is an entity that determines how an object will behave and what the object will contain. In other words, it is a blueprint or a set of instruction to build a specific type of object or a class is a group of objects which have common properties.

                b.  Syntax to declare a class:

     

                 c.  General form of a class

    A class is declared by the use of the class keyword. A simplified general form of a class definition is shown here:

     

    11.1.2. Object in Java

    An object is nothing but a self-contained component which consists of methods and properties to make a particular type of data useful. Object determines the behavior of the class. From a programming point of view, an object can be a data structure, a variable or a function. It has a memory location allocated. The object is designed as class hierarchies.

               a.  Syntax of an object

    ClassName ReferenceVariable = new ClassName();

               b.  Reference variable

    An object can be accessed only through a reference variable. A reference variable is declared to be of a specific type and that type can never be changed.

    Reference variables can be declared as static variables, instance variables, method parameters, or local variables. A reference variable that is declared as final can’t never be reassigned to refer to a different object. The data within the object can be modified, but the reference variable cannot be changed.

    • Object initialization through reference Variable:

    Initializing simply means storing data into object Example 1: Below is the example where class student is created, new keyword and the reference variable are used

      

    Example:  We can also create multiple objects and store information in it through reference variable

     

    • Object initialization through method in Java Language

    Two objects of Student class are going to be created and initialized with the value by invoking the insertRecord method. The state (data) of the objects are displayed by invoking the displayInformation() method.

    Example: The use of method in Java program

     

    Example: Example that maintains the records of Rectangle class.

     

    Application Activity 11.1

          1. What do you understand by object instantiation?

          2. What is the difference between a class and an object?

          3. What is the role of a method in java program?

          4. Discuss why main () method is public, static and void in java?

          5. What is meant by the terms instance variable and instance method?

    11. 2 Constructor in Java

     Learning activity 11.2


    Write the above program in your computer and run it. After analyzing the result, answer the following questions:

                    1. What is the output of the above program?

                    2. Discuss the difference between class district and the function district ()?

                    3. Why the function district () does not have a return type?

    11.2.1. Understanding constructor in Java

                        a.  Definition

    A constructor is a special method of a class that initializes an object of that type. A constructor is an instance method that usually has the same name as the class and can be used to set the values of the members of an object, either to default or to user-defined values

    A Constructor is a special type of method which is used to initialize the object. It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if the class doesn’t have any.

    Every time an object is created using new () keyword, at least one constructor is called. It is called a default constructor.

     There are two (2) ways of creating a constructor: explicit and implicit: • Explicit means that the constructor is created by the programmer. • Implicit means that the creation of a constructor was done by the Java Virtual Machine or the tool, not the Programmer.
    Java will provide default constructor implicitly even if the programmer doesn’t write the code for constructor. It is called default constructor. The explicit is opposite to this implicit which means that the programmer has to write a constructor. Example: The program below maintains records of employees.

  • UNIT 12 : IO AND JAVA

    Key Unit Competency: to be able to use stream, reader and writer in java

    Introductory activity

    Teacher Ntwari prepared examination at the District level and he saved the examination in My Documents folder under File name” district Examination”. One of the questions is to calculate the following quadratic equation x2-7x=0

    1. Explain the path that should be used to access the file contents.

    2. Solve the above quadratic equations using java programming language.

    3. How many variables needed to solve the above quadratic equation if you need to run it with java programming language?

    12.1. Introduction to IO Streams

    Learning activity 12.1

    1. Discuss the steps to be followed if you are requested to write a program that will calculate and display the sum of 10 numbers that you need to provide during the execution of the program.

    The term stream refers to a sequence of values from any input source of data (key-board, file, port, and so on), or to any output destination for data (screen, file, port, and so on).

    They are,

    1. Byte Stream : It provides a convenient means for handling input and output of byte.

    2. Character Stream : It provides a convenient means for handling input and output of characters.

    12.1.1.Definition of Input Stream

    The Input Stream is an abstract class that describes stream input. In Java programming language the Input Stream is used to read data from a source.

    This class defines several methods among which include read() that reads byte of data

    12.1.2.Definition of Output Stream

    Output stream is an abstract class that describes stream output. In Java programming language, the Output Stream is used for writing data to a destination.This class defines several methods among which include write() that reads byte of data

    12.1.3 Role of I/O Stream

    IO Streams provide convenient ways of handling data input and output in a java program. While writing java programs, three IO objects are provided implicitly for performing data Input and Output.

    They are;

    • System.in (input stream)

    • System.out (output stream for normal results)

    • System.err (output stream for error messages)Generally System.in is connected to the keyboard and inputs character data*, and System.out and System.err are connected to the monitor and output character data.

    Application activity 12.1

    1. What is a stream and what are the types of Streams and classes of the Streams?

    2. Differentiate the following terms:

    a. System.in and System. out

    b. output stream and input stream

    12.2. Input Stream, Output Stream and File Stream

    Learning activity 12.2

    From the previous lessons in this unit, we have learned the standard I0 stream in Java. Write and Discuss in groups the source code program allows user to calculate area of any given triangle if base and height that are entered through the keyboard and print the area

    The goal of Input Stream and Output Stream is to abstract different ways to input and output: whether the stream is a file, a web page, or the screen shouldn’t matter. All that matters is that information is received from the stream (or send information into that stream.)

    12.2.1 Output Stream

    Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket.

    Code of Printing “WELCOME WORLD” without advancing to a new line

    System.out.print(“ WELCOME WORLD”);

    Code of Printing “WELCOME WORLD “ and advance to a new line.

    System.out.println(“ WELCOME WORLD”);


    12.2.2. Input Stream

    Java application uses an input stream to read data from a source, it may be data, a file, and an array. There are different input stream classes that can be applied to input data from user.

    • scanner()

    • BufferedReader()

    • DataInputSteam()

    a. Using Scanner class.

    Java has a number of predefined classes which can be used. Predefined classes are organized in the form of packages. A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations) providing access protection and namespace management.

    In Java, data can be input with the help of the Scanner class. This Scanner class is found in java.util package. So, to use the Scanner class, java.util package needs to be included first in the program. Apackage is included in a program with the help of import keyword. The java.util.Scanner class or the entire java.util package are then imported.

    The advantage of using Scanner class is that it provides convenient methods for capturing primitives (nextInt(), nextFloat(), ...) from input devices whereas its disadvantage is that reading methods are not synchronized .

    To import a class or a package, one of the following lines should be added to the very be-ginning of the code.

    import java.util.Scanner; // This will import just the Scanner class

    import java.util.*; // This will import the entire java.util package

    After importing, the following statement will be valid when written in the program.

    Scanner k = new Scanner (System.in);Scanner k, here K is declared as an object of Scanner class. System.in within the round brackets tells Java that this will be System Input i.e. input will be given to the system.

    The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it can also be used to read input from the user in the command line. Here is an example:

    Example 1: a program that asks to enter numbers from the keyboard and displays those numbers on the screen

    n= s1.nextInt(); s1.nextInt() will take integer input from the user and it assigns it to n. . So, this statement will be like n = 14; when user entered 14.

    Similarly, values of other data types can be also input . Same as nextInt() is used to input an integer value, other methods s in table 12.1 will be used to input those values.

    b. Using Buffered Reader Class

    Java Buffered Reader class is used to read the text from a character-based input stream. It can be used to read data line by line by read Line() method. It makes the performance fast. It inherits Reader class.

    Buffered Reader reader = new Buffered Reader(new Input Stream Reader(System.in));

    System.out.print(“Enter your name: “);

    String name = reader.read Line();

    System.out.println(“Your name is: “ + name);

    In the above example, the readLine() method reads a line of text from the command line.

    Advantages: The input is buffered for efficient reading and its disadvantage is that the wrapping code is hard to remember.

    Example of program using Buffered Reader


    Notice that a “keyboard object” for reading from the console keyboard can therefore be instantiated as follows:

    InputStreamReader inStream = new InputStreamReader(System.in);

    BufferedReader keyboard = new BufferedReader(inStream);

    The intermediate variable inStreamcould be eliminated and it can be done in one step like this:

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

    c. Data Input Stream

    InputStream uses read Line() method of DataInputStream to read data from the keyboard. Java InputStreams are used for reading byte based data, one byte at a time.

    The following example describes how to use datainputstream wtih different data types

    Example 1


    Example 2


    Explanations:

    The readLine() method of DataInputStream reads a line at a time and returns a string, irrespective of what the line contains. Depending on the input value, the string is to be parsed into an int or double etc. This is extra work in the keyboard reading when compared to C/C++. In C/C++, parsing is done implicitly by %d, %f, etc.

    What is “System.in”?

    “ in” is an object of “ InputStream” class defined in System class (like “out” is an object of PrintStream class defined in System class). It is declared as static and final object. The in ob-ject is connected implicitly to the “ standard input stream” of the underlying OS.

    DataInputStream dis = new DataInputStream(System.in);

    System.in is a byte stream which is automatically connected to the keyboard reading mech-anism of operating system. It is chained to DataInputStream to facilitate the reading of user input with its readLine() method.

    Like System.in is connected to the keyboard mechanism of OS, the System.out is connected to the standard output mechanism of OS.

    Application Activity 12.2

    1. Write a java program that allows the user to enter three integers and that displays their sum

    2. Write a java program asking the user to enter a number and print its factorial.

    3. Write a java program that allows the user to enter the age of KARENZI, SINGIZWA and MPORE and print the youngest ( use Scanner , input stream and console)

    12.3 File Streams


    a. 1 File Input Stream

    This File Input Stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

    The following constructor takes a file name as a string to create an input stream object to read the file:

    InputStreamf=newFileInputStream(“C:/java/hello”);

    The following constructor takes a file object to create an inputstream object to read the file.

    First a file object using File()methods created as follows:

    Filef=newFile(“C:/java/hello”);

    InputStreamf=newFileInputStream(f );

    Once Input Stream object i s in hand, then there is a list of helper methods which can be used to read from the stream or to do other operations on the stream.

    Methods used for file Input Stream

    1. public void close() throws IO Exception{}: This method closes the file output-stream. Releases any system resources associated with The file. Throws an IO Exception

    2. protected void finalize()throws IO Exception{}: This method cleans up the connection to the file. It ensures that the close method of this file output stream is called when there are no more references to this stream. It throws an 10 Exception.

    3. public intread(intr)throws IO Exception{}: This method reads the specified byte of data from the InputStream and returns the next byte of data and-1will be returned if it is end of file.

    4. public intread(byte[]r)throws IO Exception{}: This method reads r.length bytes from the inputstream into an array. I t r eturns the total number of bytes read. If end of file -1 will be returned.

    5. Public int available() throws IO Exception{}: Gives the number of bytes that can be read from this file input stream. It returns an integer.

    12.3.1 File Output Stream:

    File Output Stream is used to create a file and write data into it. The stream would create a file, if it doesn’t already exist, before opening it for output.

    a. File output stream constructors

    The following constructor takes a file name as a string to create an output stream object to write the file:

    OutputStream f=new FileOutputStream(“C:/java/hello”)

    The following constructor takes a file object to create an outputstream object to write the file. First, a file object using File()method is created as follows:

    Filef=newFile(“C:/java/hello”);

    OutputStream f=newFileOutputStream(f );

    Once the OutputStream object is in hand,then there is a list of helper methods,which can be used to write to stream or to do other operations on the stream.

    b. File output stream methods

    1. public void close() throws IO Exception{}: This method closes the file output stream. Releases any system resources associated with the file.Throws an IO Exception.

    2. protected void finalize()throws IO Exception{}: This method cleans up the connection to the file. Ensures that the close method of this file output stream is called