Tag Archives: free computer studies notes pdf

COMPUTER STUDIES NOTES FREE PDF FORM 2

WORD PROCESSORS

Chapter outline

  • Definition of word processor.
  • Purpose of word processing.
  • Using a word processing package (Microsoft word).

1.4 Editing and formatting a document.

 1.5 Creating and editing a table.

1.6 Mail merge document.

  1. 7 Inserting graphics.

1.8 Printing a document.

DOWNLOAD COMPUTER STUDIES NOTES IN PDF IN THE LINKS BELOW;

COMPUTER STUDIES NOTES FORM 1-4 PDF

Free Computer Studies notes, revision questions, KCSE past Papers, Exams, Marking Schemes, Topical revision materials, Syllabus and Many more

Definition of a word processor

What is a word processor?

A word processor is an application software that enables a person to create, save, edit, format and print text documents. Word processing is the act of using a word processor.

 

Examples of word processors

Examples of word processors include, Microsoft Word, Corel WordPerfect, WordStar, Lotus WordPro and many others.

A word processor has a number of advantages over he type writer that include:

  1. A document can be stored in the computer for future reference in computer files that do not occupy physical space like the one on paper. This creates a paperless document-processing environment.
  2. Typing using a word processor is easier and more efficient because some actions are automated. For example, word-wrap feature automatically takes the cursor to the beginning of the next line once you reach the end of the current. Another automatic features common in most word processors is automatic insertion of a new page after reaching the end of the current page.
  3.  Most word processors have special editing tools such as spelling and grammar checkers and thesaurus that help the user to easily Correct grammar and spelling mistakes. A thesaurus helps to find a word or phrase with similar meanings.
  4.  With insert and type over modes available in most word processors, one can easily insert or replace a word or a phrase without affecting the structure and neatness of the document.
  5. Word processors have superior document formatting features. Formatting refers to the art of making the document more attractive and appealing to the eye. Such features include, underlining, boldfacing, italicization, applying different colors etc.
  6.  While a typewriter may require that we retype the entire document when we want many copies, with a word processor, printing lets you produce as many copies per session as needed.
  7. Using the cut, copy and paste commands, you can incorporate other text without having to retype it.

 

Basic word processing features and concepts

  1. They allow the user to create a file, save it and open it again and again for reuse, editing or formatting.
  2. They have almost similar document windows with the following Features:

(a) Most are designed to look like a piece of paper with a few

(b) Most of the screen is blank before typing of text.

(c) There is a cursor, which blinks at the position where you can Begin entering text.

(d) There is a status bar or line that provides the user with current status information such as saving operation, the name of the file in use, the current page, the current imaginary horizontal-line and column cursor position.

(e) Word wrap: The feature that automatically moves a word or cursor to the beginning of the next line if it does not fit at the end of the current line.

(g) Scrolling: This is the vertical movement of text document on the screen. We can scroll through a text document using the up or do n arrow keys, page up and page down keys and also using, a mouse in windows based word processors.

(h) Help: Sometimes we get lost, confused or need more information on how to use an application. Help contains instruction, tips, pointers, explanations and guidance. You can get help by either pressing F 1 on the keyboard or clicking Help from the menu.

(i) Editing Modes: Word processors have two editing modes, insert and type over mode. In insert mode, every character typed between words, lines or characters is placed at the cursor position. This pushes all the text in front of the cursor away without deleting it. However in type over mode every character typed deletes what was there before and replaces it with new text at the cursor position.

  1. Nearly all word processors have a spelling checker, thesaurus (Dictionary of synonyms) and grammar checker.
  2. They provide for the use of headers and footers, indexing, footnotes and references, typefaces (fonts) and character set.
  3. Most word processors have ability to create and import tables, text and graphics from other programs.

Mostly, word processors are used for writing letters, reports, projects, books, essays, memos curriculum vitae etc.

Factors to consider when choosing a word processor The choice of a word processor depend on:

  1. The type of operating system. For example, most microcomputers are currently running on Windows based operating system such as Microsoft Windows. This means that you should consider acquiring a graphical user interface based Word Processor,
  2. Its user-friendliness, i.e. ease of use.
  3. Its formatting and editing features. They should be good and varied.

 

Using a word processing package Microsoft Word

.

Microsoft Word is one of the components of Microsoft Office. Microsoft Office is integrated software with a number of interrelated programs. The programs include Microsoft Word, a spreadsheet called Microsoft Excel, and a database management system called Microsoft Access, communication software called Microsoft Outlook, and a presentation package called Microsoft PowerPoint among others.

Although there are several versions of Microsoft Word, the most common are Word 97, Word 2000, WordXP and Word 2003. These versions of Microsoft Word are found in Microsoft Office 97, 2000, XP and 2003 suites respectively.

Starting Microsoft Word

There are a number of ways you can start Microsoft Word. However the

Simplest is by using programs start menu.

 

Starting Microsoft Word from the start menu

  1. Click the start button.
  2. Point to programs/ all programs if you are using Windows XP
  3. Click from the programs menu

Microsoft Word screen layout

Once you start Microsoft Word, it provides you with a blank document window referred to as the new document template where you can create your document.

However you may need to use other specialised templates such as Faxes and letters, Memos and Web page. How? Click File then select New from the menu. The New dialog box in Figure 1.3 that appears enables a person to select a template by activating templates tab then double clicking its icon.

 

With Windows multitasking capability, you can have more than one document window at the same time sharing one application window. However, each document window will have its own title bar but both will share other facilities like the menu bar of the application window.

However only one document window will be visible on the desktop at a time while others remains minimized or covered. This window is referred to as the active document window. To switch between document windows, click their buttons on the taskbar.

 

Parts of a window

 

Title bar

A title bar is mostly a blue strip at the top of the window that displays the title of the currently running application or task. However it is possible to change the color of the title bar using the display properties.

 

The title bar also enables the user to move the window around the desktop. This is possible by pointing to it then dragging using the mouse.

 

On the right of the title bar are three tiny buttons called minimize, restore/ maximize and the close buttons.

The minimize button reduces a window to become a button on the taskbar.

 

The restore/maximize button stretches the window to cover the entire desktop or restore it to its original size respectively.

The close button is used to close and exit a window.

 

Menu bar

Provides a drop down list of commands that one can use to perform a task. Examples are File, Exit, Window and Help. Figure 1.4 shows the File drop down menu.

Too/bars

These are rows of buttons or icons that represent commands. The command buttons are shortcuts to the same commands you can access from the menu bar. There are various toolbars available in Microsoft Word but the most common are the Standard and Formatting toolbars (Figure 1.5 and 1.6)

To see what other commands are, just point to the icon on the toolbar and a text tip will be displayed showing the function of the icon.

Most of these commands will be discussed later.

Hiding and displaying the toolbars

  1. Click the View menu option.
  2. Position the pointer on Toolbars.
  3. Click the type of tool bar required to select it.

 

Selected toolbars have ticks or check marks next to them as shown in Figure 1.7.

Rulers

Microsoft Word provides the user with vertical and horizontal on screen rulers that helps the user position text or objects in the right position.

 

If the ruler is not visible on the screen, then display it using the following procedure.

  1. Click the View menu option.
  2. On the drop down menu that appears, click Ruler. A check mark or tick will appear next to it showing that the ruler is displayed on the screen.

 

Work area

This is the working area where you can enter text or graphical objects. All windows based application programs provide the user with a unique working area suited to that particular application.

 

Status bar

This is an interactive strip at the bottom of the screen that acts as a communication link between the user and the program. It displays interactive activities like saving, opening, background printing, cursor position etc.

Scroll bars/button_ and scroll arrows

Scroll bars or buttons are horizontal and vertical bars on the borders of a window that the user drags to scroll upward, downwards, to the right or left of a document. Scroll arrows are arrows at the end of the scroll bars that the user clicks instead of dragging the scroll button. Using scroll bars or arrows is equivalent to using the arrow keys on the keyboard

 

Running the program

 

Creating a document

When you start a new document, you will see a blinking vertical bar called an insertion pointer. You can move your insertion pointer by using the arrow keys or the mouse.

 

In case you are in Microsoft Word and you want to create another new document, you should proceed as follows:

  1. Click the File menu,
  2. Choose new, from the resulting dialog box, click Blank Document Or select template by clicking any template’s tab
  3. Click the OK button.

 

Saving a new document

  1. From the file menu, click save or Save As or simply click the save Button on the Standard toolbar. The difference between save and save as is that although both give the save as dialog box when saving for the first time, Save allows the user to save document without the opportunity to change the file name or the location. Figure 1.9 below shows a save as dialog box.

2.In the file name box, type a unique name for the document

3.Select a the location or drive you want to save in, by clicking the down arrow on the right of save in list box,

4.To save the file in a different format or type such as Word 6.0, Word for Macintosh etc. click the down arrow on the right of Save as type list box and choose a file type.

5.Click the save button. The file will automatically be saved as a Microsoft Word document.

Opening an existing document

1.From the file menu, click Open command or on the Standard toolbar, click the Open button. Alternatively press Ctrl + 0 key combination on the keyboard. The Open dialog box shown appears.

2.Select a drive or folder where the file is saved.

3.In the file name box, type or select the name of the document you want to open.

4.Click the open button

To open a document created in another program, click the file format you want in the files of type box, and then double click the document name in the folder list. You can also use wildcards in the file name box for example, type *. Document to find Microsoft Word files.

 

NB: Microsoft Word keeps a list of shortcut links to recently used files on the file drop down menu. If the list of recently used documents is not displayed, you can configure Microsoft Word to be displaying them by doing the following:

  1. Click the Tools then Options command. This displays the options Dialog box.
  2. On the general tab, select the recently used file list check box as Shown in Figure 1.11.

 

Protecting a document with a password

A password is a combination of characters that prevents other users from opening and changing a document without permission. If a document is protected by a password, only the person who knows the password can open the document or edit it.

 

To save a document with a password

  1. Create or open the document you want to protect
  2. From the file menu, choose Save As.
  3. Click the down arrow on the Tools button in the save as dialog box
  4. Click General options.
  5. Type in a password in the password to open. This prompts the user to enter password when opening a document.
  6. Type in a password in the password to modify. This prevents the user from making changes to a document unless the user enters the correct password.
  7. Finally click OK.

 

Closing a document

Closing a document means unloading the current active document from memory so that the user can create or open another without necessarily exiting from Word.

To close a document:

  1. Click the File menu.
  2. Choose Close.

 

Exiting from Word

  1. To exit from Word, make sure all open documents are saved.
  2. Click File menu,
  3. Click Exit command.

 

NB: You can exit from Microsoft Word by pressing Alt + F4 keys or by double clicking the application icon at the left most comer of the title bar. If you have not saved any of the open documents, Microsoft Word prompts you to save the document first.

 

1.4

Editing and formatting a document

 

Editing

Editing refers to making necessary changes to an existing document. Apart from manual editing using delete, insert and overtype/overwrite commands, Microsoft Word provides the user with inbuilt tools such as the spelling and grammar checker, thesaurus, undo and re-do, find and replace etc.

 

Block operations

 

Selecting (highlighting) a block of text

The purpose of selecting text is to enable the user perform a number of editing or formatting operations on the selected block of text. Microsoft Word presents the user with a number of ways for selecting a block of text. You can either select a block of text using the mouse or keyboard.

 

  Selecting with a mouse

  1. To select a word, place the insertion pointer on the word then, double Click it.
  2. To select a sentence, positions the mouse pointer at the left margin until it changes to a right arrow, and then click once.
  3. To select a paragraph, place the pointer at the beginning or end of the paragraph. Notice that the pointer changes to I-beam. Now drag the I-beam over the text to be selected and release the mouse button at the end of the text you wish to work on.

 

Selecting with the keyboard

  1. To select one word, move the insertion pointer to the beginning or End of the word then press Shift+Ctrl+Right or left arrow.
  1. To select one line, press Shift+Up or Shift+Down arrow key. Alternatively, move the insertion point to the end or beginning of The line then press Shift+Home or end keys respectively.

3.To select an entire page; press Shift+Page Down or Shift+Page Up. 4. To select the entire document, press Ctrl+A or place the cursor at the beginning of the document then press Shift+Ctrl+End.

 

Deleting text

  1. To delete a character or a word from the right to the left, place the insertion pointer on the right of the word then press the backspace key.
  2. To delete a character to the right of the cursor position, place the Insertion pointer on the left of the word then press the Delete key.

 

To delete a block of text

  1. Highlight the text to be deleted.
  2. Press the Delete key.

 

Restoring deleted text

To restore text that has just been deleted in the current word processing session: click the Edit menu, then the Undo command

 

Copying and moving text and objects

Copying means creating a duplicate of text or an object while moving means changing the position of text or an object in a document. In Microsoft Word, you can copy or move a block of text.

To copy a block of text:

  1. Highlight the text,
  2. Click Edit, then Copy or simply click the Copy button on the standard Toolbar.
  3. Position the insertion pointer where you want to copy the text,
  4. Click Edit then Paste or simply click the Paste button on the standard toolbar.

 

NB: To use the keyboard shortcut keys, press Ctrl + C to copy, then Ctrl + V to paste

 

To move text and objects

  1. Highlight the text,
  2. Click Edit, then Cut or simply click the Cut button (whose icon is a Pair of scissors) from the standard toolbar.
  3. Position the insertion pointer where you want the text to be placed,
  4. Click Edit then Paste or click the Paste button on the standard toolbar.

 

NB: To use the keyboard shortcut keys, press Ctrl + X to cut, then Ctrl + V to paste

Typing modes

There are two typing modes in a word processor that assist the user in typing or editing text documents. These are:

  1. Insert mode.
  2. Overtype/typeover mode.

 

Insert mode

This is the default mode in most word processors. In this case when text is inserted between words or characters it pushes the existing text away without replacing it.

 

Typeover mode.

In this case, when text is typed between existing words or characters, the new text automatically replaces the existing text by deleting it. To switch between typeover and insert mode, simply press the insert key on the keyboard or double click the OVR label on the status bar.

 

Find and replace

When you need to search for a word or phrase in a large document, use the Find command. In case you wish to replace a word or phrase, use the Replace option.

 

Find

  1. Click Edit menu, then click Find command. The find dialog box appears.
  2.  Type the text or phrase you want to search for then click FindNext
  3.  Step 2 can be repeated if you wish to find other occurrences of the same word or phrase. Click OK when a message appears telling you that Microsoft Word has finished searching the document. Click Cancel to close the dialog box.

 

NB: You can use the keyboard shortcut Ctrl+F to find. Some search options:

 

You can specify search options by clicking the more buttons to display them. They include:

  1. Match case: This identifies only text that matches in case with that in the find what box e.g. it will not find the word DEEN if you typed deen and selected the match case option.
  2. Whole Word: Searches for a word or phrase that is whole. If it is part of another word it will not be found, e.g. the word ever will not be found in words like however, whenever etc. during the search.
  3. Use wildcards: Wildcards are special symbols such as * and? That are used to represent a set of words with certain characters in common e.g. names like Jeff, Joe, Jane can be represented using a wildcard as J* which means all names starting with J.
  4. Like: Searches for words, which are similar in pronunciation e.g., fare and fair.

 

Replace command

Click Edit menu then Replace command. The dialog box appears.

 

Type the name you want to replace in the Find what box and the one that will replace it in the Replace with box. Click the Find next button to find the next occurrence of the word then click Replace button to replace it. To replace all the occurrences of the word in the document at once, click the Replace all button.

Proofreading

Proofreading refers to checking whether the document has typographical or grammar errors. Microsoft Word has tools for proofreading e.g. spelling and grammar checker, Thesaurus, Autocomplete and Autocorrect.

 

Spelling and grammar checker

The spelling and grammar checker is an inbuilt tool that helps the user to correct spelling errors and incorrect grammar structures. However, the checker can only recognise errors of those words whose correct spelling is in its dictionaries. A correctly spelt word used wrongly cannot be detected hence the document should be proofread just before and after printing. To check the accuracy of spelling and grammar:

  1. Click Tools menu option.
  2. Click Spelling and grammar on the drop down menu. The spelling

And grammar checker dialog box appears as shown in Figure 1.14.

Words that do not match in the custom dictionary are highlighted for correction. The lower plane of the dialog box suggests to the user with a list of suggested correct words.

  1. Either choose one of the following buttons:

(a) Change to correct only the highlighted incorrect word.

(b) Change all to correct all the occurrences of the misspelled word.

(c) Ignore to retain the highlighted and continue. For example, although a word like jembe may not be in the custom dictionary, in the Kenyan context, the word is acceptable therefore if highlighted, click Ignore.

(d) Ignore all to retain all the occurrences of the same word or phrase in the document from another language e.g. a Kiswahili

(e) Click Add to add the word into the custom dictionary.

 

In case you want to undo the changes made, click on the Undo button at the lower bottom of the spelling and grammar dialog box.

 

NB: You can close the spelling and grammar dialog box even if the process is not complete by choosing Close.

 

Using the thesaurus

This is an editing tool that helps the user find words or phrases with similar meaning (synonyms) or opposite meaning (antonyms) to the one selected.

To use the Thesaurus:

 

  1. Select a word or a phrase.
  2. Click Tools, and then point to Language.
  3. Click Thesaurus to see Figure 1.15 displayed on the screen.
  4. For synonyms, under the heading Replace with Synonym, choose an alternative word phrase you intend to use as replacement for the selected text.
  5. To replace a word or a phrase with an antonym, select the word or phrase with antonym enclosed in brackets.
  6. Click Replace.

 

Autocomplete The auto complete feature displays a complete word when the user types the first few characters of the word. This enables the user to type faster by simply accepting the suggested word if indeed he/she intend to type it. To accept the suggestion, simply press the Enter key, and continue typing other word or phrases

The figure shows an auto text that automatically completes Dear sir or Madam text entries.

 

To turn auto complete on/off

  1. Click Insert menu and point to Auto text. A dropdown list is displayed.
  2. Click AutoText.
  3. Select or clear the Show AutoComplete tip for AutoText and dates Check box
  4. Type in an Auto text in the Enter AutoText entries here text box then Click Add.
  5. Click Close.

Autocorrect

The auto correct feature automatically detects wrongly spelled or capitalised words and replaces them with the correct word. However, the settings of auto correct are user defined e.g. if a person keeps on typing the word certain as certain, set the auto correct feature to replace the later with the former. Figure 1.18 shows the auto correct feature.

 

To turn auto correct on/off

  1. Click Tools menu, then AutoCorrect.
  2. To turn on the spelling checker corrections, select the Replace text as you type check box, and then select the Automatically use suggestions from the spelling checker check box.
  3. To turn off the spelling checker corrections, click Automatically use suggestions from the spelling checker check Box at the bottom of the dialog box
  4. Click OK to close the dialog box.

Undo and redo

Undo: It reverses the last command that was issued in Order to revert back to the previous state. To undo, click Edit then Undo command.

Redo: It does the last undone action. To redo, click Edit, then Redo Command.

 

Formatting a document

Formatting refers to applying various styles or features to enhance the document’s appearance. You can format text, a paragraph or a page.

Text formatting

Text formatting refers to features such as changing fonts (type, style and size of characters), changing text color, underlining, bolding Italicising etc. You can use either the formatting tools bar or the Format menu to underline, bold, etc.

 

To format existing text using the format menu

  1. Highlight the text to be formatted
  2. From Format menu, click the Font command. A dialog box with all Text formatting features is displayed
  3. To change font type and size, where necessary scroll down the Font list box then click the font required, for example Verdana font style would appears as Verdana. To increase the font size, where necessary, scroll down the Size list box and select the required size e.g. 12 points (pt). A point is 1/72 of an inch in height. 72 points i.e. 72/72 is equivalent to 1 inch For example “Verdana” is in Times New Roman 16 points and “Verdana” is in Verdana 16 points.
  4. Bolding text: Bolding makes the selected text appear darker than the rest of the text. To bold text:
  • Activate the font dialog box.
  • From the font dialog box, select Bold.
  1. Underline text: Underlining refers to placing a line at the base or bottom of a word or a phrase. To underline:

(a) Activate the font dialog box.

(b) Click the down arrow at the right of Underline style and select. The underline style required e.g. single, double, dashed etc.

  1. Italicising text: To italicise is to make the text slant forward.

(a) To italicise activate the font dialog box.

(b) Click Italic.

  1. Changing the font color: In most cases, the font default color is black. However you can change the font color for example to red, green, blue etc. To change the font color,

(a) Activate the font dialog box

(b) Click the down arrow at the right of font color list box and

Select the color of your choice.

 

Using formatting toolbar

As mentioned earlier, the formatting toolbar lets the user easily format text by clicking the required format button. To format some text, highlight it first then click a command on the toolbar.

For example to bold text, highlight it then click then bolding command (B) on the formatting toolbar.

 

Paragraph formatting

 

Text alignment

Text alignment refers to how text is lined up on the page relative to the left, right or center of the page. There are four ways in which text can be aligned namely left aligned, centered, right aligned and justified.

 

Left alignment

Lines of text are lined up evenly along the left margin but unevenly at The right margin. This is the default alignment. To align left,

  1. Highlight your text.
  2. Simply click the left alignment button. Alternatively click format, Paragraph. And select left from the alignment list box as shown in Figure 1.20.
  3. Click OK. To apply the choice.

 

Right alignment

This is opposite of left alignment. Lines of text are lined up evenly along the right margin but unevenly at the left margin. To align right,

  1. Highlight your text
  2. Simply click the right alignment button. Alternatively click Format, Paragraph. select Rigl1t from alignment list box, then click OK..

Center alignment

The lines of text are centered unevenly between the left and right margins.

To center text,

 

  1. Highlight your text,
  2. Simply click the Center, button. Alternatively click format, paragraph,

Select centered from alignment list box, then click OK.

Justification

Lines of text are arranged evenly along the left and right margin.

To justify text,

  1. Highlight your text
  2. Simply click the Justify alignment button. Alternatively click Format,

Paragraph, select Justify from Alignment list box, then click OK.

 

Change case

When typing a text, there are a number of cases the user may intend to apply in order to create contrast within the text. These are:

  1. Sentence case: All the first characters in a sentence are in uppercase (Capitalised).
  2. Lowercase: All characters appear in lowercase.
  3. Uppercase: All characters appear in uppercase.
  4. Title case: All the first characters of each word in a sentence appear in uppercase.
  5. Toggle case: It changes upper cases to lowercases and vice versa.

 

Figure 1.21 shows a dialog box for change case.

 

To change case in an existing text;

  1. Highlight the text.
  2. From the format menu, click Change case.
  3. From change case dialog box, select the case type to be applied.
  4. Click OK.

Drop caps

There are times when you wish to attract the reader’s attention by making the first character in a sentence large, taking more space in the next line. Such kind of a character is said to be “dropped”.

To apply drop cap;

  1. Highlight the first character in the sentence
  2. From the Format menu, click Drop Cap. Drop cap dialog box appears
  3. Click Dropped or In Margin
  4. Select font in case you wish to apply a certain font to the dropped Cap
  5. Specify the number of lines to drop.
  6. Click OK

Indenting paragraphs

Indentation refers to moving the text away from the margin. You can indent the first sentence in a paragraph (first line), the whole paragraph (full indent) or the rest of the text except the first line (hanging indentations).

First line indent

  1. Select the paragraph to be indented
  2. From the format menu click paragraph. Paragraph properties dialog box appears
  3. Click the down arrow in the list box under Special and select First Line.
  1. Specify by how far the paragraph is to be indented from the margin

In the by text box

Click OK to apply the indent and close the dialog box. The paragraph will be indented

NB: You can also indent the first line by positioning the cursor at the beginning of the paragraph then press the Tab key.

Hanging Indent

  1. Select the paragraph to be indented
  2. From format menu, click Paragraph.
  3. Click the down arrow in the list box under Special and select Hanging. 4. Specify by how far the paragraph is to be indented from the margin In the by text box
  4. Click OK to apply the indent and close the dialog box. The paragraph will be indented

Full indent                     ­

  1. Select the paragraph to be indented or position the cursor anywhere in the paragraph
  2. From the formatting tool bars, click the Increase or Decrease indent Button

Setting tabs

Tabs are used to indent the first line of a paragraph or create columnar data. By default the tab stop is set at 0.5 of an inch. To change the default setting:

  1. From the format menu, click Tabs
  2. Enter a new value for tab stop in the Tab stop Position box.
  3. Choose the type of tab either left, center or right.
  1. If need be specify the Tab leader option
  2. Click the Set button then OK.

Setting tabs using the ruler

The easiest way to set tabs is by using the ruler. On the left comer of the horizontal ruler is a tab alignment button that lets the user select the type of tab. Figure 1.28 shows various tab alignment buttons, while Table 1.1 gives an explanation of each button.

To set the tab using the ruler;

  1. Click on the tab button to choose the required tab type. Notice that the tab type keeps on changing as you click the tab button.
  2. Set the tab stop by clicking where you want it to be on the ruler.
  3. Drag the tab stop

 

Button Name Purpose
Left tab Text is left aligned
Center tab Text is centered
Bar tab Inserts a vertical line at
    Tab stop and align text to
    The right of the line
. Decimal tab Text is aligned at decimal
  Character
Right tab Text is right aligned

 

Table 1.1 Examples of tabs

 

Line and character spacing

Line spacing refers to the vertical distance between lines of text. The default line spacing is single spacing. This type of spacing accommodates the characters in a text leaving a small extra space between lines. Character spacing on the other hand refers to the space between the characters in the text.

 

To change line spacing:

  1. Highlight the text,
  2. From format menu, click Paragraph to display the paragraph dialog Box.
  3. Click the down arrow from the Line Spacing list box and select the Type of spacing required e.g. double, 1.5, at least etc.
  4. Click OK to effect the changes. To change character spacing:
  5. Highlight the text
  6. From Format menu, click Font.
  7. Click the Character Spacing tab
  8. Adjust the spacing as required
  9. Click OK.

Bullets and numbering

Bullets and numbers are used to mark steps in a procedure or items in a list.

To apply bullets and numbers in a list:

  1. Select the list.
  2. From the Format menu, click Bullets and numbering. A dialog box appears.
  3. Do one of the following;

(a) To apply bullets, click the Bulleted tab.

(b) To apply independent numbers click the Numbered tab.

(c) To apply outlined numbered list, click Outline Numbered. Tab

  1. Click OK to effect the changes and close the dialog box.

 

Section breaks

A break is used to identify where a section, a column or a page ends and the beginning of next. This allows the user to apply more than one paragraph or page format in the same document especially when it comes to page layout, size, different margins etc.

 

To insert a section break

  1. Position the text cursor in the document where the break is to be inserted.
  2. Click Insert then. Break.
  1. From the Break dialog box select the type of section break to insert e.g. page break.
  1. Click OK.

 

Formatting pages

Inserting page breaks

A page break identifies the end of one page and the beginning of the next. NofQ1ally, Word automatically inserts a new page after the current. One is full. However, there may be a need to start a new page even if the. Current one is not full.

 

To insert page breaks:

  1. Position the pointer where the break is to be inserted.
  2. Click Insert then Break.
  3. From the Break dialog box
  4.  Click Page break then OK.

 

Creating columns

To, create columns on existing text:

  1. Highlight the text
  2. From Format menu, click Columns to display the dialog box
  3. In the columns dialog box, select the number of columns or type in the Number of columns text box
  4. In the Width and spacing boxes, specify the column widths and space between columns
  5. Click OK

Page setup

Page setup options let the user specify the size of the margins, paper size, paper source and layout.

 

Setting margins

Margins are blank spaces around the edges of the page. Only text and objects inside the margins are printable.

 

To set up margins:

  1. Click the File menu then Page setup. Page setup dialog box appears
  2. Click the Margins tab.
  3. Enter the values for the left, right, top and bottom margins in the respective boxes.
  4. Click OK.

 

Setting the paper size

By default, the paper size may be either Letter or A4. An A4 paper has dimensions 210 mm x 297 mm

 

To specify a different paper size

  1. From the File menu click Page setup
  2. In the page setup dialog box click the Paper size tab.
  3. Select the size of paper required from the paper size list. If your size is different from the ones provided, click Custom size and enter dimensions in the height and width boxes.
  4. Click OK.

Specifying page orientation

The term page orientation refers to the positioning of the page in relation to the text. The two available orientations are:

Portrait: text and graphics are printed with the longest side vertically upright. For example, on an A4 piece of paper, the 210 mm edges are at the bottom and top.

 

Landscape: With landscape, text and graphical objects are placed with the longest side of the page placed horizontally and the lines of text printed parallel. For example, to create a timetable on an A4 page, the 297 mm side should be horizontal.

 

To select the orientation:

  1. From File menu, choose Page setup.
  2. Click on the Paper size tab and a dialog box comes on the screen.
  3. Select the orientation required then clicks the OK button.

 

Page layout

This option lets the user specify how text will be placed on the page from the margins. By default, text starts from the top margin.

 

To change the layout

  1. From File menu, choose Page setup. The dialog box Appears.
  2. Click on the Layout tab.
  3. From the Vertical alignment tab, select the alignment required then click OK.

 

Inserting headers and footers

Headers, footers and page numbers make it easy to locate information. Headers are few words placed at the top of every page while footers appear at the bottom. To insert headers and footers:

  1. Click on the. Headers and Footers from the View menu
  2. In the text boxes that appear, type a header using the top text box or a footer using the bottom text box or even both if you are to insert both a header and footer.

Inserting page numbers

To give your document page numbers:

  1. From the Insert menu, click Page numbers to display the dialog box
  2. In the Position box, specify where you want the page numbers to be inserted.
  3. In the alignment box, specify whether the number is to be on the right, left, center, inside or outside
  4. Use the Format button to choose the number format, i.e. 1,2,3,…, A,B, C etc. You can start from any page number by using Start at box

 

Creating and editing tables

 

Creating tables

A table is a feature in Microsoft Word made up of rows and columns that is used to organise and enhance display of information.

 

Creating a new table

. .

You can create a table either by using the Insert Table command from tables menu, or by using Draw Table tool that resembles a pencil to create more complex tables.

 

To create a table using the insert table command;

  1. Click Tables menu, position the pointer on Insert, then click Table
  2. In the Insert table dialog box displayed, specify the number of rows and columns.
  3. Click OK. The table will be displayed on the screen and you can start entering data in it.

NB: You can insert a table by clicking the table button on the standard toolbar, then drag to select the number of rows and columns.

 

To create a table using the drawing tool:

  1. Click Tables menu, then Draw table or simply click the Draw table button from the standard toolbar. The mouse pointer changes to a pencil symbol
  2. Drag the pointer to draw the outline of the table
  3. Fill in the table with rows and columns by dragging the pointer as you would draw using an ordinary pencil.

 

Formatting and editing a table

 

Inserting rows and columns

To insert a row:

  1. Place the cursor where you want to insert a row
  2. Click Table, point Insert then click Row above or Row below.

 

To insert a column:

  1. Place the cursor where you want to insert a column
  2. Click Table, point Insert then click Column to left then Column to the Right.

 

Adjusting the column width:

  1. Position the mouse pointer on the row or column boundary until the mouse pointer changes to an arrowed cross.
  2. Drag the boundary to the required size.

 

Deleting rows, column or cells

  1. Select the rows or columns to be deleted.
  2. From Table menu, point Delete, then Columns, Rows or Cells.

 

Merging cells in a table

This refers to combining more than one cell in a table. To merge cells:

  1. Select cells to be merged
  2. From Tables, click Merge cells.

 

Splitting cells in a table

This refers to subdividing a cell or cells into more cells. To split cells:

  1. Select cells to be split
  2. From Tables, click Split cells. A dialog box appears that lets you specify the number of rows and columns that the selected cells will be split.

 

Formatting table borders and shading

Word provides the user with automatic formatting feature that lets you choose border styles and shading.

 

To format a table:

  1. From Table menu, click Table AutoFormat.
  2. In the formats list box, select the format you want. Note that the format you choose applies to borders, shading font and colour.
  3. Click Ok to apply the effects.

NB: You can also format a table by using the table’s toolbar. If the toolbar is not displayed, click view point to toolbars then click tables and Borders.

 

 

Table conversions

With convert feature in Microsoft Word, you can convert a table to lines of text and vice versa.

 

To convert a table to text

  1. Select the entire table or row and columns you want to convert to text.
  2. From table menu, point to convert then click table to text. A dialog box is displayed that requires you to specify how the text will be separated after conversion
  3. In the separate text with box enter or select the character to be used as a separator.
  4. Click ok

 

To convert text to table:

  1. Select the text that you want to convert to a table.
  2. From table menu, point convert then click text to table .A dialog box is displayed that requires you to specify the number of rows and of columns
  3. From Separate text at, specify whether the table will be defined by paragraphs, commas, Tabs or other characters.
  4. Click OK. .

 

Importing tables

Microsoft Word lets you import tables from other applications or an existing file. To import a table,

  1. Click the Insert menu then Objects. A dialog box appears
  2. From the Object type select the type of object to insert e.g. Adobe table.
  3. The program in which the table was created in starts and lets you choose a table from it and return back to Microsoft Word. Alternatively click Create from file. This lets you browse for a file that contains the table you wish to insert.
  4. Click OK to insert the table.

 

Performing arithmetic calculations in a table

It is possible to perform mathematical calculations such as sum, product and count, if a table has numerical figures.

 

To perform calculations:

  1. Click the cell in which you want the result to be placed.
  2. From the Table menu, click Formula. A formula dialog box is displayed.
  3. Type the formula you want or select from the Paste function box. For example, to add figures in a row or column, click SUM. The function in Table 1.2 below that calculates the total is =SUM(ABOVE). The word “ABOVE”. in brackets is called the argument of the formula and tells Microsoft Word which cells in the table are to be worked on.

Sorting

In Microsoft Word you can sort a list of text, numbers and dates in ascending or descending order.

To sort a list or table:

 

  1. Highlight the text list or table you want to sort.
  2. From the Table menu, click Son.
  3. Select the type of data to be used when sorting i.e. Text, Number or Date.
  4. Click either Ascending or decending
  5. Click OK.

 

Mail merge document

Mail merge is the process of generating personalised letters or documents by combining a main document, e.g. a letter, with an existing data source such as the address book. Therefore in mail merge, the three files created are:

  1. The primary file (main document)
  2. The secondary file (Data source)
  3. Merged file

To create the main document,

 

1 From the file menu, select New to create a new document. You can also open or retrieve an existing document.

  1. On the Tools menu, click mail merge to display a dialog box.

3 Click create button, to select the type of document needed e.g. form .letters. Select the active window as the main document this means that the currently running document will be the form letter that will be later merged with a data source to produce individualised letters.

The next step is now to create a data source.

  1. Click Get Data. To use an existing list of names and addresses, click

Open Data. Source To use existing addresses from an electronic address book, click on Use Address Book. To create a new list of names and addresses, first choose the necessary fields from the create data source box then save the record structure. A message appears asking you whether you want to edit the data source or the main document choose one then the Next.

  1. With the main document open, spot the mail merge toolbar on the screen. Position the text cursor where you want to insert merge fields. Use the insert field’s button to insert merge fields in the document

Merging the document

Once you finish inserting merge fields from the data source in the main document, you are now ready to merge. There are several merge options:

 

To merge to a new document

Click the Merge to new document icon on the mail merge toolbar.

 

Merging to printer

Click the .Merge to printer, icon on the mail merge toolbar. Before you merge to a printer or other device, you may want to preview the appearance of the merged documents. For example, you can preview the merged documents one at a time. You can also collect the merged documents into a new document, so you can review and personalise the documents.

 

Preview merged documents

Before you print the documents, ensure that you’ve inserted merge fields in the main document and selected a data source. To preview, click anywhere in the main document, and then click View Merged Data on the Mail Merge toolbar.

 

Microsoft Word displays information from the first data record in place of the merge fields.

 

Send merged documents via e-mail or fax

Click the merge button on the Mail merge toolbar Select e-mail or fax in the merge to box. Click the Setup button to specify the e-mail addresses or faxing number then click the merge button. The internet connection wizard starts and if your computer is properly configured, the mail merged document will be sent.

Inserting graphics

 

Working with graphics

The term graphics refers to non-text images generated by a compute! This includes photographs, drawings and graphs. Graphics present information in a form that is easy to understand.

 

You can insert a graphical object from Microsoft Clip Gallery, a scanner or by using drawing tools available in Microsoft Word.

 

Inserting a clip art or a picture from clip gallery:

  1. Position the insertion pointer where you want your object to be inserted,
  2. On the insert menu, point to picture then click clipart Click on the tabs to select on the category of objects i.e. clip art, pictures, sound or videos. See Figure 1.42.
  3. Double click on the object you want or click it once then click the insert button.
  4. Use the object place holders to resize your object. If you place the mouse pointer on one of these holders, it turns into a two headed arrow, hold down the mouse button and drag to increase or reduce the object size
  5. Click anywhere outside the object to remove the holders.
  6. To move you object to another position, click inside the object. The pointer turns into an arrowhead cross. Hold down the mouse button and drag your image to a new location.

Fig. 1.42: A clip art image

Inserting an image from a scanner

The computer must be connected to a scanner to complete this procedure. A scanner is a data capture device that transforms a hand copy or real graphical object into digital form.

 

To scan an object:

  1. Position the insertion pointer where you want your picture to appear,
  2. from the insert menu, point to Picture and then click from scanner or Camera.
  3. To scan, follow the instructions that come with your scanner.
  4. When the image appears on the screen you can edit and format it as required the same way you would with a clipart.

 

Inserting a picture from another file

  1. Position the insertion pointer where you want your picture  placed,
  2.  From the insert menu, point to Picture, then click “From file
  1. Locate the file that contain the image you want to insert eg from your floppy disk, from a compact disk etc.
  2. Select the object you want to insert

5 Then click the Insert button.

6 When the image appears on the screen you can edit and format it as required the same way you would with a clipart.

 

Editing and formatting pictures

 

To format or edit a picture:

Microsoft Word provides the user with a picture editing toolbar that lets you adjust the brightness, contrast, change it to black and white or grayscale and crop the image. Cropping refers to hiding the unwanted details so that they do not come out when printing.

 

To display the picture toolbar, click on View menu, point to toolbars then select Picture. The picture toolbar has buttons that enable a person to format a picture to format a picture, click it to select it then use the commands on the picture toolbar.

 

Drawing an object using MS Word drawing tools

Microsoft Word provides the user with basic drawing tools such as polygons, lines, a circle, stars and banners, call outs and many others. If the drawings toolbar is not displayed, click on View menu, toolbars then click on Drawing. The toolbar will be displayed which a button has labeled Auto shapes, an arrow, a line, square and a circle

 

To draw a line, a circle an arrow or a rectangle:

  1. Click on the appropriate shape button. The pointer changes to a plus sign.
  2. Place the pointer where you want to draw that shape and drag to the required size.

 

To draw an object using the Auto shapes:

  1. Click the Auto shapes button. A menu is displayed showing categories of shapes you can choose from
  2. Point to the category required then select the type of object you wish to draw
  3. Place the pointer where you want to draw that shape and drag to the required size.

 

Editing and formatting a drawn object

You can resize, move, fill color and change the drawing outline.

 

To resize or move a drawing.

  1. Click anywhere inside it. The place holders appear.
  2. To move it, hold down the mouse button and drag.
  3. To resize it, place the pointer at one of the place holders and drag.

 

To fill the object with color and fill effects:

1    Click the object. The place holders appear.

2    Click the down arrow of fill color button, the one that looks like a bucket pouring ink.

3 Select the color you want applied. To fill the drawing with texture, gradient or pattern, click the Effects button. From the resulting dialog box, select the appropriate fill effect.

Printing a document

 

Printing in Microsoft Word

Because the main purpose of any word processor is to prepare documents for printing, this cannot be accomplished without a printer. The choice of a printer depends on the quality of hardcopy desired. Before you print, it is very important that you preview you document to confirm that no details are outside the printable area and that the document layout is okay.

 

Using print preview

In Microsoft Word, to view your document before printing proceed as follows:

  1. From file menu, select print preview the mouse pointer changes into a symbol that resembles a magnifying glass. You can click on the mouse button inside the document to increase or reduce the size of the view.
  2. Click the close button or Esc key to return to your document.

 

To print:

 

  1. From file menu click on print A dialog box appears where you can specify:
  • The type of the printer installed in your computer other than the default printer.
  • Whether to print the whole document or a range in the Page range box,

(c) Number of copies to print per page in the Number of copies box then,

  1. Click OK to start printing.

 

SPREADSHEETS MS-EXCEL

 

Chapter outline

 

2.1 Definition of spreadsheet

2.2 Components of a spreadsheet

2.3 Application areas of a spreadsheet

2.4 Creating a worksheet/workbook using Microsoft Excel

2.5 Cell data types

  1. Cell referencing
  2. 7 Basic functions and formulae

2.8 Editing a worksheet

2.9 Worksheet formattin2.10 Data management

2.11 Charts/graphs

2.12 Printing worksheets

 

2.1 Definition of a spreadsheet

A spreadsheet is essentially a ledger sheet that lets you enter, edit and manipulate numeric data. There are two types of spreadsheets namely:

  1. The manual spreadsheet.
  2. The electronic spreadsheet.

A manual spreadsheet is the most commonly used type by book keepers as a ledger book with many sheets of papers divided into rows and columns on which various amounts of money are entered manually using a pen or pencil. You can visit your bursar’s office and request to see a ledger sheet.

 

An electronic spreadsheet on the other hand is prepared using a computer program that enables the user to enter values in rows and columns similar to the ones of the manual spreadsheet and to manipulate them mathematically using formulae.         ‘

 

In this book, the word spreadsheet shall be used to refer to the electronic spreadsheet. ‘.

Advantages of Using Electronic Spreadsheets over Manual Spreadsheet

 

  1. The electronic spreadsheet utilizes the powerful aspects of the computer like speed, accuracy and efficiency to enable the user quickly accomplish tasks.
  2. The electronic spreadsheet offers a larger virtual sheet for data entry and manipulation. For example the largest paper ledger you can get is one that does not exceed 30 columns and 51 rows while with an electronic spreadsheet, the least ledger has at least 255 columns and 255 rows!
  3. The electronic spreadsheet utilizes the large storage space on computer storage devices to save and retrieve documents.
  4. The electronic spreadsheet enables the user to produce neat work because the traditional paper, pencil, rubber and calculator are put aside. All the work is edited on the screen and a final clean copy is printed. With a handwritten spreadsheet, neatness and legibility depends on the writer’s hand writing skills.
  5. Electronic spreadsheets have better document formatting capabilities. 6. Electronic spreadsheets have inbuilt formulae called functions that enable the user to quickly manipulate mathematical data.
  6. An electronic spreadsheet automatically adjusts the result of a formula if the values in worksheet are changed. This is called the automatic recalculation feature. For a manual sheet, changing one value means rubbing the result and writing the correct one again.

 

Examples of spreadsheets

  1. VisiCalc: This was the first type of spreadsheet to be developed for personal computers.
  2. Lotus 1-2-3: This is integrated software with spreadsheet module graphs and database. 3. Microsoft Excel
  3. VP-Planner etc.

In this book, the spreadsheet that will be considered in details is Microsoft Excel.

Components of a spreadsheet

A spreadsheet has three components  ­

  1. Worksheet. /
  2. Database.
  3. Graphs.

Worksheet

This is the component in which data values are entered. It is made up of rows and columns. The intersection between a row and a column is called a cell. A row is a horizontal arrangement of cells while a column is a vertical arrangement of cells. Each row is labeled with a number while each column is labeled with a letter as shown in the Figure 2.1. Each cell is referenced using the column label followed by the row label e.g. cell B3 has the value 20. A group of many worksheets make up a workbook.

 

A             B       C          D        E         F

1                      
2                      
3   20                  
4                      
5       I              

 

Fig. 2.1: A Worksheet

 

Database

Data values can be entered in the cells of the spreadsheet and managed by special Excel features found on the Data menu. These features were incorporated in Excel but they actually belong to database management software. One of such feature is filtering records, using forms, calculating subtotals, data validation pivot tables and pivot chart reports.

 

If the data values for the same entity (related values) are entered on the same row, they form a record. Hence a worksheet can be manipulated to some extent as a database that has data records entered in it. Figure 2.2 shows a worksheet having two records, Joy and Jeff.

 

A              B             c           D           EF1

      1 Name IDNo. Age Nationality
      2 Joy 123445 25 Kenyan
      3 Jeff 125675 35 Ugandan
      4        

 

Fig. 2.2: A spreadsheet with records

 

NB: A spreadsheet file is structured in such a way that it can be visualised as a table of records. That is why such a ‘file can be imported into a database program as will be discusses later in databases.

 

Graphs

A graph is a pictorial representation of the base data on a worksheet. Most spreadsheets refer to graphs as charts. A chart enables the user to present complex data elements from a worksheet in a simple easy to understand format. Examples of charts are pie charts, line charts and bar charts. As shall be discussed later, it is easy to generate charts when working with a spreadsheet program. Figure 2.3 shows an example of a pie chart.

 

2.3 Application areas of a spreadsheet

 

Statistical analysis

Spreadsheets provide a set of data analysis tools that can be used to save steps when developing complex statistical or engineering analyses. The user is usually expected to provide the appropriate data and parameters for each analysis. The statistical tool then uses appropriate automated statistical or engineering functions and then displays results in an output table. Some of the tools generate charts in addition to the output tables.

 

Because most of these tools are complex, the user needs to have the statistical background knowledge before attempting to use the tools. Examples of some simple statistical functions include the following:

  1. Average: This is used to calculate the mean of a set of values.
  2. Median: This is used to return the value in the middle of a set of values.

 

For example a set of values may be composed of:

 

10   20    30   40    50     60.

 

The average of the set is 35 and its median is also 35. The median is found by taking the average of the two numbers at the centre of the set, in this case 30 and 40.

 

Accounting

Many accountants find the spreadsheet a useful tool to use in recording daily transactions and keeping of financial records. Spreadsheets provide a user friendly environment for financial management and they come with inbuilt functions that make accounting tasks easier. For example, the spreadsheet can be used by accountants to do the following:

  1. To track the value of assets over time (depreciation and appreciation)
  2. To calculate profits
  3. To prepare budgets

 

Other formula like sum, average, product etc. enables the accountant to carry out his daily work without any problem.

 

Data management

A spreadsheet enables neat arrangement of data into tabular structure. Related data can be typed on the same worksheet. However, when data is on different worksheets, the worksheets can be linked to enhance accessibility.

 

Data management functions include sorting, filtering (displaying only the required items) and using forms to enter and view records.

 

Spreadsheets enable the user to create, edit, save, retrieve and print worksheet data and records.

 

Forecasting (“What if” analysis)

The automatic recalculation feature enables the use of “What if’ analysis technique. This involves changing the value of one of the arguments in a formula to see the difference the change would make on the result of the calculation. For example, a formula to calculate a company’s profit, margin may be as follows:

 

Profit =, (Total units sold x sale price) – (Total units bought x cost price) – Operating ‘expenses.

A sales manager in the company c n ask the following question: What if sales increase by 20%, how much profit wills the company make? The manager substitutes the total units sold value with one that is 20% higher and the spreadsheet automatically displays the new profit. A traditional analysis method would require a different work sheet to be prepared. Therefore, this method can be used for financial forecasting, budgeting, stock portfolio analysis, cost analysis, cash flow etc.

Creating a worksheet/workbook using Microsoft Excel

To start Microsoft Excel, click Start button, point to Programs and then select Microsoft Excel from the programs menu This procedure may vary slightly depending on the version of Excel you are using or the computer’s hardware and software configuration.

The Windows environment allows a person to place shortcuts to a program’s executable (.exe) file in various places like the desktop. If the Excel shortcut is on the desktop, simply double click it to start the application.

 

The Microsoft Excel application window opens as shown in the Figure 2.5. Make sure that you can be able to identify all the labeled parts of the Microsoft Excel application window.

 

The Microsoft Excel application window

The Microsoft Excel application window is made up of the following components:

Title bar: It has the title of the application and control buttons for minimising, maximising and closing the application

The menu bar: It displays a list of menu options e.g. File, Edit, View etc. Clicking one of them displays a menu that has commands which can be selected in order to manipulate data in the spreadsheet.      ‘

Tool bars: The most common of these are the standard and formatting toolbars. The most important thing is to be able to identify each toolbar by its icons. The standard toolbar has shortcuts to some of the most commonly used menu commands like print, copy, paste and save. The formatting toolbar has shortcuts to the commonly used commands found on the format menu option

Formula bar: This is one of the most important components of the Microsoft Excel application window. It enables the user to enter or edit a formula or data in a cell. You can identify the formula bar because it has an equal sign (or fx). The name box to the left of the formula bar displays the position of the cell in which data or a formula is being entered which is also called the current cell. If the formula bar is not available, click on View menu then select Formula bars. A check mark appears on the left of the selected item to show that it is now displayed on the screen.

Cell pointer: It marks the position of the current cell or the insertion point. It is special cursors that is rectangular in shape and makes the current cell appear as if it has darker boundaries.

The Worksheet: Consists of cells, rows and columns. Data is entered here for manipulation.

Status bar: It shows the processing state of the application. For example, on its left is the word Ready which shows that the spreadsheet is ready to receive user commands.            ‘

 

Worksheet labels: These are usually of the format Sheet 1, Sheet 2 etc. A workbook may have several sheets. It is also possible to rename the sheets by right clicking on the labels then choosing rename command from the shortcut menu that appears. The active sheet (one being used) has its label appearing lighter in colour than the rest. To move to a particular sheet in the workbook, simply click its sheet label.

 

Vertical and horizontal scroll bars: Clicking the arrows at their ends moves the worksheet vertically and horizontally on the screen respectively.

 

Worksheet layout

The worksheet has the following components: Cells: An intersection between a row and a column.

Rows: Horizontal arrangement of cells. Columns: Vertical arrangement of cells.

Range: Is a group of rectangular cells that can be selected and manipulated as a block.

 

Navigating the Microsoft Excel screen

  1. Click cell D5. Notice that the cell pointer immediately moves to the cell and the name box reads D 5. Typing on the keyboard now inserts entries in cell D5 as long as the pointer is still there.
  2. Click letter A that heads the first column. Notice that the whole column is highlighted.
  3. Double click cell EIO. Notice that the text cursor forms in the cell and you can now type characters inside the cell. Also the status bar will now read enter which means that Microsoft Excel expects you to enter a value in the cell.
  4. Click the down arrow on the vertical scroll bar. The worksheet moves upwards on the screen. The opposite happens when you click the up arrow on the vertical scroll bar.
  5. Click the right button on the horizontal scroll bar. The worksheet moves to the left. The opposite happens when you click the left button on the horizontal scroll bar.
  6. Press the right arrow key on the keyboard. Notice that the cell pointer moves one column to the right on the same row. This can also be done by pressing the Tab key once.
  7. Press the left arrow key on the keyboard. Notice that the cell moves one column to the left on the same row. Pressing gives the same results.

 

  1. Press the up arrow key on the keyboard. Notice that the cell pointer moves one row up on the same column.
  2. Press the down arrow key on the keyboard. Notice that the cell pointer moves one row down on the same column.
  3. Press the end key. The status bar will display the message “END”. If you press the right arrow key, the cell pointer will move right to the last cell on the row. If the left up or down keys were to be pressed instead, the cell pointer would move to the last cell to the left, top or bottom respectively.

 

  1. Pressing Ctr1+Home moves the cell pointer to the first cell of the worksheet i.e. cell AI.

 

Creating a worksheet

At its simplest level, creating a worksheet consists of starting the spreadsheet program and entering data in the cells of the current worksheet. , However, a person can decide to create a worksheet either using the general format or from a specially preformatted spreadsheet document called a template.

 

Using the general format

When a spreadsheet program is running it will present the user with a new blank screen of rows and columns. The user can enter data in this worksheet and save it as a newly created worksheet. If this is not available then click File menu option and select the new command. The dialog box shown in Figure 2.8 will be displayed on the screen. On the General tab, double click the workbook icon. Enter data in the new worksheet created.

 

Using a template

Click File menu option then new command. On the spreadsheets solutions tab, double click the template that you wish to create. Figure 2.9 below shows some examples of templates that may be present for selection.

 

NB: If the template was saved previously on the hard disk, it will open as a new worksheet with all the preformatted features present allowing the user to enter some data. However, some templates may require the original program installation disk in order to be able to use them because they may not have been copied to the hard disk during program installation.

 

Editing a cell entry

Editing a cell means changing the contents of the cell. Before the contents in a cell can be. Changed, the cell must be selected by making it the current cell.

To edit a cell entry proceeds as follows:

.1. Move the cell pointer to the cell you wish to edit.

  1. Double click the formula bar for the text cursor to appear in the bar. The status bar message changes to edit
  2. Use the keyboard to delete and add contents to the formula bar then press enter key to apply. Click the save button on the standard toolbar to save the edited changes.

 

Selecting a range

As you have experienced with the previous two examples, working with one item at a time is tedious and time consuming. Using a range saves time when working with a large .amount of data.

 

A range is a rectangular arrangement of cells specified by the address of its top left and bottom right cells, ‘separated by a colon (:) ego Range AI:CIO is as shown in Figure 2.10.

Selecting multiple ranges

When using a mouse, you can select more than one range without removing the highlight from the previous. To do this:

Hold down the Shift key or the Ctrl key while you click on the row header of the second range you want to highlight. What happens? Do you notice the difference when holding down the shift and the ctrl keys?

  1. Shift key will cause all columns/rows between the selected and the newly clicked cell to be highlighted.
  2. Ctrl selects individually clicked cells or range.

 

Hiding rows/columns

You can hide some rows or columns in order to see some details, which do not fit, on the screen. To do this:

  1. Highlight the columns/rows you want to hide
  2. Click format menu, point on row or column and click hide command.

 

Saving a worksheet

To save a worksheet, one has to save the workbook in which it belongs with a unique name on a storage device like a hard disk. The procedure below can be used to save a workbook:

  1. Click File menu option then select Save as’ command. Alternatively, click the save command on the standard toolbar. The save as dialog appears
  2. Select the location in which your workbook will be saved in the Save in box then type a unique name for the workbook in the File name box. Make sure that the option Microsoft Excel Workbook is selected under the save as type box.
  3. Click the Save button to save.

 

Retrieving a saved workbook

This means opening a workbook that was previously saved.

  1. Click File menu option then the Open command. Notice that the Open command has three dots (called ellipsis) indicating that a dialog box will open, as the user is required to provide additional information. Alternatively just click the Open command on the standard toolbar. The open dialog box appears on the screen.
  2. Click the Look in drop down list arrow and select the drive or folder where the workbook was saved. For example, if you saved in a diskette, insert it in the floppy drive then select 3 1/2-floppy (A:). A list of folders and files in the drive will appear in the list box.
  3. Double click the icon of the workbook you want and the worksheet will be displayed in the Microsoft Excel window. Notice that the cell pointer is in the same cell it was in when the worksheet was last Saved.

Closing a worksheet

Click File then Close command. This closes the worksheet but does not

Close the Excel spreadsheet program. Alternatively, click the; close button of the worksheet window

Exiting from the spreadsheet                 

Click File then Exit command. This closes not only the worksheet but also the spreadsheet program as well. Alternatively click the close button of the main application window.

Cell data types

There are four basic types of data used with spreadsheets:

  1. Labels
  2. Values,
  3. Formulae
  4. Functions.

 

Labels

Any text or alphanumeric characters entered in a cell are viewed as labels by the spreadsheet program. Labels are used as row or column headings usually to describe the contents of the row or column. For example, if a column will have names of people, the column header can be NAMES. Sometimes, numbers can be formatted so that they can be used as labels. To achieve this add an apostrophe just before the most significant digit in the number. For example, the number 1990 will be treated as numeric. if typed in a cell but’ 1990 will be treated as a label.

 

Labels are aligned to the left of the cell and cannot be manipulated mathematically.

 

Values

. ,

These are numbers that can be manipulated mathematically. They may include currency, date, numbers (0-9), special symbols or text that can be manipulated mathematically by the spreadsheet.

 

Formulae

These are user designed mathematical expressions that create a relationship between cells and return a value in a chosen cell. In Microsoft Excel, a formula must start with an equal sign. For example, the formula

=B3+D4 adds the contents ofB3 and D4 and returns the sum value in the current cell.

 

Excel formulae use cell addresses and the arithmetical operators like plus (+) for addition, minus (-) for subtraction, asterisk (*) for multiplication and forward slash (I) for division.

Using cell addresses, also called referencing, enables Microsoft Excel to keep calculations accurate and automatically recalculates results of a formula in case the value in a referenced cell is changed. This is called automatic recalculation.

 

Functions

These are inbuilt predefined formulae that the user can quickly use instead of having to create a new one each time a calculation has to be carried out Microsoft Excel has many of these formulae that cover the most common types of calculations performed by spreadsheets. To add the contents of cell B3 and D4 the sum function can be used as shown below:

 

= Sum (B3:D4)

 

2.6

 

Cell referencing

A cell reference identifies a cell or a range of cells on the worksheet and shows Microsoft Excel where to look for the values or data needed to use in a formula. With references, you can use data contained in different cells of a worksheet in one formula or use the value from one cell in several different formulae.

By default, Microsoft Excel uses the A 1 cell referencing style. This means that a cell is identified by its column label followed by the row number. However, the Rl Cl referencing style can be used. In this case, the cell is referencing by its row number followed by its column number. The table below gives a few examples of equivalent referencing using both styles.

A1 style R1C1 style
B2 R2C2
C10 R10C3
E20 R20C5

 

 

The RlCl style is useful when automating commonly repeated tasks using special recording programs called Macros.

 

Relative referencing

When performing tasks that require cell referencing, you can use formulae whose cell references keep on changing automatically depending on their position in the worksheet. This is called relative cell referencing. A good example would be if you type the formula =Al+Bl in cell Cl. If the same formula is copied to cell C2 the formula automatically changes to =A2+B2.

 

Absolute referencing

These are cell references that always refer to cells in a specific location

, of the worksheet even if they are copied from one cell to another. To make a formula absolute, add a dollar sign before the letter and/or number,

such as $B$lO. In this case, both the column and row references are absolute. .

 

Referencing using labels and names

Labels of columns and rows on a worksheet can be used to refer to the cells that fall within those columns and rows. It is possible to create a name that describes the cell or range then use it instead of having to specify a range with actual cell references. Such a descriptive name in a formula can make it readable and easier to understand its purpose. For example, the formula =SUM(SecondQuarterProfits) might be easier to identify than =SUM(AlO:C20). In this example, the name SecondQuarterProfits represents the rangeAlO:C20 on the worksheet. Names can also be used to represent formulae or values that do not change (constants). For example, you can use the name .Tariffs to represent the import tax amount (such as 7.0 percent) applied to imports.

 

To create a named range

To create a named range proceeds as follows: 1. Select the range to be named:

  1. Click inside the name box to move the text cursor inside. Delete the Cell reference that is there and type a name for the range.
  2. Press Enter key to apply. Figure 2.13 shows a worksheet range called sales that has values used in a formula to give the sum in cell C 11.

 

 

2.7 Basic functions and formulae

Formulae perform mathematical operations ranging from very simple arithmetic problems t9 complex scientific, financial and mathematical analysis.

 

Statistical functions.

  1. Average: It returns the average (mathematical mean) of a set of values which can be numbers, arrays or references that contain numbers. If the value 20 is in cell DIO and 30 in ElO then:

=Average(D lO:E 1 0) returns 25 as the average of the two values.

  1. Count: Counts the number of cells that contain values within a range e.g.

= count (AIO: EIO) many return a value 5 if all the cells have values.

  1. Max: It returns the largest value in a set of values. It ignores text and logical values e.g. == Max (AlO:EIO) will return the maximum value in the range.
  2. Min: It returns the smallest value in a set of values. It ignores text and logical values e.g. = Min (AIO:EIO) will return the minimum values in the range.
  3. Mode: It returns the most frequently occurring value in a set of values. e.g. = Mode (AIO:ElO)
  4. Rank: Returns the rank of a number in a list by comparing its size relative to the others. For example if A 1 to AS contains numbers 7, 3.8,3.8, 1 and 2 then RANK (A2, Al :A5,1) returns 3 while RANK (AI, AI:A5,I) returns
  5. The general format is RANK (number to be ranked, range, order).

 

Logical functions

  1. If: It returns a specified value if a condition is evaluated and found to be true and another value if it is false. If (marks > 50, “pass”, “fail”) will display a pass if values are more than 50 else it will display fail.
  2. Countif: Counts the number of cells within a specified range that meet the given condition or criteria. e.g. suppose A 1 0 : E 1 0 contains eggs, beans, beans, eggs, eggs, countif(AIO:EIO, “Eggs”) will return 3.
  3. Sumif: It adds values in the cells specified by a given condition or criteria. e.g. For example if AIO to ElO contains values 10,50,60, 30, 70, to sum all values greater than 50 = Sumif(AIO:EIO, “>50”). This returns 130.

 

Mathematical functions

  1. Sum: adds values in a range of cells as specified and returns the result in the specified cell. e.g Sum (AIO:EIO) adds values in the range
  2. Product: multiplies values in a range of cells and returns the result in the specified cell. For example if A 10 has 30 and BIO has
  3. Product (AlO:BIO) will return 90.

 

Arithmetic formulae – using operators

       Operator Function

 

+ (plus)                                          adds values as specified

– (minus) .                                      subtracts values as specified

* (multiplication)                           multiplies values

/ (division)                                     divides values.

( ) parenthesis                                     encloses arguments to be calculated first.

 

For a formula =(Al +C3)/E20, if the value in E20 is not zero, the result is displayed in the current cell.

 

Order of execution

If several. Operators are used in a single formula; Microsoft Excel performs the operations in the order shown in Table 2.3. Formulas with operators that have same precedence i.e. if a formula contains both a multiplication and division operator are evaluated from left to right. Enclosing part of the formula to be calculated in parentheses or brackets makes that part to be calculated first.

 

Operator   Name Precedence
1. –   Negation as in -1 1
2.%   Percent 2
2. 1\   Exponentiation 3
3. * and / ! Multiplication and division 4
4. + and –   Addition and subtraction 5
6. =,<>,>,<,<=,>= Relational 6

 

Table 2.3: Operators’ order of execution

 

2.8

 

Editing a worksheet

 

Coping and moving data

Spreadsheet software automates many processes that could have been tedious if done manually. For example with Microsoft Excel, you can do calculations using formulae fairly easily as you give the data and correct instructions to the program. Copying and moving of, data can also be done quickly and efficiently.

 

When data is cut or copied from the worksheet, it is temporarily held in a storage location called the clipboard.

 

Copying data

To copy a cell or a range of cells:

  1. Highlight the cells or range you want copied
  2. Click the Edit menu then select Copy command.
  3. Select the cell in which you want to place a copy of the information 4. From the Edit again, click Paste command. The Paste command puts a copy from the clipboard on the specified location

 

Moving data

Unlike the Copy command where a duplicate copy is created, the Move command transfers the contents of the original cell (s) to a new location.

 

To move a range of cells:

  1. Highlight the range you want to move.
  2. From the Edit menu, select Cut.
  3. Specify the location you want to move the contents to.
  4. From the Edit menu again, click Paste.

 

2.9 Worksheet formatting

Worksheet formatting refers to enhancing the appearance of the worksheet to make it more attractive and appealing to the reader. Appropriate formatting should be used to lay emphasis, catch attention and bring otherwise II hidden detail to the fore of the document.

 

The golden rule of formatting is to use simple clear formats. It essentially consists of changing text colour and typeface (font), size, style and alignment. In Microsoft Excel, format the cells whether empty or not and their contents will acquire the set format automatically.

 

To format a single cell, make it the current cell then format menu option and select the cells command In the format cells dialog box, make the formatting specifications that you wish then click the ok button to apply. If it is a range of cells, they must be highlighted first before formatting them as a block of cells.

 

Formatting text

  1. Highlight the cells that have the text to be formatted.
  2. Click Format menu then cells command. The dialog box appears
  3. Select the font tab as shown in the figure by clicking it.
  4. Select the font type e.g. Times New Roman. Other font formatting features like style, size, underline and colour are available and can be selected.
  5. Click button to apply.

 

NB: Alternatively, use the formatting toolbar to accomplish all your text formatting needs. Notice that the options in the font dialog box are commands on the formatting toolbar.

 

Formatting numbers

  1. Highlight the cells that have the numbers to be formatted.
  2. Click Format menu then cells command. The dialog box in Figure 2.15 appears.
  3. Select the Number tab as shown in the figure below.
  4. You can now choose number formats as explained below:

Number            Meaning

General           general format cells have no specific number format.

Number           Used for general display of numbers e.g. 2345.23.

Currency         For displaying general monetary values e.g. $100, Ksh.10.

Accounting     Lines up the currency symbols and decimal poin s. Displays date in chosen format.

Date                Displays time in chosen format.

Percentage       Multiplies the value in a cell with 100 and display ‘ it as %.

Text                 Formats cells to be treated as text even when numbers are entered.

Custom          For a number format not predefined in Microsoft Excel, select custom then define the pattern.

 

Worksheet borders

You may need to put a printable border around your worksheet or in a range of cells to make it more attractive and appealing. To put a border:

  1. Highlight the range you wish to insert borders. From the format menu, click cells command.
  2. Click the borders tab and specify the border options for left, right, top and bottom. .
  3. From the style options, select the type of line thickness and style. Also select the preset options.
  4. Click the ok button. The selected range will have a border around it.

 

Formatting rows and columns

Sometimes, the information entered in the spreadsheet may not fit neatly in the cell set with the default height and width. It therefore becomes necessary to adjust the height of a row or the width of a column. The standard width of a column in Microsoft Excel is 8.43 characters but can be adjusted to any value between 0 and 255.

 

Changing column width

  1. Move the mouse pointer to the right hand side line that separates the column headers i.e. for instance the line between A and B.
  2. Notice that the mouse pointer changes from a cross to a double arrow
  3. Click the mouse button and hold it down so that you can now resize the width of the column by dragging to the size you wish. After Dragging to the required point release the mouse button and the Column will have a new size.

 

NB: Alternatively, move the cell pointer to one of the cells of the column then click Format, point to Column then click Width command from the sidekick menu. Type a width in the dialog box that resembles Figure 2.17 then click Ok.button to apply.

NB: To change the widths of several columns at the same time, highlight them first before following this method.

 

Changing row height

  1. Point to the line that separates two row numbers e.g. the line between 1 and 2. The mouse pointer becomes a double arrow.
  2. Drag the line until the height of the row is as required then stop and release the mouse button.

NB: Alternatively, click Format point to Row then click Height from the sidekick menu that appears. Type the height that you wish in the dialog box that appears and then click OK button to apply.

 

Inserting rows and columns

I, Click cell A5 to make it the current or active cell.

2.clik insert then columns to insert a ‘row above cell A5 and shift all the other rows downward.

OR

 

Click insert then Columns to insert a column to the left of column A and shift all the others to the right.

 

NB: Alternatively, click  insert  then cells to display the dialog box select the entire row or entire column options to insert a row or column respectively.

 

Global worksheet formatting

The word global in this case refers to the entire worksheet. In order to format the whole worksheet globally, it must be selected as a whole.

Two methods can be used to select a worksheet globally:

  1. Click the top left comer of the worksheet that has a blank column header i.e. immediately on the left of A and just above I,

OR

  1. Press Ctrl+A on the keyboard.

 

Notice that the whole worksheet becomes highlighted. It can now be formatted as one big block using format cells command.

 

Using autoformat

It allows the user to apply one of sixteen sets of formatting to & selected range on the worksheet. This quickly creates tables that are easy to read and are attractive to the eye..

  1. Select a range e.g. B 1 :G7 to make it active.
  2. Click format then select the auto format command on the menu that Appears. Select a format from the autoformat dialog box shown in Figure 2.19.
  3. Click the ok button to apply the format to the selected range.

 

2.9 Data management

At times, it becomes necessary to use advanced data management tools to manage large ,data stored on a ‘worksheet. For example, if the worksheet has many records, it may become necessary to arrange them in a particular order using a method called sorting for easier access to data items. Other methods of data management include use of filters, total/subtotal function and forms.

 

Sorting

To carryout sorting proceed as follows:

  1. Highlight the range that you wish to sort by clicking its column header letter.
  2. Click Data then Sort . Notice that the Sort by field is already reading the field that you selected. This field is called the criteria field.
  3. Select the field to be used as the key for sorting and the sort order as either descending or ascending then click OK button to apply.

 

Filtering data

Filtering is a quick and efficient method of finding and working with a subset of data in a list. A filtered list will only display the rows that meet the condition or criteria you specify. Microsoft Excel has two commands for filtering lists.

  1. The auto filter: It uses simple criteria and includes filter by selection.
  2. Advanced filter: It uses more complex criteria.

 

In this Pupil’s Book we will look at the autofilter.

 

Autofilter

Filters can be applied to only one list on a worksheet at a time.

  1. Click a cell in the list that is to be filtered; usually the list is in a column.
  2. On the Data menu, point to Filter, and then
  3. To display only the rows that contain a specific value, click the arrow in the column that contains the data you want to display as shown in Figure 2.21.
  4. Click the value that is to be displayed by the filter from the drop down list. e.g in the example below, the selected value is 34.

NB: Sometimes while looking through a list of values on a large worksheet, you may come to a value of interest and want to see all other occurrences of the value in the spreadsheet. Simply click the cell that has the value then click auto filter on the standard toolbar. Microsoft Excel turns on AutoFilter and then filters- the list to show only the rows you want.

 

Subtotals function

Consider the following scenario: A company that has many salespersons

will need to know how much each of them should be paid at the end of a period by looking at individual sales volumes. Also, the grand total for all the payments has to be calculated. Therefore, if the salespersons are held in a list, there would be need to calculate the amount due to each of them. This can be called a subtotal in the list. All the subtotals can then be added together to make the grand total. Consider the following list:

Name                    Amount Owed

Stephen           `           6000

Joy                              3000

Stephen                      2000

Virginia                     5000

Joy                             800

Stephen                       200

Virginia                     5000

 

Microsoft Excel can automatically summarise the data by calculating subtotal and grand total values of the list. To use automatic subtotals, the list must have labelled columns and must be sorted on the columns for which you want subtotals. In this example, the list is first sorted by name

  1. Click a cell in the list that will have subtotals e.g. cell A3.
  2. On the Data menu click Subtotals 3. Notice that all the data range is now selected.
  3. In each change in box, select Name from the drop down list because we want a subtotal for each of the names.
  4. In the Use function box select the sum function then select the list for which subtotals will be inserted in the add subtotals box by checking the appropriate label. In this case it is the amount owed field.
  5. Click ok button to apply and the list will now have sub totals inserted

Totals function

Use theAutoCalculate feature in Microsoft Excel to automatically show the total of a selected range. When cells are selected, Microsoft Excel displays the sum of the range on the status bar. Right clicking this function displays other functions like Min, Max and Average that can also be used. To find the total of a range, highlight it then click the autosum icon ∑ on the standard toolbar.

 

Forms

A form is a specially prepared template that the users can use to enter data in a worksheet. It is specifically formatted to enable users to enter data in a format that is more convenient to them. If data is collected on paper before entering in the computer, then a form can be created to have the layout of the data on the paper to quicken data entry procedures. To display a form: Click ‘Data, then form.

 

2.10 Charts/graphs

Charts/graphs are graphics or pictures that represent values and their relationships. A chart helps the reader to quickly see trends in data and to be able to compare and contrast aspects of data that would otherwise have remained obscure. Microsoft Excel has both two-dimensional and 3-dimensional charts that can be used instead of the raw data in the table that has to- be studied for a long time to understand it.

 

The various types of charts available include column, bar, line. Pie, bubble and area charts among others. Consider carefully the type of chart that would best represent the base data in the worksheet before creating one. For example, if the aim is to depict the performance index of a student from Form I-to 3, a line chart would be most appropriate because it clearly shows the trend in performance.

 

Types of charts

  1. Line chart – represents data as lines with markers at each data value in the x-y plane.
  2. Column chart- represents data as a cluster of columns comparing values across categories. .
  3. Bar chart – data values arranged horizontally as clustered bars. Compares values across categories.
  4. Pie chart – it displays the contribution of each value to a grand total.
  5. Scatter chart – compares pairs of values on the same axis.

To view types of charts, right click the chart object then select the chart type command.

 

Creating a chart

A chart must be based on values that are already entered in the worksheet.

 

To create a chart:

  1. Select the range of values for which you want to create a chart.
  2. Click the Chart wizard button on the standard toolbar and the chart wizard dialog box will open as shown in Figure 2.25
  3. Click the type of chart you wish to .create. If the office assistant appears, close it. The chart sub-type preview will show several styles of the selected chart type.
  4. Click the Next button to move to the dialog in Figure 2.26.
  5. Click the Series tab then the collapse dialog button on the labels text box.

This will shrink the dialog box so that only the category labels text box is shown. Highlight the data labels from the worksheet.

  1. Click the Expand dialog button to bring the full dialog box into view then click the: Next button. In step 3 of the wizard, use the appropriate tabs to type the title of the chart, show a legend, select whether to display gridlines or not etc. After all these click the Next button.’
  2. At step 4 determine whether the chart will be inserted in the current worksheet or a new worksheet then click Finish button (Figure 2.27).

 

Moving and resizing a chart

Once the chart is created, its size and location can be changed in the worksheet. The chart element is enclosed inside a boundary called the chart area and hence both can be resized independently. Simply click the object you wish to resize and use the object handles just like in objects to drag to size. To move the chart, click inside the chart area then drag to the desired position.

 

Data ranges

A data range is a rectangular block of cells that provides the base data that is used to create the chart. In charting, a data range is referenced as an absolute range e.g. .

=Sheetl !$B$2:$C$8 which means that the base data is found on Worksheet 1 and absolute range B2:C8.

To see the data range of a chart, right click it then select the Source data command. .

 

Labels

Each representation of data on a chart can either be labelled by a value

or text label. For example, in a bar chart that compares the height of pupils, each bar can be given a value label to make it more readable.

 

To label:

  1. Right click the chart then select the Chart options command from

the shortcut menu.

 

  1. Click the lables tab and choose whether you want value or text labels then click OK button to apply. .

 

Headings and titles

Each chart must have a heading showing clearly what it represents. To I make the chart understandable, include axis titles.

 

. To include axis titles proceed as follows:

  1. Right click the chart then select the. Chart options command.
  2. Click the Titles tab then type the chart title (heading). And axis titles respectively.
  3. Click OK button to apply.

 

Legends

The legend is like a key that explains what each colour or pattern of the data representation in the chart means. For example, Microsoft Excel may give red colour to one data value and green to the other. Without a legend it would be difficult to know how to differentiate the two sets of values.

 

: To create a legend:

.1.Right click the chart then select the Chart options command.

  1. Click the legends tab and specify that it be displayed in the chart area.
  2. Click OK button to apply.

 

2.11

 

Printing worksheets

A worksheet will finally be printed for sharing with others or for filing purposes. If it contains objects like charts, it may not fit on a standard printing page using the default printing options and settings. Therefore, Microsoft Excel allows the user to preview and set up the pages of a’ worksheet in order to fit them on the hard copy page.

 

Page setup

  1. Click .File menu option then Page setup command to display the page setup dialog box. . .
  2. On the Page tab, select the orientation of the page. Study the meanings of each buttons and options in Figures 2.28.
  3. After making the necessary selections, click OK to apply.

 

Print preview

It displays the worksheet from the point of view of the printer i.e. exactly the way it will look when printed. Before using this command, make I sure the chart is deselected.

  1. Click the Print preview button on the standard toolbar.
  2. The worksheet will be displayed in the print preview window with the status bar reading preview.
  3. Click Setup to start the page setup dialog box. To close the preview, click the Close. Button.

I Print options

 

To print click File then Print command. The print dialog, box appears as shown in Figure 2.29 .

  1. Select printer – the name box in this dialog box enables a person to select the printer that will be used to print the document. All the printers that are installed on the computer will be available here.
  2. The print what options are:

(a) Selection – this prints the selected worksheet area.

(b) Workbook – prints all the worksheets in the workbook.

(c) Selected chart – prints the selected chart only.

 

Page orientation

As explained earlier, page orientation refers to the layout of the text on the page. A worksheet can also be printed on either landscape or portrait depending on the number of columns across the worksheet.

 

Pages and copies                                                                        .

The number of copies box specifies how many copies of a particular worksheet or workbook should be printed.

 

Sometimes only some specified pages in a workbook are specified for printing e.g. if a workbook has 100 pages and you wish to print only pages 50 to 60 select the page(s) range button then type 50 and 60 in the from, to boxes respectively before clicking the OK button.

 

Printing

After selecting all the options, click the OK button to print.

 

Some common printing problems

  1. A message appears on the screen saying that the printer specified could not be found in the directory.

 

Possible problems and solutions

(a) The printer could be off. Switch it on and it will start printing.

(b) The data cable to the printer could be loose. Make sure it is firm at the ports.

(c) The wrong printer could have been selected. Select the right one in the print dialog box and send the print job again.

(d) A message appears on the screen reading that there is paper jam.         I

 

The printer is clogged with a paper jam. Alert the lab, technician or the Teacher to clear the paper jam.

 

DATABASES

 

Chapter outline

 

3.1 Introduction to databases

3.2 Database concepts

3.3 Data organization in a database

3.4 Creating a database using Microsoft Access

3.5 Editing a database

3.6 Form design

  1. 7 searching for specific records in a database

3.8 Creating reports

3.9 Creating labels

 

Introduction to databases

We are often faced with the need to keep, search for or give a report of daily experiences. This is the reason why many people use data storage methods like recording daily experiences in a diary. Traditionally, human beings used to manage data and information manually by using simple devices. However these methods have a number of weaknesses which include

 

  1. Unnecessary duplication of data
  2. Boredom and time wasting especially when searching for a Particular item.
  3. Misleading reports due to poor data entry and organisation
  4. Poor update of records etc.

 

Today, computerized systems have radically changec4the way data and information is managed by use of special programs called Database Management System (DBMS).

 

A database is a collection of structured and related data items organised so as to provide a consistent and controlled access to the items.

 

Database concepts                                                                           .

Computerised database creation and manipulation is achieved using Database Management System software. This software facilitates the creation, organisation and maintenance of databases. Examples of database management software’s include Microsoft Access (Ms Access), Oracle, FoxPro, Dbase/V, Lotus Approach etc.

 

The functions of database management software are to:

  1. Allow the user add or delete records.
  2. Update or modify existing records.
  3. Organise data for easy access, retrieval and manipulation of records.
  4. Act as an interface between a database and other application programs.
  5. Ensure security for the data in the database by safeguarding it against unauthorized access and corruption (damage).
  6. Keep statistics of data items in a database.

Database models

 

Databases are classified according to the method used to organise data. The main database models are;

  1. Flat file 2. Hierarchical
  2. Network 4. Relational

 

NB: Current database models are called object relational and object databases. However these models will not be discussed in details in this book.

 

Flat files

 

In a flat file model, a database holds only one set of data and is not any different from the manual files. For example, the teacher’s assessment report may consist of performance cards for every student in a class. Another example of a flat file database are the cards used in a library books catalogue. The cards are arranged sequentially for easy access e.g. alphabetically using books’ titles or by authors’ names. Figure 3.1 below is a sample record of a flat file.

Name Serah Seki
Admission number 649
Total marks 680
Number of subjects 10
Average 68
Position 4

Fig. 3.1: Sample record in a flat file

 

Hierarchical model

 

In this model, data items are arranged in hierarchical (tree) form as shown in Figure 3.2. To access level two data items, you have to first access level 1 data items. Level 1 item is called the root component. A specific single path leads to each item at lower levels. Hierarchical model is rarely used in modem database systems.

 

­                 Level 1 main data item

Path

  Level 2 data item

 

 

Fig. 3.2: Hierarchical database model

 

Network model

 

In this type of organisation, links are used to express the relationship between different data items, forming a network of items as shown in Figure 3.3. Access to one item can be through multiple paths and from any item. This model is also rarely used in modem database systems.

 

Dataitem 4

 

 

 

 

 

Fig 3.3: Network database model

 

Relational model

This is the most common type of model used on minicomputers and microcomputers. In this type of organisation, related data items are stored together in structures called relations or tables. Relationship can be created between tables such that a record or records from one table relates to another or other records in another table. Tables 3.1 and 3.2 show customers and orders tables that are related by two fields; the customer number in Table 3.1 and customer ID in Table 3.2. In this case, the orders table shows that one customer with number 450 (Bat Hori) has made several orders.

 

    Customer Number Name   Telephone number
    900   Mary Koech 02078907
    230   Peter Karimi 0667896
  450   Bat Hori 04456000
      Table 3.1: Customer number  
  Customer ID Order Number Date     Amount (sh)
900   2380   2/3/2004 90 000
  450   811   2/5/2004 5000
‘- 450   234   . 3/5/2004 13 000
  450   567   3/6/2004 13 000

Table 3.2: Customer ID

 

Object oriented models                                                                           . !

The next generation of database model will look at records as objects that are independent and relate with the other objects in the database. This concept is a bit difficult to conceptualise because such databases are still at developmental stage. However, many databases today combine object and relational concepts to come up with object relation models.

 

Features of a database management software

Most database software contains a collection of features that provides the user with a means to manipulate data in a database. These features include Tables/files, Queries, Reports generators, Form interface and a computer programming language within it. Microsoft Access database software that will be considered in this book has two distinct features used to automate operations namely Macros and Modules.

 

Tables/ file structure

This is a database structure that is used to hold related records. Tables are organised in rows and columns with each row representing a record while each column represents common fields in each record. Table 3.3 shows a table of six records and each record is made up of four fields.

 

FIRST NAME MIDDLE NAME LAST NAME ADDRESS
MBUGUA STEPHEN KIMANI 250 KERUGOYA
ADERA NELSON ODUOR 396 HOMA BAY
MARGARET JUDY WEKESA . 761 NAIROBI
GATO PATRICIA MUILA 170 TALA
MWELU LUCY. MWENI 390 KANGUNDO .
KOECH PETER KORIR 605 KERICHO

 

Table 3.3: Table of six records and four fields

 

Queries and query language

 

A query is a database tool used to search for or question a database on specific records. Because a query is a question posed to the database, it returns a result for the user. In Microsoft Access, this result is called a dynaset. For example, assume you work with the National Irrigation Board (NIB), you may wish to display all those farmers from Mwea Rice Irrigation Scheme who delivered rice in January to the National Irrigation Board. You can use a query object or statements to get the required records.

The query statements are written using a special language called

Structured Query Language (SQL). The user creates a, query by writing Structure query language statements such as:

Select

Farmer Number, Name, Month of Delivery

From

       Delivery Table

Where

Month of Delivery = “January”

 

Forms/screen input

 

A form is a graphical interface that resembles the ordinary paper forms used to collect data. However, a database form enables the user to view and enter data into a table. Figure 3.4 shows a sample form used for entering a student’s marks scored in four subjects and. the date of admission. Form interface is a more convenient and easy way of entering and viewing records from a table.

 

Reports

 

Most database systems provide the user with a tool for generating reports from an underlying table or query. It is the report generator that provides the user with a means to specify the output layout and what is to be output or printed on a report. Table 3.4 shows a sample report for employees’ salaries.

Net Pay Report

 

fay rol/no .Last.Name      First Name. . .Basic salary                PAYE              Net salary.

 

07      Wangui        Grace        sh 80,000.00   Kshs 7,300.00 sh 72,700.00

09      Ochieng       Mbenga    sh 37,000.00   Kshs 3,800.00 sh 33,200.00

13      Mumbua      Peter         sh 22,000.00   Kshs 2,300.00 sh 19,700.00

20      Mbuvai        Sicily        sh 60,000.00   Kshs 5,700.00 sh 54,300.00

Table 3.4: Sample report

 

Macros

 

Some database software provides the user with a tool called a macro, that can be used to automate frequently performed procedures or tasks. For example, if you frequently use a particular form when you start a database program, you need to create a macro that automates the opening of the form.

 

Programming module

 

When your database becomes more and more complex, you may need a more powerful tool than the macros to automate your database operations further. Some database software come with their own computer languages associated with them. For example Microsoft Access comes with a language called Visual Basic included as a Module in the software. Using this feature, you can create a program that will print a query result over and over again until a certain condition is true. This can be illustrated using a simple statement like;

 

Print Student Report until NumberofStudents = 40 (Not a real command anyway).

 

NB: For the purpose of this book, only tables, forms, queries and reports, have been covered.

 

Data organisation in a database

One of the functions of a database system is to organise data for easy access, retrieval and manipulation. Data is organised from the simplest fQfll1 called a field to a very complex structure called a data,base.

 

Fields

A field is a character or a logical combination of characters that represent data item. For example, in a class list, the student name is a field.

 

Records

This is a collection of related fields that represent a single entity. An example of a record is the student report card that may contain the. student’s name, admission number, class, total marks, average and grade.

 

Files/tables

A file is a collection of related records. For example, the students’ file in a school database contains the details of all the students in the school.

 

Database

This is the highest in data organisation hierarchy that holds all related files ‘or tables. For example, a school database may contain students and staff tables/files.

 

Creating a database using Microsoft Access

Microsoft Access (Ms Access) is a package in Microsoft Office suite used for creating and manipulating databases. Because there are different versions of Ms Access such as Ms Access 95/97/2000 and XP, a general approach for carrying out tasks has been adopted in this book. However most of the illustrations are based on Access 2000 in order to maintain consistency.

 

Starting Microsoft Access

  1. From Windows desktop, click the start button.
  2. Select. Microsoft Access from the programs menu
  3. In the dialog box that appears when Microsoft Access starts, click Blank Access database as shown in Figure 3.5 then OK.

 

  1. The Save As dialog box appears. See Figure 3.6. This lets you specify the name and location where your database will be stored. Click Create to save the database.

 

  1. Microsoft Access database objects window is displayed from which I you can choose the type of object to create such as tables, forms, queries etc.

 

Microsoft Access screen layout

Like the other applications discussed earlier, Ms Access application Window has a title bar, menu bar, toolbars and status bar. However instead of having a work area like that ofMs Word or Excel, it provides the user with an object window from which you choose the type of an objectto work with such as tables, forms, reports e,tc. See Figure 3.7.

 

.Exiting from Microsoft Access

Because Microsoft Access consumes a large amount of computer memory  it is advisable to exit from the application at end of each working session.

 

To exit:

From the File menu, click exit the close button on the title bar.

 

Guideline on designing a good databases

To design a good database which will require little time to maintain, consider the following:

  1. Carefully study the requirements of the user in order to define all the data inputs, outputs and relationships required.
  2. Design a draft database on the paper to determine the number of files or tables required.
  3. Divide the information into separate fields, records and tables to allow flexibility in manipulating the database. This process of dividing information into independent tables to avoid repetition of data entries items is referred to as normalizing a database.
  4. Define a field for each table that will be used to identify each record uniquely. This field is referred to as a primary key
  5. Give the most important fields the first priority when constructing a table structure. Important fields are those that are used in sorting’ and querying the database. “
  6. Design data entry forms needed for the database

Creating a table/file structure

To define a table structure:

  1. From the Microsoft Access objects window, click the tables tab then new
  2. From New table dialog box, select Design View Figure 3.8 appears. :
  3. using the grid displayed, enter a unique name for each field in the table. A field name must start with a letter and can be up to a maximum of 64 characters including letters, numbers, spaces and punctuation.
  4. Choose the correct data type before adding the next field. By default, Ms Access inserts Text as a data type. Figure 3.8 shows various data types used in Ms Access.
  5. To save the table, click the Save button on the standard tool bar or save from the file menu.
  6. Access will ask you whether you want to create a Primary Key, click Yes.

 

Description of field data types

The type of data to be used in a database must be clearly defined for the purpose of manipulation and storage. For example, if a field is to be used for calculation, it must be defined as a number. The data types allowed in Ms Access include:

 

Text

This type includes alphabetic letters, numbers, spaces and punctuation. Use this data type for fields that do not need to be used for calculations such as names, places, identification numbers etc. This type of field accommodates a maximum of 255 characters.

 

Number

These are fields made up of numeric numbers 0 to 9 that are to be manipulated mathematically.

 

Memo

This is a field made up of alphanumeric (both alphabetic and numeric) data. Instead of using Text use this data type if you need to enter several paragraphs of text because it accommodates a maximum of 32 000 characters.

 

Date/Time

Used to identify a field as either a date or time. This is because date/time values can be manipulated mathematically in a database. For example, you can calculate the age of a person from the date of birth to the current data.

Currency

Used to identify numeric values that have decimals or fractions. Use this data type especially when dealing with monetary values such as fees balance, amount sold etc.

 

AutoNumber

This is a numeric value used if you wish Ms Access to automatically increment the values in a field. For example when entering a list of forty students and you have a field labelled StudNumber, the numbers will increase by one every time you enter a new record.

 

Yes/No

This is a logical field where an entry is either a yes or a no, true or a

false. For example a field may require you to answer whether you are a male or a female.

 

OLE Object

OLE stands for Object linking and Embedding. This type of field is mostly used with graphical user interface applications for inserting graphical objects such as pictures, drawings charts etc. – – –­

 

Field properties

As you create more and more complex tables, you will find a need to use the field properties to specify finer details related to fields and the table entries expected. The field properties depend on the type of-the field selected. For example when you click on a Text field then the General tab you will see properties associated to text data type as shown in Figure 3.9. ­The various properties are:

 

Field size

This allows the user set the number of characters in a field instead of the default 50 for text fields for numeric field’s integer and long integer, Byte, Single and Double.

Integer and longer integer: Accept numbers with no decimals.

Byte: Can only accept a number from 0-255.

Single and double: Accept numbers with decimals. Single accommodates up to 38 decimal places while double, accommodates up to 308.

 

Format

Determines how information appears on the screen and when printed. For example, you can format a number to scientific, currency, percentage or general format.

 

Decimal places

For number and currency fields you can specify the number of decimal places.

Input mask                                                           ,

Input mask automatically formats the field entry into a specified format. F or example, if you enter a number such as 02000 I 00409874 and the input mask is set as 000-(00000)-000000, it is automatically displayed as 020-(00100)-409874. This property is mostly used to format phone and address entries.

 

Caption

This is a more descriptive name for a field to be used in a table or a form display. For example the caption for StuName could be Student Name.

 

Default value                                                                                         ,

This is a value that will appear automatically in the datasheet or form if ‘ nothing is entered by the user to change it. For example = Date -( ) automatically displays the current date in a date field.

   Validation Rule

Logical expression restricts the values to be entered in a field. ‘For example, if you want to restrict marks entered in a field to values between

, zero and a hundred, type >=0 And <= 100.

 

Validation Text

The message that appears once the validation rule is violated. For example, you may create a validation text for the above validation rule I to display “Enter a number between 0 and 100” whenever the user enters I a value outside this range.

 

Required

Determines if an entry must be made in the field before you proceed to the next field or record. For example, if a primary key is required, you must enter before you proceed.

 

Allow Zero Length

This allows the user to proceed without making any entry in the field set as Zero length.

 

Indexed

An Index, facilitates the organisation of records for easy search. A primary key is an example of an index set to No duplicates to control double entry of a record (redundancy).

 

Primary key and Indexes

 

An index is a database feature used to speed up search and sort operations in a table. A key field also referred to as a primary key is a special index that enforces uniqueness in a table so that one record is not entered twice.

 

Ms Access uses the primary key to search for data stored in a table as well as define relationships between tables. Once a field is set as primary key, its datasheet is automatically indexed or sorted using the primary key.

To set a primary key:

  1. Open the table in design view.
  2. Select the field you want to set as the primary key by clicking in the row header to the left of the Field Name.
  3. Click Set Primary key button on the tools bar. A key should appear on the left of the field name as shown in Figure 3.10.

 

To see another field as an index other than the primary key: 1. Open the table in design view.

  1. Ensure that non of the fields is selected as a primary key.
  2. Click the Indexes button on the tool bar that is located next to the primary key. The index design grid is displayed on the screen as shown in Figure 3.11.
  3. In the index name column, type in the name you want to give to the index.
  4. In the Field Name column, click the cell to display a drop down list. From the drop down list, select the field to use as an index.

6 In the Sort Order column, select either ascending or descending.

  1. In the lower portion, specify whether you want to make the field a primary key by selecting yes for primary and unique, and Ignore Nulls to ensure that data is entered into the field before proceeding.
  2. Close the dialog box.

 

Entering data into a table

 

To enter/append data into a table:

  1. Open the database in which the table is located
  2. Click the Tables tab then double click the table you want to add records to.
  3. Enter each record field by pressing the tab key to move to the next. Once you reach the end of the record and move the cursor to a new row the previous record is automatically saved.

 

Editing a database

 

Modifying the Datasheet view

 

To adjust the column size:

  1. Point to the column border between the field’s header then drag to the require size.
  2. Alternatively, click on the format menu then point to column and click on width
  3. Type the desired width

To adjust row height

  1. Point to the border between two rows in the row header and then drag.
  2. Alternatively, use format menu, then Row height.

To reorder fields:

  1. Select the column of the field you wish to move by pointing to the desired file name.
  2. Drag the column right or left to the top of the field where you want your field to appear and then drop.

 

Modifying the table structure

 

Once you create a table, you may need to add more fields, remove some fields, reorder the fields or change fields data types and properties. Before you modify the table it is important to save a copy to avoid losing everything in case you make a mistake

To make a copy of your table:

  1. From the file menu, click save as /export
  2. From the dialog box that appears, choose whether to save to another (external) database or the current.
  3. Type a new name for your table and click OK.

 To modify the original table:

  1. Open the table in design view by clicking the button that looks like a pencil and a set square placed on the edge of a ruler.
  2. Select the field or fields to be modified and make the necessary changes.
  3. Click the Save button to save the changes.

NB: If a table contains data and you make changes to the field data type, Ms Access may refuse to implement the changes. To avoid this problem, exit without saving and delete all the records from the table then return to the design view. You can then import a copy or copies of tables you backed up.

To import a table from another database:

  1. From the File menu, point to Get External Data then click Import
  2. From the dialog box that appears, select the database you wish to

import data from then click the Import button. Objects dialog box is displayed as shown in Figure 3.12.

  1. From the objects dialog box displayed, click the Tables tab
  2. Select the table(s) you wish to import then click OK.

 

Form design

 

Tables display many records at once from the database and in some cases you may not be able to see some fields properly. A form is an interface that enables the user to view and make data entries into an underlying table more easily. Figure 3.13 shows a sample form used to enter records into a books table.

 

In Microsoft Access, a form is designed using graphical objects called controls. A control is an object such as a text box, check box, command button or shapes that you place on a form design grid to display data or perform actions. There are two types of controls you can place on the grid: bound and unbound controls. A bound control is one whose source of data is a field in a table or query while unbound control is a control that is not connected to any data source.

 

You design or modify a form layout by dragging these controls to the required position. Figure 3.14 shows a form layout grid for a table called exam entry.

 

 Creating a form layout using form wizard

 

To create a form layout, you can either use the form wizard or start from scratch. Using the form wizard you can create either a columnar, a tabular a datasheet or a justified form layout.

Columnar form: The fields for each record are displayed down a column i.e. each value displays on a separate line with field labels to the left. Tabular: Records are displayed from left to right across the page and labels appear at the top of each column and each row represents a new record.

Datasheet: The form resembles a table datasheet view.

Justified: One record occupies the whole form.

To create a form using the form wizard:

  1. Open the database for which the form is to be created e.g.”EMPLOYEES”
  2. Click the Form tab then, New. From the New form dialog box that appears, click Form Wizard.
  3. Select the table you want to create a form for then New, A dialog box appears.
  4. Click the name of the table or query that includes the data you want to add into the form, and then click OK.
  5. From the fields list window, select the fields to add into the form by clicking the> button or click>> to add all fields then
  6. From the layout dialog box, select the layout you wish to use e.g. Standard then. click Next.
  7. In the Form title dialog box, type the name of the form then click Finish. Ms Access will automatically display the form on the screen.

 

Creating a form using autoform wizard

 

You can easily create a form using the Autoform wizard. This wizard creates a form for you automatically by asking you very minimal questions. The form includes all the fields from the selected table.

 

To construct an autoform tabular.

  1. Make sure your database is open
  2. Click the Form tab, then New.
  3. In the new form dialog box, select an auto form layout e.g. columnar
  4. In the “Choose the table or query where the object data comes” select the table you wish to create a form for then click OK. The form with all fields will be displayed.
  5. Click the Save button to save the form.

 

Creating a form from scratch

 

  1. Open your database
  2. In the database window, click the Form tab then New
  3. From the New form dialog box, select Design view
  4. In the “Choose the table or query where the-object data comes” select the table you wish to create a form for then click The form with all fields will be displayed.

To add controls onto the grid:

  1. Click the View menu, then. Field list command . The table you selected fields list is displayed.
  2. Drag and drop each field and arrange them on the grid.
  3. Save the form by clicking on the save button.

 

 

Data manipulating in a form

 

Adding and displaying records

 

The form provides the user with navigation buttons located at the bottom that can be used to navigate the form

The functions of the buttons can be summarized from left to right as follows

  1. Displays the first record in the table
  2. Displays the previous record.
  3. Displays the next record
  4. Displays the last record.
  5. Add a new record.

 

Formatting fields/controls in a form

To format fields in a form;

  1. Open the form in design view
  2. To resize, click the controls then position the pointer on the outline of the control then drag to the required size.
  3. To move, click the control and position the pointer onto the place holder or inside the control then drag to the required location.

 

Searching for specific records in a database

One major reason for use of a computerised database is the ability to search and retrieve specific information more efficiently. Rather than searching through endless filing cabinets, you simply enter an instruction and let the database do the rest. To search for data in a database, Ms Access provides the user with two search tools:

  1. Find command 2. Queries’

 

Using the find command

With a large database, the Find command saves your time when you need to move a record pointer to a particular record.

To search for a record:

  1. From Edit menu, click Find. The find dialog box appears in which you specify the field you want to search for in the” Find What” box as shown in Figure 3.16.
  2. Type the name of field you wish to search for in the Find What text box. .
  3. In the Search box (Figure 3.16), specify whether to:

( a) Search All

(b) Search Down to up or

(c) Search up to bottom

  1. In the match box, you can select one of the match types:

(a) Any part of field – As long as a string of characters to be searched are present in a word, then all the words having the string will

be searched e.g. “Berg” finds Berger, inselberg etc.

(b) Whole Field – Searches for the whole field for example, “Berg”

will not return Berger, inselberg but specifically berg if it is in the database.

(c) Start of Field – Specifies that, the searched word should start with the specified search string e.g. “Berg”

  1. In searching, you can also check or uncheck;

(a) Match case – Finds only text that has the same pattern of upper and lower case as the one specified in the Find What box.

(b) Search Field As Formatted – Select (check) to find data based on its display format e.g. ‘a date stored asa number 1/5/98 but

displayed as 05-Jan-98

(c) Search Only Current Field:- Select to search through all records for the current field only.

  1. After you set the search conditions click the Find First button.
  2. If you want to search for the second record or other records with the same field, click Find Next button.

 

You can use a wildcard e.g. asterisks (*) if you are not sure of the correct search word that will find all records that match the specified search string. For example, if you wish to search for all names that start with letter “J” in a school database, type J *. All names that start with J e.g. John, Jane Joy, Joyce and James will be displayed.

 

Using Queries

Queries are the fastest way to search for information in a database. A query is a database feature that enables the user to display specific records as well as perform calculations on fields from one or multiple tables. You can analyse a table or tables by using either a select query or an action query. However, only the select queries will be discussed in detail in this book

 

Select query

This is the most common type query used for searching and analysing data in one or more tables. Select query lets the user specify the search criteria and the records that meet those criteria are displayed in a dynaset

 

Action query

These are queries that are used to make changes to many records once. They are mostly used to delete, update, add a group of records from one table to another or create a new table from another table.

 

The four types of a action queries found in Microsoft Access are:

  1. Update – Updates data in a table.
  2. Append query – adds data in a table from one or more tables.
  3. Make table Query – Creates a new table from a dynaset.
  4. Delete Query – Deletes specified records from one or more tables.

 

Creating a select query

  1. Ensure that the database you want to create a query for is open.
  2. Click the Query tab, then New.
  3. From the New query dialog box, choose either to create a query from in Design view or using a Wizard.
  4. To design from scratch, click Design View. The Show Table dialog box appears from which you can add a table or tables you wish to create a query for as shown in Figure 3.17.
  5. Click the table from the table/ query list and then click Add.’
  6. Click Close to close the show table dialog box.
  7. The query design grid opens. In Microsoft Access it is called Query By-Example. This lets the user to design a query. Figure 3.18 is QBE grid for a table called Exam.

 

Parts of the query grid             ­

Field row- Fields from a table or tables to be used are arranged in this row. Each field should occupy its column.

Sort row – By clicking the down arrow in the sort cell, you can specify the sort order i.e. ascending, descending or no sort.

Show row – By clicking the Show box, you specify whether to display the field in the query results: When the box is not checked, the field will not be displayed.

Criteria row – This is where you type conditional statement that will be used by the query to display specific records.

Or row – Used to specify an alternative condition e.g. if you want to display records with a field called City with items Nairobi or Embu, type Nairobi in criteria cell and Embu in the Or cell.

To add fields into the query grid:

  1. Open the query in design view
  2. From the field list of the underlying table, drag each field and place it in the field row

 

Specifying the search criteria

In order to search for a particular set of records, you have to enter a conditional statement or statements in the criteria row. For example if you have a table called employees with one of the fields as salary, you can display all the employees earning more than Shs. 5,000, by typing >5000 in the criteria row, salary column.

 

To define criteria, use either relational or logical operators. Relational operators include less than «), greater than (», greater than or equal to (>=), less than or equal to «=), not equal to «» and equal to (=). Logical operators include AND, OR and NOT.

 

Use AND to display values in a specific range. For example, to display records from the employees table with salaries above 4000 but less than 6000, type, >4000 AND < 6000 on the criteria row in the salary column. All the employees who meet this condition will be displayed.

 

Use OR if you wish to get either one of two values. For example if you wish to get those employees either in Nairobi OR Embu.

 

If you want to display data in a particular range use the word Between. For example, instead of typing , >4000 AND < 6000, type Between 4000 And 6000.

 

If you want to list all records except those that you do not want to see use NOT. For example if you type NOT 6000 in the salary column of the employees table, all employees records will be displayed except. those with their salary as 6000.

 

To display records you are not sure of the field name but at least you can remember a few characters, use LIKE and the wildcards. Wildcards are

special symbols mostly an asterisk and a question mark used in place of other characters. For example, to display all names starting with “Sm” followed by any other character, type Like Sm? Like */*/1993 lists records created in 1993 regardless of the day or month.

 

Saving and running the query

  1. Click the Save button on the standard tool bar or save command from the file menu.
  2. In the name box that appears, type in the name of the query then click OK.
  3. To run the query in design view, click the Run button on the toolbar as shown in Figure 3.19 or Run command from the Query menu.
  4. You can view the results of your query any other time by selecting the query, then clicking the Open button from the database window.

 

Sorting the dynaset To sort a dynaset:

  1. In the sort row, click the down arrow that appears to specify the sort order i.e. ascending or descending of the desired field.
  2. Display the dynaset.

 

Modifying and updating a query

To delete fields from the query grid:

  1. Open the desired Query in design view.
  2. Select the field column you wish to delete
  3. Choose Delete from the Edit menu.
  4. Click the Save button to save the changes

 

To adjust the column size in a query

  1. Open the desired query in design view.
  2. Position the mouse pointer at the boundary that separates columns then drag it to the required size. Alternatively, double click the boundary to auto fit cell content.
  3. Click the Save button to save the changes

To modify a criteria statement ‘select query,

  1. Open the desired query in design view.
  2. Modify the criteria statements as desired, 3. Click the Save button to save changes.
  3. To test whether the changes have been effected, click the Run button to display the results of the query.

 

Performing calculations in a query

Unlike tables, queries let the user perform mathematical calculations on numeric data. You can perform calculations in a query by using the Total functions or by creating basic formulas

Creating basic formulae

To create a formula that calculates the total marks in an underlying table e.g. Exams table:

  1. Open your query in design view
  2. In an empty cell, preferably the immediate last field cell, type an expression that includes a field name of your choice such as:

Total: [Math’s) + (Physics) + (Chemistry) as shown in Figure 3.20

 

Math’s Physics Chemistry Total: (Math’s)+(physics)+(Chemistry)
Exam Exam Exam  
      .
        √      √     √     √

 

Fig. 3.20: Creating an arithmetic expression

 

  1. You can then set the criteria, and other query options.
  2. Save the query and run it. The results of the calculations will be displayed in the dynaset as shown in Figure 3.21. However, this field is not added to the underlying table(s) because query results must always be based on the most current data in the database.

Using Total functions                 .

With a query, you can analyze all records fields using the inbuilt functions such as Sum, Average, Minimum and Maximum etc. To use the total functions:

  1. Open your query in design view.
  2. Click the Totals button on the query toolbar.
  3. Select the field you want to analyze.
  4. For each field to be analyzed, click its cell in the Total row, and then select any of the functions as shown in Figure 3.22.

Sum: Adds all the numerical data items.

Avg; Calculates the mean of all numeric data items in the field column.

Min: Returns the minimum value from the field column.

Max: Returns the maximum value from the field column.

Count: Returns the number of items field column.

  1. Set criteria and other options then click run to preview the results
  2. Save the query.

 

Printing a query:

  1. Open the database window of the database containing the query you want to print
  2. Click the query tab then the query you want to print.
  3. From the file menu, click print Set the printing options then click the OK. Button.

 

Creating a select query from multiple tables

When you use fields from more than one table in a query, there should be a common link or relationship between the tables. There are three type of relationships

  1. One – to – One
  2. One -to – Many
  3. Many -to – Many

In a one -to one relationship, for a particular field in one table (the main table), there is only one matching record in the related table and vice versa. In a one -to many relationships, for a particular field in one table there are several matching records in another table. This is the most common type of relationship. For example, a person may make one order, or several orders. For this instance, there is only one record with that person’s details say in customers’ table, yet there are several records related to the same person in the Orders table.

In a many -to many relationship, for particular records in one table there are several matching records in the other table and vice versa. This is not very common.

 

Defining relationship between tables

  1. Make sure your database is open.
  2. From Tools menu, choose Relationships. The relationship dialog box appears.
  3. Select the tables to add then click the Add button. .
  4. To create relationship, click on the common field and drag it to the second table. The fields used to create the relationship must be of the same type and properties.
  5. To Enforce Referential Integrity, right click the line joining the two tables then click Edit. An Edit relationship dialog box such the one in Figure 3.23 will be displayed.
  6. Make sure Enforce Referential Integrity is checked to ensure that all records entered in the related table exists in the primary table.

 

  1. Click OK to close the Edit relationship dialog box.

 

To create a query based on related tables

  1. Start the database window and click the Queries tab,
  2. Select design view and click OK.
  3. From the show table dialog box, click the tables you want to base your query on and then click Add.
  4. Relationship between various tables will be displayed as shown in Figure 3.24. Add the fields from both tables into the QBE grid.
  5. Save and Run the query.

 

Creating reports

Reports are used to summarize and present information from a database. A good database software should enable the user to generate database reports and print them for presentation and distribution. This process is referred to as formal presentations. As with forms, a report layout is also designed by placing controls on to the report layout grid as shown in Figure 3.25.

 

Parts of a report layout in design view

Report Header-This contains unbound controls that displays title of the report.

Page Header – Contains heading or labels data items to be displayed in every column.

Detail – Holds bound controls that display data items for the table or query it was created from.

Page footer holds a control that is to be displayed on every page such as the page number and date. For example =Now() displays the current date and time as set in the system clock.

 Report footer Used to display summary from a report such as the grand total for numerical data in a particular field column.

 

Creating a report using report wizard

Just like the form wizard, report wizard takes the user through a number of steps by answering a few questions and Ms Access automatically does the rest.

 

To create a report layout:

  1. Ensure that the database is open.
  2. Click the Report tab, then New
  3. From the/New Report dialog box, click Report Wizard then
  4. Select a table or a query then the fields to be added to the report then click next.
  5. The wizard asks you whether you wish to add any group. Grouping is used to categorise records using a particular field for better presentation or if you need to perform calculations on a group of common items. For example, to categorise books in a library database according to ISBNNumber, double click the field then click Next. (Figure 3.26).
  6. In .the dialog box that appears, select the Sort option if you want to sort the records. You can also click the Summary options button in case you want Ms Access to perform calculations on numerical fields. In summary options dialog box, select the Summary options you want performed e.g. Sum, Average etc. as shown in Figure 3.27. Click OK to close the summary options dialog box then Next.
  7. From the layout dialog box, select the type of layout such as stepped, block etc. Select page orientation i.e. either portrait or landscape then click Next.
  8. In style dialog box, specify the report style by selecting either bold, casual etc.
  9. Finally enter the name of your report then click finish. The report will be displayed on the screen in print preview mode.

 

Creating a report in design view

Just like with forms, you can create a report in design view by placing controls on the report design grid.

 

To design a report in design view:

 

.’

  1. In the database window, click the Reports tab then New.
  2. In the New Report dialog box, click Design view.
  3. Click the name of the table or query you want to generate a report from.
  4. Click the OK button. You will get a report design grid where you can place data controls.
  5. From the view menu, click Field List.
  6. To design the layout, drag each field from the field list to the layout grid and drop it where you want the data column to appear.
  7. Once you finish placing controls, click the Save button.
  8. In the save as dialog box, enter the name of the report and click OK.
  9. To view the report, click the Print Preview button. Alternatively, click Print Preview from the file menu.

 

Modifying a report layout

To modify headers and footers:

  1. Open the report in design view.
  2. Click the report header or footer you want to modify.
  3. Make the necessary changes and then click the Save button.
  4. Click the Print Preview button to view the changes.

 

To add more controls onto the report layout:

  1. Open a report in design view.
  2. Display the field list by clicking the Field list button or using the View.
  3. Select one or more fields in the field list and drag view to the Report design grid.

 

To resize or move a control:

  1. Click at once to select it. Position the mouse pointer to on the place holder, until the mouse pointer changes to a double-sided arrow. Drag the pointer to resize the control
  2. To move a control, select it and place the mouse pointer on the place holder until it changes to a hand.

 

Creating labels

A label is a sticker or piece of paper put on an item for the purpose of identification. Examples of stickers are mailing labels, label on the floppy disk where you write your name etc. Using the report label wizard, Microsoft Access lets you easily create labels of different sizes.

To create a label using the report wizard,

  1. Open the your database
  2. From the database window, click the Report tab then New
  3. From the New Report dialog box, select Label Wizard the table or query from which the labels are to be generated from.
  4. Label wizard starts running as shown in Figure 3.28.
  5. From a series of dialog boxes displayed, specify the label size, font, and fields to be included in the label, whether to sort the labels, the name of the label then click Finish.

 

Modifying labels

Just as you can modify a report or a form, you can also modify a label by manipulating the layout controls.

To modify a label,

  1. From your database window, click the Report tab then the Design View button.
  2. The label design grid is displayed. Edit the layout as desired, save and close the design grid.
  3. To view the modified label, click the Preview button from the database window.

 

Printing the report and labels

Before you print a report or a label, you should first set the page options i.e. the margins, paper size and orientation.

  1. Open the database that contains the report you want to print.
  2. Click the Report tab, select the report you want to print then click the Preview button.
  3. From the File menu, click Print.
  4. Set the printer options i.e. the printer type, print range and number of copies.
  5. Click OK to print.

 

 

DESKTOP PUBLISHING (DTP)

 

Chapter outline

 

4.1 Introduction.

4.2 Definition of desktop publishing.

4.3 Purpose of desktop publishing.

4.4 Types of desktop publishing software.

4.5 Designing a publication.

4.6 Manipulating text using the toolbox

4.7 Editing a publication.

4.8 Formatting a publication.

4.9 Printing a publication.

 

Introduction

Have you ever asked yourself how newspaper and book publishing companies manage to produce publications that are attractive with creative layouts and graphics in large volumes? They do this through a special process called publishing. Publishing is the process of producing publications like newspapers, cards, pamphlets, pictures, calendars etc. that have special text and graphical layouts and designs. The traditional method of publishing involved drawing and writing manually on wooden or metallic boards. The artwork would then be painted with ink and pressed on papers to produce a printout. This was a very tedious work.

 

Today the art of publishing has changed because of the advent of personal computers and smaller printers that are able to print high quality text and graphics even in an office or at home.

 

Definition of desktop publishing (DTP)

Desktop publishing refers to the process of producing publications like cards, newspapers etc. by designing their text and graphics layout and inserting, editing, formatting and printing of text and graphical objects using a special desktop publishing software installed on computers. The term desktop means that all the publishing processes can now be done on a desk in the office or at home using a personal computer! The difference between a desktop publisher and a word processor is that a desktop publisher software gives the user more tools and control of the page layout, text manipulation and graphic design than a word processor.

 

However it is important to note that some word processors today have also been incorporated with text and graphic formatting and editing tools. Hence a thin line exists between them and the desktop publishers. For example you can design a full publication in Microsoft Word by using the available drawing and picture tools, create columns etc.

 

Examples of desktop publishers include Adobe PageMaker, CorelDraw, Microsoft Publisher and Ventura. This book will use Adobe PageMaker to demonstrate the concepts of desktop publishing.

 

Purpose of desktop publishing software

Desktop Publishing programs are very popular in publishing because they give the person designing publications (typesetter) a lot of control on:

Graphic design: Using desktop publishing software, a typesetter can create and edit very complex text and graphical objects like pictures to the finest details. For example, the software provides the user with rulers and ruler guides that can be used to place an object in exactly the correct position.

Page layout design: With a desktop publisher, the user can be able to design a page layout by setting consistent picture and object locations, dividing a page in a number of columns and creating layers. A layer can be viewed as the arrangement of objects on top of each other with the one on top being on the first layer e.g. text can be on one layer while graphical objects on another. Therefore the text layer can be manipulated separate from the graphical object layer like for example text moves separate from the objects. Another good example is you can make the graphical object layer transparent in order to make the text in a layer behind the object visible.

Printing: Because the main purpose of any desktop publisher is to produce publication s, this cannot be accomplished without printing. Desktop publishing software therefore helps the user prepare what is referred to as an artwork in commercial circles for printing.

 

Types of desktop publishing software

There are two main types of desktop publishing software:

Graphical based: They are specifically developed to edit and format graphic objects like pictures. Examples are Adobe Photoshop, Corel Draw, harvard graphic etc. This desktop publishers have superior image handling capabilities like setting resolution, brightness, contrast, cropping and filling images of all types with colour.

 

Layout based: These types of desktop publishers are specifically developed to create different page layout designs for text and pictures. Have you ever wondered how the complicated front page of a newspaper is developed? It is difficult to achieve such without a good layout based DTP. Good examples of layout based desktop publishers are Adobe PageMaker and Microsoft Publisher.

 

Designing a publication

Publications vary in design and formatting. For example, a card has a particular design layout that is different from a newspaper. Therefore, publication designs determine how they are classified.

 

Types of publications

It is possible to produce different types of publications using a desktop publishing software. There are several types of publications that can be published namely:

Cards: These may be for weddings and other special occasions like graduations and for congratulations.

Certificates: To show completion of courses and special events. These type of publications are very sensitive because they must be designed to discourage any type of duplication or counterfeits.

Newspapers, magazines, pamphlets and newsletters: Have news targeting a group of people. They may have many text and graphical layouts and designs.

Books: Are bulky publications with many pages bound together in the same publication.

Calendars: Apart from showing dates, they are used by companies to advertise their products hence most of them have heavy catchy graphics.

 

Running Adobe PageMaker

Currently PageMaker versions 6.5 and 7.0 are the most common desktop publishing software developed by Adobe PageMaker. Other Adobe products includes Adobe Photoshop mainly used for editing and formatting photographs, Adobe illustrator used for creating complex freehand artwork such as drawings and logos etc.

 

Starting Adobe PageMaker

  1. Click the Start button and then point to Programs
  2. From the programs sidekick menu, point to Adobe group then select PageMaker. Figure 4.1 shows how to start PageMaker in a typical Windows environment.
  3. The PageMaker program starts and provides the Document Setup dialog box. If the Document setup dialog box is not displayed, then click File menu and select the New command.
  4. In the Document Setup dialog box similar to the one in Figure 4.5 specify the publication setup options.
  5. Click OK to apply the selected options. A publication window similar to the one in Figure 4.2 is now displayed.

 

PageMaker screen layout                                                       .

The PageMaker application window looks like most application windows for programs you have used before. It also has a title bar, menu bar and scroll bars. However, you will note that unlike most of the Microsoft applications you have used before, Adobe PageMaker does not have a status bar on its application window. The most notable difference between a desktop publishing software such as PageMaker and a word-processing software such as Microsoft Word is that a desktop publishing software

 

has its printable work area centered on a pasteboard as shown in Figure 4.2.

The PageMaker publication window is made up of the following layout components:

 

  1. The pasteboard. 3. The toolbox. 5. Rulers

 

  1. The printable area. 4. Master pages.
  2. Control pallete.

 

The pasteboard

A pasteboard is a large blank area where you place text and graphical objects before arranging them neatly on the printable work area enclosed with margins.

 

The printable area

It is the area that looks like a page surrounded by margins on the pasteboard. Any object or text that is placed on the printable area will be printed by the printer.

 

The Toolbox.

This is a set of buttons that contains various tools you can use to create and manipulate your publication it has the following tools

 

Line tool

Rectangle tool

Ellipse tool

Polygon tool

Hand tool

Pointer tool

Rotate tool

Text tool

Cropping tool

Constrained tool

Rectangle frame tool

Ellipse frame tool

Polygon frame tool

Zoom tool

 

The function of each tool can be summarised as follows:

 

 

Tool

 

Purpose

 

Pointer

 

Select, move, and resize text blocks and graphical

objects

Text

 

Type, select, and edit text.

 

Rotating Select and rotate objects.

 

Cropping

 

Crop i.e. trim imported graphics
Line Draw straight lines in any direction
Constrained line Draw vertical or horizontal lines.
Rectangle

 

Draw squares and rectangles.
Rectangle frame

 

Create a rectangular placeholder for text and Graphics.
Ellipse Draw ellipses and circles
Ellipse frame Create a circular or oval place holders for text and graphics
Polygon Draw basic polygons such as triangles, pentagons, stars etc
Polygon frame Create polygonal place holders for text and graphics
Hand Scroll the page or to preview and test hyperlinks
Zoom Magnify or reduce the area of the page

 

Master pages icons

At the bottom of the publication window is a bar that holds icons representing each page in the publication. These icons are called page thumbnails. To move to a page, just click its thumbnail. When you click the master page thumbnail(s), the master page(s) are displayed. A master page is used to design the general layout that needs to be applied in all other pages of the publication. (Figure 4.4)

 

Rulers

Each publication window can include horizontal and vertical rulers. They extend along the top and left borders of the window. You can display rulers when you need them and hide them when you want more room on the screen to view a publication. The rulers must be visible to help the user to manually create ruler guides, which are nonprinting extensions of the ruler as well as measure an object size.

 

Control pallete

It is a shortcut toolbar mainly having text and paragraph formatting command icons.

 

Setting up a publication

Sometimes, it is necessary to change the setup options of a publication e.g. page size, margins, orientation etc.

 

To change publication’s setup:

  1. From File menu, click Document Setup. A dialog box such as the one shown in Figure 4.5 appears.
  2. Select the following page set up options:

(a) In the Page size list box, select the appropriate size. When you select a page size, its dimensions appear in the Dimensions text boxes. Alternatively select custom size then use the dimensions text box to specify a custom page size of up to 1065 by 1065 mm.

(b) Select page orientation by either clicking Tall for portrait or Wide for landscape orientation.

(c) Click Double-sided to set inside and outside margins to accommodate binding on pages that will be printed on two sides.

(d) Click Facing pages if you want left and right pages displayed   together as a two-page spread on the screen.

(e) Enter the number of pages you initially plan for-the publication.

(f) Click OK to effect the changes.

 

Setting up a publication using master pages

If you are creating a publication that will have several pages such as a book or a project report, it is important that you layout a common layout foundation for all pages for the sake of consistency and cohesiveness. These pages used to design a common layout to be applied in the other pages of the publication are called master pages or a document master.            You can create, modify, and delete objects on master pages just like any other objects, but you must do so from the master pages themselves.

 

The document master applies to all pages in the publication until you’ specify otherwise, and cannot be renamed or removed from the publication. To switch to master pages, simply click the master page icon(s) then:

  1. Place non-printing ruler guides on the master pages to help you place text and graphics accurately and consistently throughout your publication. Non-printing ruler guides are vertical or horizontal lines

. you place on printable area. You place the guides by positioning. the mouse pointer on the ruler then dragging the guide to the required position.

  1. Create basic design elements on the master pages, including text and graphics that you want to appear on each page in your publication.

 

Setting up margin guides

Margin guides are very important because they define the printable area of your publication.

 

To change margin settings;

  1. From File menu, click Document Setup
  2. In the Setup dialog box

(a) For a double sided document enter the values for inside and outside margins to accommodate binding for a document that will be printed on both sides. For Single sided pages, set the left and right margins.

(b) Enter the value for the Top and Bottom margins.

  1. Click OK to close the setup-dialog box and effect the changes.

 

Saving the layout

Once you complete setting up your publication layout, it is important you save it before you start entering text and graphics.

To save the layout:

  1. To save the publication for the first time, from the File menu, click Save As or click the Save button on the toolbar.
  2. In the Save As dialog box, specify the name of the file and the storage location of your publication then click Save button
  3. To save changes made to a publication, from the File menu, click Save.

 

Displaying and hiding rulers

If the rulers are not displayed, click the View menu, then Show rulers to display them. To hide the rulers, click the View menu then Hide rulers.

 

Selecting ruler measurement units

It is possible to set different measurements on both rulers. For example, you can set the vertical rule in millimetres and the horizontal in inches. Therefore if you want to use common units, you must set each ruler measurement independently.

 

To set the measurement units,

  1. Right click a ruler separately. A drop down list displays available measurement systems that is inches, decimal, millimeters, picas and Ciceros as shown in Figure 4.6 below. If you are not familiar with some of these units, it is advisable you use millimeters.
  2. Select the measurement system option you want to use.

 

Manipulating text using the toolbox

 

Manipulating text

 

Using text tool

To create a text block with the text tool:

  1. Click the text tool from the toolbox. The pointer turns into an I-beam.
  2. On an empty area of the page or pasteboard click or drag a rectangular area to define a text block or frame. If you click without dragging, a text block the width of the column or page will be created. It is the text frame that defines the space you want the text to occupy. The borders of a text block remain invisible until you click the text with the pointer tool.
  3. Type the text you want.

 

Using text frame

You can create text by using a frame tool or by converting any object you have created with the drawing tools except a line into a frame. Text frames do not change height or width as you add or remove text.

 

To add text into a frame:

  1. Draw a frame using any of the frame tools that defines the shape you want the text block to take. Alternatively select a drawn shape, from Elements menu, point to Frame then click Change to Frame.
  2. Do one of the following:

(a) Click the text tool, click in the frame, and then type or paste text from the clipboard

(b) From the File menu click Place, double-click the file that contains the text you want to place in the text frame. When the cursor becomes a loaded icon, click inside the text frame to place the text.

 

You can also add text into a text frame by:

  1. Selecting a text block, hold down Shift, and then select an empty frame.
  2. From the Element menu, point to Frame and click Attach Content. The text flows into the frame and the text block disappears.

 

Manipulating graphical objects using the toolbox

The toolbox has several graphic drawing tools. For example, the polygon tool helps a person to draw polygons and the ellipse tool is used for drawing circular objects. All these tools enables a person to apply stroke and fill patterns. For more complex graphics, PageMaker allows a person to import pictures from other applications and to place them in the publication. A stroke refers to a line style while a fill refers to applying patterns such as shading. Figures 4.7 (a) and 4.7(b) shows examples of fill and stroke respectively applied to simple rectangular graphical objects drawn using the polygon tool.

 

Applying stroke and fill

Once you create a graphical object, you can enhance it by applying stroke and fill. To apply stroke or fill:

  1. Select the object you want to apply stroke or Fill.
  2. From the element menu either point to stroke to apply a line style or fill to fill the object with a background colour or pattern. Alternatively, click the fill and stroke command to set the fill and stroke options in the dialog box as shown in Figure 4.8.

 

Moving and resizing text and graphical objects

Once you create text and graphical objects, you can adjust the size, shape, or location of an object.

To move a text or graphical object:

  1. Click the object to select it then position the pointer tool anywhere inside the text or object.
  2. Drag the text or object to a new position.

 

To resize text or object:

  1. Select the text or object with the pointer tool. Selection handles are displayed at the comers of the text block or the object. 2. Position the pointer on the selection handle and drag to the required size.

 

Editing a publication

The term edit means making changes to a publication. In most cases, editing would include the process of correcting spelling mistakes, replacing words etc.

 

You can search for specific occurrences of a word or group of words in your publication and make the necessary changes. PageMaker comes with two special editing tools namely the Find and Change tool and the Spelling tool.

 

Before editing the publication, you must open it in the story window. PageMaker defines each text block as a story. Once text is in PageMaker, it is part of a story. A story is a text block that PageMaker recognizes as a single unit. A story can be one letter or several hundred pages of text, and can be contained in a single text object or threaded through many different ones.

 

Find and change tool

This editing tool helps a person to search for a particular word or a phrase and replace it with another one. To find and change a word and or a phrase in the publication:

  1. Using the text tool, click an insertion point in a story, or select a range of text if you want to limit your search to that section.
  2. Click Edit menu then select Edit story command. The publication now opens in the story window showing only the text but not the graphical objects.’
  3. Click Utilities then Find or Change. A dialog box such as the one shown in Figure 4.9 is displayed.

4 In the Find What text box, type or paste the text you want to find. To change the text, type new text in the Change To text box. To search for formatting only, leave the text boxes blank.

  1. Select Match Case and Whole Word as appropriate.
  2. In the dialog box, specify the formatting to search for and, if appropriate, how you want to change it, and click OK
  3. Select options to determine the scope of the search e.g. in all open publications or only the current one. If you search the current publication only, select Search Story option.
  4. Click Find to begin the search.
  5. Click Find Next to continue with the search operation
  6. Once you are through, click Story menu then Close Story. Alternatively press Ctrl+W.

Spell checking

To check spelling in one or more publications:

  1. Click the insertion pointer anywhere in the publication or select the range to be spell checked.
  2. From the Story Editor menu, choose Utilities then Spelling. A dialog box as shown in Figure 4.10 appears.
  3. Specify the scope of the search either as:

(a) In selected text.

(b) In the current story only.

(c) In all stories in the publication.

  1. Specify spell checking options:

(a) Checking alternate spellings lets you see suggested replacements for misspelled words.

(b) Checked show duplicates displays/repeated words.

  1. Click the start button and spell checking begins.

 

Formatting a publication

This refers to applying special attributes to text, graphical objects and pages in order to make them attractive and appealing to the eye. Therefore, formatting may include things like font sizing, bolding, changing text colour, adjusting picture brightness and contrast and formatting columns on the page.

 

Text and paragraph formatting

To format your publication, you can either use commands available in the Type menu or a control palette. The Control palette is a strip that contains command buttons and list boxes that let you assign attributes to text and graphical objects:

 

To display the control palette

From Window menu, click show control pallet The Control palette appears floating on top of your publication (Figure 4.11). You can move it by dragging the bar at the left edge of the palette.

The contents of the Control pallete  vary. Depending on which tool is selected from the toolbar or from itself. The two types of control palettes are the object mode and text mode. The text mo e can be selected by clicking the Character view or paragraph view button. There are two types of text modes namely;

  1. The character view that is, when the T tool on the pallete is selected. This means that you can apply character attributes to selected text. Character attributes determine how text looks on the page. such as font type, size, or style (bold, italic or regular).
  2. The paragraph view that is, when you select a paragraph and you click the button below the T on the control palette (labelled M) in Figure 4.11. Figure 4.12 is displayed. You can apply paragraph styles, select alignment options, and other paragraph attributes.

In object view i,e. when a graphical object is selected, it lets you apply attributes related to the object such as rotating, moving, resizing etc.

 

To format text:

  1. Using the text tool, select the text you want to format.
  2. From the Type menu of the Control palette, choose the formatting attribute you want.

 

To format several text attributes at once

  1. With the text tool, select the text you want to format.
  2. From the type menu, click character command
  3. In the Character Specifications dialog box select text attributes such as font, size, type, colour, position (normal, subscript, superscript etc.) then click ok

The simplest way to format text attributes is by using the control palette. In character view the control palette has the following main formatting sections

 

  1. Font list box and style buttons
  2. Font size and leading list box
  3. Tracking and Horizontal scale

 

Changing text colour

  1. Select the text.
  2. From Window menu choose Show Colors.
  3. In the colors dialog box, click the Colors tab.
  4. Select the colour you wish and it will apply on the selected text.

 

Changing case

As with Microsoft Word you can also change text case to upper or lower case, sentence case e.t.c.

To change case:

1 Select the text you want to change case.

2 Click Utilities menu, point to Plug-ins, and then click Change case. Change case dialog box will be displayed as in Figure 4.1

3 Select the case you want

  1. Click Apply to preview the change
  2. Click OK to close the dialog box.

 

Formatting text to superscript and subscript

Superscript refers to text that is positioned slightly higher than the rest on the same line e.g. the power of 3 in 103 while subscript refers to text slightly below the same line such as the number 2 in H2O. To format text to superscript or subscript;

1     Select the text you want to style as superscript or subscript.

2     From Type menu, click Character and the dialog box in Figure 4.14 appears.

  1. In the Character dialog box, select either superscript or subscript from Position list box as shown then click OK.

To remove superscript or subscript format:

  1. Repeat step 1 and 2 above
  2. In the character dialog box, select Normal from Position list box, and then click OK

 

Drop cap

D

rop cap refers to text formatting where the first character in a line is bigger and drops down to occupy the space in the next lines as shown by the first letter D in this paragraph.

 

To apply drop cap:

  1. Select the character you want to drop
  2. Click Utilities menu, point to Plug-ins, and then click Drop cap.
  3. Specify the number of lines you want the character to occupy in the Size box as shown in Figure 4.15.
  4. Click Apply to preview the format and then OK to close the dialog box.

Paragraph formatting

You can use either the Control palette to format a paragraph or Paragraph command from the Type menu. However the later lets you apply formatting that is not available on the Control palette.

 

Setting indents and tabs

Indents and tabs are powerful tools for positioning text. Indents move text inward from the right and left edges of a margin while tabs position text at specific positions. You can set indents by moving the indent markers in the Indents/Tabs ruler, typing indent values in the Paragraph dialog box or type indent values on the Control palette in paragraph View.

 

To set tabs using the Indents/Tabs ruler:

  1. Select the paragraph or paragraphs you want to indent.
  2. From Type menu, click Indents/Tabs.
  3. On the Tab ruler, click a tab-alignment icon (left, right, center, or decimal) for the first tab you want to set. See Figure 4.16.
  4. Drag the new tab marker along the ruler
  5. If you want the tab leader, click the Leader button then choose the type of leader you want.

To set indent using the Control palette:

  1. Select a paragraph or paragraphs you want to indent.
  2. On the Control palette, click the paragraph-view button.
  3. Type values for the indents in the Indent text box then press the Enter key.

 

To set an indent using the Paragraph command:

  1. Click an insertion point in a paragraph, or select a group of paragraphs.
  2. From Type menu, select Paragraph.
  3. Type values for the Indents options, and then Click OK.

 

Adding space above or below paragraphs

You can control the vertical space between paragraphs by specifying the amount of space before or after selected paragraphs or all paragraphs of a certain style.

NB: PageMaker never inserts space before a paragraph set to begin at the top of a column or page (using the Page Break Before or Column Break Before attribute). For those cases you must add the extra space manually by typing one or more paragraph returns.

 

To increase or decrease space before or after a paragraph:

  1. Select the paragraph you want to edit.
  2. Choose Type then Paragraph.
  3. In the paragraph Space options, specify the values you want in the Before and After text boxes.

 

Page formatting

This refers to formatting the whole page and may include things like column guides.

 

Columns guides

Column guides helps you divide the pages into columns that make the publication look more organized. The idea is to divide a large page into short readable sentence sections. Imagine if a newspaper page was not divided into columns! Therefore columns are mostly used in designing large publications, newspapers and journals. The difference between column guides and margin guides is that margin guides are around the edges of the printable page while column guides may split the page at the center. PageMaker. marks margins with a blue line but column guides with pink coloured lines.

 

To setup more columns:

  1. Turn to the publication page or master page
  2. From Layout menu, choose Column Guides. You can setup column guides separately in a double sided facing pages by clicking Set left and right pages separately check box as shown in Figure 4.17.
  3. Enter the number of columns you want on the page and the space you want between columns. If you are setting left and right pages separately, enter values for both pages.

4Select Adjust Layout if you want existing text and objects on the page to adjust to the revised column setup.

  1. Click OK.

 

Moving and locking columns

You can move the column guides by dragging them. The two lines forming the gutter between columns move in pairs and the space between the two lines remains consistent. Text and graphics already on the page are not affected when you drag column guides. Once you have set up your columns, you can lock them in place to prevent accidental moving.

 

To lock or unlock column and ruler guides:

From View menu, click Lock Guides.

Page numbering

To print page numbers in a publication, you must set the page numbers in the master pages. You do this by adding a page-number marker (a special character) that keeps track of the page order in the publication and ensures that each page is numbered correctly at all times.

 

To add page-number markers to master pages:

  1. Click the master page(s) icon
  2. Click where you want the page number to be placed.
  3. Press Ctrl + AIt +P. Page-number markers appear as RM (right master) or LM (left master) on the master pages but actual page numbers are displayed on each page of your document.

 

Changing page number style

By default, PageMaker applies the Arabic page numbering style ie 1,2,3,…..

 

To change the style:

  1. From File menu click Document Setup.
  2. In the Page setup dialog box, click Numbers.
  3. Select the numbering style you want to use then click OK to close the Page Numbering dialog box.
  4. To start page numbering from another number other than the default

one ( which is usually 1), type the starting page number in Start

Page # box in the Document setup dialog box.

 

Rearranging pages

In PageMaker, you can change the order of your pages by rearranging page thumbnails (icons at the bottom of the window that represent pages). Changing the order of pages does not affect the text objects in your publication even though they may have moved to different pages.

 

Sorting pages

  1. From Layout menu, click Sort Pages.
  2. Select the page or pages you want to move either a single-sided page or a pair of facing pages. To select one page in a pair of facing pages, press Ctrl and click the page.
  3. Drag the selection to the location you want. To insert a selection between a pair of facing pages, press the Ctrl key and drag the selection over the facing pages. Notice that a black bar indicates where the selected pages will be inserted.
  4. Release the mouse button to drop the page onto the new position. PageMaker automatically renumbers the pages. The original page icon appears dimmed and another page icon appears beside the thumbnail to indicate its new page number.
  5. Click ok to change the page order.

 

Inserting page and column breaks

Sometimes you may want certain text or paragraphs such as a new chapter to start at the top of a column or page regardless of editing or reformatting elsewhere in the document.

 

To set a page or column break:

.

  1. Select the paragraph or text you want to move to another column or page.
  2. From type menu, select paragraph to display the paragraph specifications dialog box.
  3. Check Column Break Before to force the paragraph to start at the top of the next available column or page break before as shown in Figure 4.19 to force the paragraph to start at the top of the next available page.

Adding headers and footers to a publication

A header refers to a line of text such as a page number, date, or a company name usually printed on the top margin of each page in a large document.

 

A footer on the other hand is a line of text printed in the bottom margin.

 

You can use the same header and footer throughout or use running headers and footers that indicates the content of each page as is the case in dictionaries, telephone and address directories.

 

Defining consistent headers and footers

To define header or footer common throughout the publication

  1. Click the master page(s) icon
  2. At the top of the page, click where you want header to appear or at the bottom click where you want the footer/header to be placed.
  3. Type the text that you want displayed on every page in your publication.

 

Defining Running headers and footers

1 Select the text block you want to use to create running headers and footers using the pointer tool.

2 Click Utilities, point to Plug-ins and then select Running Headers and Footers. A dialog box such as the one shown in Figure 4.20 is displayed with preview page that helps you correctly position the header or footer.

  1. Click the place icon and drag the header/footer place holder onto the text page.
  2. From content list box, select the words that will be used as headers or footers on every page e.g. the first word in the first paragraph then click Add. You can click the Preview button to preview the running headers and footers
  3. Click ok

 

Tracking and Kerning

Tracking refers to changing the visual denseness or openness of characters in a line while kerning is fixing particular pairs of letters that are too close or too far apart from each other such as To, Ta, We, we, Wo etc.

 

To apply a track:

  1. Select the text you want to track.
  2. From Type menu, choose Expert Tracking.
  3. Choose one of the five tracks options i.e. No Track, Loose, Tight or Very Tight as shown in Figure 4.21.

 

Very loose,

 

To automatically kern a pair of characters:

  1. Select the text you want to kern.
  2. From Type menu, click Expert Kerning
  3. In the dialog box such the one shown in Figure 4.22, click the appropriate slider button to make the text either tighter or looser.
  4. Click OK to apply the expert kerning.

 

To set a word or letter spacing:

  1. Select one or more paragraphs.

2.From the Type menu, click Paragraph to display the dialog in Figure 4.23.

  1. In the Paragraph dialog box, click Spacing to display Spacing dialog box.

4.In the Word Space or Letter Space text box, type new values.

  1. Click OK.

 

Measurements

 

Using rulers to measure objects

When using Page Maker, you can be able to design page layouts and graphics that are exact in measurement as specified using the horizontal and vertical rulers. The idea is to drag ruler guides to mark an area of the screen where you want to insert graphics or text that can fit in the guides.

For example, to draw a rectangle of 5cm by 5cm, set the rulers to measure in millimeters then drag and place ruler guides from the horizontal and vertical rulers to create a 5 x 5cm region on the screen. Finally, select the polygon tool and drag a polygon that fits exactly inside the marked region as shown in Figure 4.24.

 

Formatting graphical objects

Using the PageMaker tools and formatting effects, you can create very complex graphical objects.

Changing fill and stroke of graphics

To change fill or stroke of an object:

  1. Select the object by clicking it.
  2. From Element menu click Fill and Stroke.
  3. Select the type of fill or stroke you want.
  4. Select colors for the fill and stroke.

To apply fill:

  1. Select the object
  2. From Element menu, point to Fill then select the fill pattern you want to apply.

To apply stroke:

  1. Select the object
  2. From Element menu, point to Stroke then select the line style you want to apply.

 

Reshaping objects

To apply rounded comers to rectangles and squares:

  1. Select the rectangle or square you want to change comers
  2. From Element menu, choose Rounded Corners.
  3. Select the comer style you want, and then click OK. Figure 4.25 shows one rectangle without and another with rounded corners.

 

Reshaping a polygon

Once you draw a polygon, you can change it from the default rectangle or square to triangles, pentagons, hexagons and even a star.

To reshape a polygon:

  1. Select the polygon you want to reshape.
  2. Double click the selected polygon. PageMaker displays reshape placeholders.
  3. Reshape the polygon by dragging the vertices place holders.

 

To set the number of sides or create a star object:

  1. Select a polygon you want to reshape,
  2. From Element menu click Polygon Settings,
  3. In the Polygon settings dialog box, specify the number of sides you want, from three to a hundred.
  4. To create a star, enter a value in the Star inset box. A value of 0% means no star while 100% represents a star whose vertices meet at the centre.
  5. Click OK.

Copying an object:

  1. Select one or more objects.
  2. From Edit menu, choose Copy.
  3. Position the insertion pointer where you want to place the object.
  4. From Edit menu, select paste.

 

NB: You can quickly copy an object by right clicking it then selecting the copy command on the shortcut menu then paste in a new location. Alternatively, select the object then press Ctr+C to copy and Ctrl +V to paste in a new place.

 

 

Wrapping text around a graphical object

One of the best ways to enhance a publications visual impact is to wrap text around graphical objects. Wrapping determines how text behaves around an object. For example, you can select a wrap that makes text to surround an object without displacing it as shown in Figure 4.27(a).

 

To wrap text around an object:

  1. Select the object.
  2. From Element menu, choose Text Wrap to display the dialog box in

Figure 4.27(b).

 

  1. Click the middle wrap option as shown in Figure 4.27 (b)
  2. Specify a Text Flow option. The leftmost icon makes the text jump the object to the next page or column, while the middle icon allows text to jump over the object and continue on the same page. The rightmost icon creates a rectangular text wrap around all sides of an object.
  3. Enter standoff value (distance of the text from each side of the graphic) for the boundary.
  4. Click OK and notice how the text wraps around the object.

 

Importing graphics

You can import a graphic or text directly from another file or application by using a process called placing in PageMaker. In most cases, graphic files will be created in graphical based desktop publishers or picture editing software then imported into PageMaker. PageMaker has a very powerful object import engine that can be activated by the Place command.

 

The Place command is the main importing method. When you place text or a graphic, PageMaker establishes a link to the source file on the storage device (unless the file is an HTML document).

To import a graphic:

  1. Click the pointer tool. Select the frame in which you want to place the graphic. If you do not wish to place it in a frame then ignore this step.
  2. From File menu choose Place.
  3. Select the file you want to place, and then click the Open button.
  4. The cursor changes to become a loaded icon. Clicking any place on the paste board will place the new graphic at the clicked location.

NB: If you place using text tool, then the graphic that will be placed will be an inline graphic contained within the text object and will behave like text. It will become hard to format it separately as an object.

 

Grouping and ungrouping objects

You can group several objects into one, especially if you want to format, resize or move them as a single entity.

 

To group objects:

  1. Using the pointer tool, hold down the shift key as you click the objects to be grouped. This selects multiple objects.
  2. From Element menu, choose Group or simply press Ctrl + G on the keyboard.
  3. To select an object within the group then press Ctrl as you click the object.

To ungroup objects:

1, Select the Group.

  1. From Element choose. Ungroup.

 

Locking objects

You can lock individual objects in place in order to help preserve the design of your pages through all stages of production. You can change the attributes of a locked object, provided the change does not affect the object’s size or position. For example, you can change a colour or fill applied to a locked object, but not its degree of rotation or its skewing angle.

 

To lock or unlock an object:

  1. Select the object.
  2. From Element choose Lock Position to lock. Otherwise select. Unlock to unlock a locked object.

 

Rotating an object

The process of rotating an object falls under a group of operations called transformations because rotation changes the angular placing of an object. Other transforming operations include skewing and reflect­ing objects. However, this book limits itself to rotating objects.

To rotate an object with the rotating tool:

  1. Select the object.
  2. Select the Rotation tool from the toolbox. The pointer changes and becomes a Star bust.
  3. Position the Starburst at a fixed point or around the centre of the object.
  4. Drag the starburst away from the fixed point, in the direction you want to rotate the object. To rotate an intervals of 45 degrees, press Shift as you drag clockwise or anticlockwise. The rotation lever helps you control the amount of rotation. The farther you drag the starburst away from the fixed point, the more control you’ll have when you rotate the object.
  5. When the object is in the desired position, release the mouse button.

 

Cropping an object

When you import a graphic from another program or publication, you can cut off unwanted parts of the graphic starting from the edges that you do not want to print by the crop place holders.

 

To crop a graphic using the cropping tool:

  1. Select the cropping tool, then the graphic that You want to crop to display the place holders.
  2. Position the cropping tool so that the place holder shows through the center of the tool.
  3. Hold down the mouse button to turn the cropping tool into a double sided arrow, and drag inwards until only the part of the graphic you want in your publication remains. To show more of the graphic, drag away from the center of the graphic.
  4. To move the graphic within its frame, position the cropping tool at the centre of the graphic and hold down the mouse button. (in Windows, hold down the left mouse button.
  5. When the hand appears, drag until you see the part you want to appear in your publication, then release the mouse button. .

 

Printing a publication

Because. the main purpose of any desktop publisher is to produce publications, it is impossible to do so without printing. The choice of a printer depends on the quality of hardcopy desired.

 

To print a publication:

  1. From File menu, click Print. A dialog box appears in which you can

specify the following:

(a) The printer that you wish to use.

(b) The range of print in the Ranges box if you do not wish to print whole document.

(c) Number of copies to print per page in the Number of copies box.

(d) Whether to print blank pages or not.

(e) The print orientation.

(f) Whether to print both pages.

2 Click Print to start printing.

 

 

 

INTERNET AND E-MAIL

 

Chapter outline

 

5.1 Introduction.

5.2 Definition of the internet.

5.3 Development of the internet.

5.4 Importance of the internet.

5.5 Internet connectivity requirement.

5.6 Internet services.

5.7 Accessing the internet.

5.8 Electronic mail.

5.9 Accessing information on emerging issues.

 

Introduction

Computers can be connected together using data transmission media like cables, to communicate with one another. Communication in this case will be in the form of exchange of data and information. Such interconnection of computers to achieve message transfer is called networking. This is because the computers are linked to form a net.

 

In most cases computer networks are unique to an organization. For example the computers in your computer laboratory may be networked. Such a network is local in nature hence it is usually called a local area network (LAN).

 

Definition of the Internet

The term Internet can be broken down into two words, inter and net which implies that there is an interconnection of networks. Internet is therefore a large network of networks that covers the whole world and enables millions of computers from different organizations and people

To communicate globally. Because of its large size and great volume of information that passes through it, it is sometimes called the information superhighway.

 

Because of the flexibility of Internet technology, many organizations are creating their own private networks using the technology of the Internet. In this book we shall refer to the Internet (with capital letter I) as the information superhighway and the internet (with lower case letter (i) to refer to smaller networks.

 

5.3

 

Development of the Internet

In 1969, a research body in the USA called Advanced Research Projects Agency (ARP ) set up a computer network that connected four universities and was given the name ARPAnet. This network is viewed as the forerunner of today’s Internet. The aim was to allow sharing of data and information between computers. The main benefit was that there was fast communication between researchers through electronic mail or e-mail.

ARPA’s goal was to allow multiple users to send and receive information at the same time. The network used a special data transmission technique called packet switching which was later adopted for the Internet. A computer would send a packet that contained data, destination address information, error detection control information and packet sequencing information. By 1973 e-mail was the most common service on the Internet. It was not until 1979 that the first media companies connected to the Internet.

 

By 1981, many people had seen the importance of computer networking and the Internet. ARPAnet formed the backbone on which many organizations started connecting to, hence expanding it. The American military also became a big user of the Internet because they could communicate and tap into the resources available on the net. Next, the American Government decided to access the Internet for commercial purposes hence greatly increasing the traffic. By this time, for every twenty days, a new host computer was connected to the net.

 

By 1987, the Internet boasted of 10 000 host computers. However, its access was largely limited to the United States of America and some nations in Europe. As the importance of the Internet grew, businesses spent billions of dollars to improve it in order to offer better services to their clients. Fierce competition arose among software and hardware manufacturers as they came up with new technology to meet internetworking needs. The result was a great increase in message transmission capacity (bandwidth) and it became cheaper to work with the Internet.

 

By 1994, 3 million computers were connected to the Internet. Today, the Internet has grown and covered the whole world. Governments, private organizations and individuals are using the Internet in all spheres of daily life to send messages and conduct business.

 

Importance of Internet

The Internet is an extensive system of interlinked yet independent networks. It has evolved from a specialised communication network previously only used for military and academic purposes to a public network that is changing the way people carry out their daily activities.

 

The Internet is playing a very important role in all aspects of life, leading to the emergence of an elite society called the information society. The Internet’s importance can be between through its contribution to research, news and information dissemination, leisure and communication, a place to do business and many other profitable activities.

 

Internet connectivity requirements

For a computer to be able to connect to the Internet, there are several requirements one of them is to connect to a telecommunication service provider in order to transmit data over a wide region. This section seeks to discuss some minimum requirements for Internet connectivity to be achieved.

 

Telecommunication facilities

The Internet heavily relies on telecommunication facilities like the telephone lines, telephone exchange stations and satellite transmission in order to cover the whole wide world. Indeed, without these facilities, the Internet is as good as dead.

 

Therefore, a computer is connected to the external world through a telephone line and has to dial a remote computer on the net to establish a connection for data transfer. Dial-up connections, however, are quickly being replaced by dedicated digital data transmission telephone lines called dedicated digital leased lines. A leased line connection ensures constant and quick connection to the Internet unlike the dial-up that you need to dial every time you need to access the Internet.

 

Transmission of data on land takes the form of telephone exchange to telephone exchange until the data reaches the destination. However, intercontinental transfer of data is achieved by having satellite base stations transmitting g the data through a wireless uplink channel to the satellite. The satellite then sends the data signal to the base station on another continent where it is picked up and sent to telephone exchanges

 

For transfer to the destination computer. Figure 5.1 shows a simple logical illustration of the Internet.

Modems

A computer needs a special digital to analog and vice versa interface card called a modem that enables it to send and receive data on telephone lines. Remember that voice transmission on telephone lines is analog in nature while computers work with digital data. However, digital telephone lines make it possible for computers to transmit and receive digital data without a modem.

 

The word modem is short form for modulator – demodulator. During modulation, the data to be transmitted is changed from digital to analog so that it can be transmitted on the telephone lines. At the receiving end, the data is changed from analog to digital for the computer to understand it through a process called demodulation.

 

In most cases a modem is bought separately and plugged in one of the expansion slots on the motherboard. Some modems are external hence the computer may be connected to them through a network interface card. Most computers today come with an internal modem permanently fixed on the motherboard called an onboard modem.

 

Internet service providers (ISP’s)

These are companies that offer internet services to end users. For example, in Kenya, until recently, the sole gateway to the Internet for a long time was Telkom’s Jambonet. However, because Jambonet cannot meet the service needs for all users in Kenya, they lease some of their stake to Internet service providers like Africaonline@ and Swiftkenya@ who can now provide Internet services to the end users at a fee.

Internet software

The Internet interconnects millions of computers and telecommunication devices that have different configurations for hardware and software. Therefore, to achieve communication between these otherwise incompatible devices, special software called protocol is needed. A protocol is a set of rules that governs how two computers can send and receive data on the network.

 

For the Internet, the most common protocol is the Transmission control

Protocol (TCP) and Internet protocol (IP). As its name suggests, TCP governs how data is transferred from one place to the next, while IP determines the addressing system on the Internet. For example, each network and computer on the Internet is recognised by a special number called the IP address that enables data to be sent and received by it. These two are combined to form the TCP/IP protocol suite that is needed by any computer that needs to be connected to the Internet.

Internet services

The Internet has become very popular in today’s world because of the diverse but very important services that it offers to people. It is “seductive” i.e. once a person connects to it they find themselves falling in love with its power to provide information and services. The temptation is to continue using the Internet again and again.

 

The World Wide Web (www)

The World Wide Web can be viewed as a vast virtual space on the Internet where information pages called websites are installed. Most local area networks have a special computer called a server that stores information and data for others on the same network to access. In order to connect a network to the internet, the local area network needs an Internet server. This server is usually given the name world wide web (www) and has all the information that others on the Internet access. Hence, www is created by a network of Internet servers!

 

To enable easier access to information and data on the Internet, a standard method of preparing documents to be put on the Internet was developed. This method uses a special language such as hypertext markup language (HTML) to prepare documents called web pages that are  attractive and can be accessed on the Internet. HTML can be combined with other web page production tools to achieve wonderful websites. Individuals and organizations establish sites where their web documents can be placed

 

2for easy access by the external world. Such sites are called websites and each has a special address called a uniform resource locator (URL) that can be used to access them. For example, one common URL address is:

http://www.yahoo.com

The first part (http) stands for hypertext transfer protocol which is a protocol that transfers hypertext. www is the name of the Internet server (web server) on which the webpage resides. yahoo.com is usually called the domain name of the local area network. It uniquely identifies a particular local area network. On the Internet, two networks may have the same web server name but never the same domain.

 

Electronic mail (e-mail)

This is the exchange of electronic letters, data and graphics on the Internet.

Electronic commerce (e-commerce)

Many companies are increasingly using the Internet to sell and buy goods and services. This new business strategy where goods and services are sold over the internet is called electronic commerce (e-commerce).

 

One advantage of e-commerce is that a company can access customers all over the world and is not limited by space and time. Hence, small companies that establish websites to auction their goods and services not only reduce operating costs but increase their sales. For example, most vehicle importers buy vehicles directly from international dealers by accessing their websites and placing orders.

 

However, the major challenges that face e-commerce are that people deal with each other without ever meeting physically and there is lack of proper laws to govern such business.

 

Electronic learning (e-Iearning)

Apart from the fact that academic materials for all levels of education are readily available on the Internet (web), the Internet has opened the door for those who would like to do distance education programs and home schooling. Learning through interaction with special programs on the computer is called electronic learning (e-Iearning).

 

Internet fax

The Internet provides you with complete fax facilities from your computer. You can configure fax settings, send and receive faxes, track and monitor fax activity, and access archived faxes. Using fax, you can choose to send and receive faxes with a local fax device attached to your computer, or with a remote fax device connected to fax resources located on a network.

 

Other Internet services

  1. News media on the net. All major media houses post their daily news on the Internet for their clientele to access. Hence information about an event can be sent right round the globe within a very short time.
  2. Health information on the net. The Internet provides latest medical news and research findings for practitioners and scholars.
  3. Music and entertainment on the net. It is possible to listen to music on the web and to watch video clips if your computer is a multimedia machine.
  4. Chatting on the net. People can sign into a chat room and exchange ideas freely through discussion. Chat rooms are a common feature and usually put together people of common interest to exchange ideas. For example, if you sign into a chartroom for politics, then you can exchange political views with otherwise unknown Internet friends who can read your typed comments as you view theirs. Try accessing www. Try. Com to see listings of chat topics that you can participate in on-line. However, you need to be careful in selecting the people to chat with on the web because some people who use the chat rooms have intentions of harming others.

Accessing the Internet

There are many applications that enable a person to access the Internet. Such applications are called web browsers. Some of them have text interface while the most popular have graphical user interface. Perhaps, the most common browsers in the world today are Netscape Navigator and Internet Explorer.

 

Therefore before accessing the Internet, a person must start the browser software. This book will use Internet Explorer for demonstration,

  1. The back button returns the browser to the immediate former webpage.
  2. The next button moves the browser to the next web page in case a person had clicked the back button.
  3. The stop button tells the browser to stop searching/loading a website.
  4. The refresh button tells the browser to try accessing a web site address again after failure
  5. The search button enables a person to search for words on the website.
  6. Clicking the favorites button displays all web addresses in the’ favorites” folder.
  7. The history button displays the website addresses that were visited in the recent past.
  8. The mail button enables a person to view and send mail and WebPages to links.
  9. The print button enables a person to print the web pages.
  10. The Go button tells the browser to load the current web page whose address is in the address bar.
  11. The address bar allows the user to type the address of a website to be accessed.
  12. The home button moves the user to the first page of the website.

 

Log in/sign in

To access a website, type the full address of the website in the address bar then press the Enter key on the keyboard. If the Internet connection is working properly, the browser will start connecting to the requested web site or URL. Notice that the status bar will be reading something like “connecting to site www.yahoo.com “

 

Some web sites allow free access to all their pages by all visitors. However, others require people to be members hence a new visitor has to register (sign up) by filling some on-line forms. The registration process gives the visitor a user name and password that can be used to sign in or log on the website for each successive visit. This is very common for e-mail account providers like at www.mail.yahoo.com.

 

Websites that give users a chance to log in are better especially if the services offered need some degree of privacy and customizing for

Individual customers e.g. it would be a gross mistake to have everybody accessing the other’s e-mail account.

 

Surf/browse

Surfing or browsing is the process of accessing Internet resources like web pages and websites. This is done by either typing the URL address of a site in the address bar of the browser or by following special links that lead to web pages called hyperlinks.

 

Hyperlinks and search engines

A hyperlink is a text or picture on an electronic document, especially web page that causes other web pages to open when the link is clicked. A hyperlink can be identified by the fact that the mouse pointer changes to look like a palm having four folded fingers with the index finger not folded but pointing outwards.

 

The Internet is a big forest of web pages and websites. Searching for particular materials or resources can be a nightmare because of the massive volumes of available documents and resources. To make the work a bit easy, special websites that maintain lists of hyperlinks are available. These websites are called search engines. They have special programs called robots or spiders that traverse the web from one hyperlink to the next and when they find new material, they add them to their indexes or databases. Figure 5.4 below shows one of the most common search engines called Google found at www.google.com

The user searches for a word by typing a few key words in the search field of the engine then clicking the search button. The engine searches its database for links to the information requested and displays a list of links from which the user can now access information by clicking them to open web pages.

 

Example of search engines include: www.google.com, www.hotmail.com and www.yahoo.com.

 

Downloading/saving/printing web content

After searching and finding information on the Internet, you may want to save the information locally on your computer for future reference. The process of transferring information from a remote computer to a local storage is called downloading. To download a file, the following procedure is followed:

  1. Right click the hyperlink to the file.
  2. On the shortcut menu, click the Save target as command.
  3. After some searching the browser displays the save as dialog box. Specify the folder or drive where the file is to be saved then type a unique name for the file in the name box.
  4. Click the Save button and the download progress dialog appears on the screen. Unless otherwise selected, the download dialog will notify the user at the end of the download process.

Pen the file in its application to view it.

 

NB: If you download a file whose application is not currently installed on the computer, then you may not be able to view its contents. For example, if you download a file that was created in Microsoft Word then you can only open it in the same application.

 

To print a file, open it in the application in which it was created then send it to the printer for printing. You can also print a web page directly from the browser window by clicking File then Print.

 

Electronic mail (e-mail)

Electronic mail refers to the sending and receiving of electronic letters and documents on the Internet. This feature serves to popularize the Internet even among non-technical people. For many, gone are the days when paper mail (of late called snail mail) would be sent and the recipient had to wait for long before receiving it. E-mail is fast because it takes

Only a few seconds to reach the recipient regardless of where they are in the world.

 

E-mail software

E-mail software falls under a special group of application packages called communication SoftArt. It is specially designed and developed to help a person to read and send individual text documents on the Internet as long as both the sender and receiver have an e-mail address.

 

Like the normal postal address, an e-mail address directs the computers on the Internet on where to deliver the e-mail message. A typical e-mail address would look like this: chemwex@yahoo.com

  1. chemwex is the user name and is usually coined by the user during

E-mail account registration.

  1. @ is the symbol for Hat” which actually separates the user name from the rest of the address.
  2. Yahoo. Com is the name of the host computer in the network i.e. the computer on which the e-mail account is hosted.
  3. The period H. ” is read as dot and is used to separate different parts of the e-mail address.
  4. Com identifies the type of institution offering a particular service(s) and is called the domain, meaning it is a commercial institution. Other common domains include:

 

Domain                                                                        Type

 

.edu                                                                   Educational institution

.gov                                                                   Government institution

.org                                                                   Non-profit making organization

.mil                                                                   Military organization

.co                                                                               Commercial institution

 

Sometimes another two letter extension is added after the domain name to show the country where the site is located e.g. injsmith@yahoo.co.uk, .uk stands for United Kingdom. Other countries domain name includes .ke (Kenya) .ug (Uganda, :tz (Tanzania), .jp (Japan), .au (Australia) etc.

 

E-mail facilities

Basically all e-mail software packages provide the user with ability to receive messages, display them, reply to the messages, compose new ones and store received messages.      ‘

 

Mails

  1. Checking mail In order to check mail the user has to open the e­mail account by providing the correct user name and password. While

In the e-mail account, click the Inbox command to view a link list of all the mails that you have received. To view a message, simply click its link and it opens on the screen for reading.

  1. To compose a message, click the Col11posebutton. The e-mail software opens a blank screen on which you can type the new message. Figure.5.5 shows a typical e-mail screen for composing a message.

 

  1. To send mail, type the correct e-mail address of the recipient in the to: text box. Type a subject in the subject box e.g. if it is a letter to a friend, type “Hi”. Finally click the Send, or send / receive button, and your message will be sent.
  2. Forwarded messages can be read and sent on to other people. Most of such messages are fun pages, poems, e-cards etc. After reading,

Simply click the Forward button and then provide the addresses of the recipients. Click the Send button to send.

  1. An e-mail message can be saved using the normal procedure for saving e.g. Click File, Save as then provide the name of the file and click save button.
  2. To print e-mail, select the text to be printed then click the File – Print command. In the print dialog box select the options for the page size, orientation etc. then click the Print button.

 

File attachment:

E-mail software also enables a person to attach other files like pictures, music and movie clips to an e-mail for sharing with friends before sending. The recipient can then download the attached files or simply view them on the screen. A good example where people use attachments is on-line job applications where a person attaches curriculum vitae to an e-mail message. To attach a file:

  1. Start the e-mail software i.e. Microsoft outlook express.
  2. Click File then New or open a composed e-mail.
  3. Specify the recipients address and the subject.
  4. Click the Insert menu then File attachment. A dialog box appears where you chose the file you want to attach.
  5. Select the file then click the Attach button.
  6. An attachment bar is inserted in the e-mail window with a name of the file you chose.
  7. Click Send to send the e-mail.

 

NB: You can also attach a file by simply clicking the attach button.

 

On-line meetings

It is possible to hold on-line meetings with people by sending mail to them. For example, on-line interviews may involve a person sending electronic mail composed of interview questions to a recipient who can read and answer back immediately. This method may not be as effective as a face to face interview or discussion but it is very useful in situations where traveling may be impossible or too expensive.

 

Telephone messages

Because of integration between mobile telephony and the Internet technology, it is possible to send e-mail to a mobile handset and a mobile message to e-mail account. This mobile computing is made possible by a special Internet access protocol called wireless access protocol (WAP) and wireless markup language (WML).

 

Contact management

Most mail programs allow the user to develop an address book which holds ‘contact information like e-mail addresses of different people along with other necessary information. The e-mail software usually provides a simple way of accessing these contacts when required. To create a new contact:

 

  1. Start the e-mail software i.e. Microsoft express.
  2. From the tools menu, click Address book or simply click the address book button.
  3. From the address book window click File then: Contact.
  4. Click the Name tab and enter the contact details.
  5. Click the Add button and add the contact into the contact list.
  6. Close the contact window then the address book.

 

5.9

Accessing information on emerging issues

The Internet is a storehouse for all types of information, presented in the form of text documents, pictures, sound and even video. Many emerging

Issues in the world today may not be properly documented in terms of hardcopy textbooks and journals but the Internet has a wide range of information concerning the issues. Emerging issues in this context refer to HIV/AIDS, drug abuse, environmental issues and moral issues.

 

Therefore, it is already evident that before embarking on finding any information on the web, a person needs to carefully plan their search to

Avoid wasting a lot of time wading through “junk” or useless material.

I

 

Steps for searching

  1. Plan for your search. You must develop a search strategy. Consider the following questions before starting to search for information: (a) what would be the best place to find the information required? (b) What tool best suits the work at hand?

(c) What key words can best describe the search problem?

  1. There is always the best place to start the search. One of the best places is on websites of leading media houses like www.cnn.com and www.nationaudio.co.ke because you are likely to get links to the latest research discoveries in your area of interest.
  2. after checking out on the news houses, you can now open some search engines and type the key words in the search field. Use different search engines to look for information on all the emerging issues mentioned above because different search engines give different search results.

 

 

DATA SECURITY AND CONTROLS

 

Chapter outline

 

6.1 Introduction and definition.

6.2 Security threats and control measures. 6.3 Computer crimes.

6.4 Detection and protection

6.5 Laws governing protection of information.

 

6.1 Introduction and definition

Computer information systems are becoming more and more important in daily life. Governments, private enterprises and individuals have found the need to protect data and information that is in their custody against unauthorized access, disclosure or damage. This is because of the rise of the information age and society leading to the subsequent view of information as a scarce valuable resource. This has posed threats to data and information both from known and unknown sources.

 

Data and information security Data security involves:

  1. Protection of data and information against unauthorized access or

Modification.

  1. Denial of data and information to unauthorized users.
  2. Provision of data and information to authorized users.

 

Data security also includes all the measures that will be taken to detect, document and counter the threats to data and information.

 

Data and information privacy

Private data or information is that which belongs to an individual and must not be accessed by or disclosed to any other person unless with direct permission from the owner. On the other hand, the data or information held by a government or organization about people is confidential data. This data and information may be seen by many authorized persons without the knowledge of the owner. However, it should not be used for commercial gain or any other unofficial purpose without the owner being informed. This data must also be protected against unauthorized access or disclosure.

 

6.2 Security threats and control measures

 

Viruses

A computer virus is a destructive program that attaches itself to other files and installs itself without permission on the computer when the files are opened for use. The virus may cause havoc on the computer system, for example, it may delete data on storage devices or interfere with the proper functioning of the computer system.

 

Types of computer viruses include:

  1. Boot sector viruses – they destroy the booting information on storage devices.
  2. File viruses – attach themselves to files.
  3. Hoax viruses – Come as e-mail with an attractive subject and launches itself when e-mail is opened.
  4. Trojans – they appear to perform necessary functions but perform other undesirable activities in the background without user knowledge.
  5. Worms – viruses that stick in the computer memory.
  6. Backdoors – may be a Trojan or a worm that allows hidden access to a computer system.

Control measures against viruses

  1. Install the latest versions of anti-virus software on the computers.

Make sure that you continuously update the anti-virus software with new virus definitions to counter the new viruses that are being manufactured on a daily basis.

  1. Avoid foreign diskettes in the computer room. If they have to be used, they must first be scanned for viruses.
  2. Avoid opening mail attachments before scanning them for viruses.

 

Unauthorized access

Data and information is always under constant threat from people who may want to access it without permission. Such persons will usually have a bad intention either to commit fraud, steal the information and ­destroy or corrupt the data. Unauthorized access may take the following forms:

 

Eavesdropping

This is tapping into communication channels to get information. Hackers mainly use eavesdropping e.g. to obtain numbers of credit cards.

 

Surveillance (monitoring)

 

This is where a person may keep a profile of all computer activities done

By another person or people. The information gathered may be used for one reason or the other e.g. spreading propaganda or sabotage. Many websites keep track of your activities using special programs called cookies.

 

Industrial espionage

Spying on your competitor to get information that you can use to counter or finish the competitor. This is mostly done with an aim to get ideas on how to counter by developing similar approach or sabotage.

 

Also unauthorized access can be as follows:

  1. An employee who is not supposed to view or see sensitive data by

mistake or design gets it.

  1. Strangers who may stray into the computer room when nobody is using the computers.
  2. Forced entry into the computer room through weak access points.
  3. Network access in case the computers are networked and connected to the external world.

 

Control measures against unauthorized access

  1. Enforce data and information access control policies on all employees.
  2. Encrypt the data and information during transmission (data encryption is discussed in details later in the chapter).
  3. Keep the computer room closed when nobody is using it.
  4. Reinforce the weak access points like doors and windows with metallic grills and burglar alarms.
  5. Enforce network security measures.
  6. Use files passwords to deter any persons who may get to the electronic files.

Computer errors and accidental access

Sometimes, threats to data and information come from people making mistakes like printing sensitive reports and unsuspectingly giving them to unauthorized person(s). Also, if end users have too much privilege that allows them to change or access sensitive files on the computer then accidental access mistakes may occur.

 

Errors and accidental access to data and information may be as a result of people experimenting with features they are not familiar with. For example, a person may innocently download a file without knowing that it is self-installing and it is dangerous to the system.

 

Control measures against computer errors and accidents

  1. Give various file access privileges and roles to the end users and technical staff in the organization i.e. denies access permissions to certain groups of users for certain files and computers.
  2. Set up a comprehensive error recovery strategy in the organization.

 

Theft

The threat of theft to data and information is a real one. Some information is so valuable that business competitors or some governments can pay a fortune to somebody who can steal the information for them to use. Therefore the following control measures should be taken to prevent theft of hardware, software and information.

 

Control against theft

  1. Employ guards to keep watch over data and information centers and

Backups.

  1. Burglar proofs the computer room.
  2. Reinforce weak access points like the windows, door and roofing

With metallic grills and strong padlocks.

  1. Create backups in locations away from the main computing centre.

 

Computer crimes

6.3 Trespass

The term trespass here refers to two things. One is the illegal physical entry to restricted places where computer hardware, software and backed up data is kept. The other form would be accessing information illegally

 

B­on a local or remote computer over a network. Trespass is not allowed at all and should be discouraged.

 

Hacking

A hacker is a person who intentionally breaks codes and passwords to gain unauthorized entry to computer system data and information files. The hacker therefore violates the security measures put in place such as breaking through passwords or finding weak access points in software.

 

There are various motivations for hacking. One is that some people like the challenge and they feel great after successful hacking, while some do it for computer and software producer companies that want to secure their systems by reducing weaknesses discovered after professional hacking. The most vulnerable computers to this crime are the networked computers faced with hackers working remotely.

 

Tapping

In this case, a person sends an intelligent program on a host computer that sends him information from the computer. Another way is to “spy” on a networked computer using special programs that are able to intercept messages being sent and received by the unsuspecting computer.

 

Cracking

Cracking usually refers to the use of guesswork over and over again by a person until he/she finally discovers a weakness in the security policies or codes of software. Cracking is usually done by people who have some idea of passwords or user names of authorized staff.

 

Another form of cracking is trying to look for weak access points in software. For example, Microsoft announced a big weakness in some versions of Windows software that could only be sealed using a special corrective program prepared by them. Such corrective programs are called patches. It is advisable therefore to install the latest patches in software.

 

Piracy

Piracy means making illegal copies of copyrighted software, information or data. Software, information and data are protected by the copyright law. There are several ways of reducing piracy:

 

  1. Enact laws that protect the owners of data and information against. Piracy.
  2. Make software cheap enough to increase affordability.
  3. Use licenses and certificates to identify originals.
  4. Set installation passwords that deter illegal installation of software.

 

Fraud

Computer fraud is the use of computers to conceal information or cheat other people with the intention of gaining money or information. Fraudsters can be either employees in the company or outsiders who are smart enough to defraud unsuspecting people. Some fraud may involve production and use of fake documents.

 

An example of fraud is where one person created an intelligent program in the tax department that could credit his account with cents from all the tax payers. He ended up becoming very rich before he was discovered.

 

Sabotage

This is the illegal destruction of data and information with the aim of crippling service delivery or causing great loss to an organization. Sabotage is usually carried out by disgruntled employees or those sent by competitors to cause harm to the organization.

 

Alteration

This is the illegal changing of data and information without permission with the aim of gaining or misinforming the authorized users. Alteration is usually done by those people who wish to hide the truth. To avoid this, do not give data editing capabilities to just anybody without vetting. Secondly, the person altering data may be forced to sign in order for the system to accept altering the information.

 

Alteration of data compromises the qualities of good data like reliability, relevance and integrity.

 

6.4

 

Detector and protection against computer crimes

After seeing the dangers that information systems are faced with due to threats to data and information and perpetration of computer crimes, it is important to look at some measures that can be taken to detect, prevent computer crimes and seal security loopholes.

 

Audit trial

This is a careful study of an information system by experts in order to establish or find out all the weaknesses in the system that could lead to security threats and weak access points for crimesters. An audit of the information system may seek to answer the following questions:

  1. Is. the information system meeting all its originally intended design objectives?
  2. Have all the security measures been put in place to reduce the risk of computer crimes?
  3. Are the computers secured in physically restricted areas?
  4. Is there backup for data and information of the system that can ensure continuity of services even when something serious happens to the current system?
  5. What real risks face the system at present or in future?

 

Data encryption

Data on transit over a network faces many dangers of being tapped, listened to or copied to unauthorized destinations. Such data can be protected by mixing it up into a form that only the sender and receiver can be able to understand by reconstructing the original message from the mix. This is called data encryption. The message to be encrypted is called the plain text document. After encryption using a particular order called algorithm or key, it is sent as cyphertext on the network. The recipient receives it and decrypts it using a reverse algorithm to the one used during encryption called a decryption key to get the original plain text document. Hence without the decryption key nobody can be able to reconstruct the initial message. Figure 6.1 is a flow diagram showing how a message can be encrypted and decrypted to enhance message security.

 

6.5 Log files

This is special system files that keep a record (1og) of events on the use of the computers and resources of the information system. This is because each user is assigned a user name and password or account. The information system administrator can therefore easily track who accessed the system, ‘when and what they did on the system. This unto second information can help monitor and track people who are likely to violate system security policies.

 

The most dangerous aspect in this case is when genuine users lose or give their passwords to unauthorized users.

 

Firewalls

A firewall is a device or software system t at filters the data and information exchanged between different networks by enforcing t e host networks access control policy. The main aim of a firewall is to monitor and control access to or from protected networks. People who do not have permission (remote requests) cannot access the network and those within cannot access firewall restricted sites outside the network.

 

Laws governing protection of information

Although most countries do not have laws that govern data and information handling, the awakening has started and the laws are being developed. The “right to privacy” is expected by all people. For example, the data protection law may have the following provisions:

  1. Data is not transferred to other countries without the owner’s permission.
  2. Data and information should be kept secure against loss or exposure.
  3. Data and information should not be kept longer than necessary.
  4. Data and information should be accurate and up to date.
  5. Data and information be collected, used and kept for specified lawful purposes.

 

Therefore, countries are encouraged to develop a data and information handling legal framework that will protect people’s data and information.

COMPUTER STUDIES NOTES FREE PDF FORM 3

DATA REPRESENTATION IN A COMPUTER

Chapter outline

1.1 Introduction

1.2 Concepts of data representation in digital computers

1.3 Bits, bytes, nibble and word

1.4 Types of data representation

1.5 Binary arithmetic operations

DOWNLOAD COMPUTER STUDIES NOTES IN PDF IN THE LINKS BELOW;

COMPUTER STUDIES NOTES FORM 1-4 PDF

Free Computer Studies notes, revision questions, KCSE past Papers, Exams, Marking Schemes, Topical revision materials, Syllabus and Many more

Form 3 notes for all subjects; free pdf & word downloads

Introduction

In Book 1 of this series, we learnt that computers are classified according to functionality, physical size and purpose. We saw that when classified according to functionality, computers can be analog, digital or hybrid. Digital computers process data that is in discrete form while analog computers process data that is continuous in nature. Hybrid computers, on the other hand can process both discrete and continuous data.

In digital computers, the user input is first converted and transmitted as electrical pulses that can be represented by two distinct digits’ l’ and ‘0’ before processing. These two digits are referred to as binary digits or in short bits.

Although two graphs can look different in their appearance, they may repeat themselves at equal time intervals. Electronic signals or waveforms of this nature are said to be periodic. Generally, a periodic wave representing a signal can be described using the following parameters.

  1. Amplitude (A)
  2. Frequency (f)
  3. Periodic time (T)

Amplitude (A): Amplitude is the maximum value a wave can attain. For example, the amplitude of waves in Figure 1.1 is 1.

Frequency (f): Frequency of a wave is the number of cycles made by the wave in one second. It is measured in units called hertz (Hz). 1Hz is equivalent to 1 cycle/second.

Periodic time (T): The time taken by a signal to complete one cycle is called periodic time. Periodic time, T, is given by the formula T = 1/f where f is the frequency of the wave.

When a digital signal is to be sent over analog telephone lines e.g. e-mail, it has to be converted to analog signal. This is done by connecting a device called a modem to the digital computer. This process of converting a digital signal to an analog signal is known as modulation. On the receiving end, the incoming analog signal is converted back to digital form in a process known as demodulation.

Concepts of data representation in digital computers

Since digital computers are the most widely used, this book seeks to explain in details how data is represented in digital form.

Data and instructions cannot be entered and processed directly into computers using human language. Any type of data be it numbers, letters, special symbols, sound or pictures must first be converted into machine readable form i.e. binary form. Due to this reason, it is important to understand how a computer together with its peripheral devices handle data in its electronic circuits, on magnetic media arid in optical devices.

Data representation in electronic circuits

Electronics components, such as the microprocessor, are made up of millions of electronic circuits. The availability of a high voltage (on) in these circuits is interpreted as ‘I’ while a low voltage (off) is interpreted as a ‘0’. This concept can be compared to switching on and off of an electric circuit. (Figure 1.3). When the switch is closed, (Figure 1.3 (a)), the high voltage in the circuit causes the bulb to light (‘ l’ state). On the other hand, when the switch is open (Figure 1.3 (b)), the bulb goes off (‘0’ state).

Data representation on magnetic media

The presence of a magnetic field in one direction on magnetic media is interpreted as ‘I’, while the field in the opposite direction is interpreted as ‘0’. Magnetic technology is mostly used on storage devices which are coated with special magnetic materials such as iron oxide. Data is written on the media by arranging the magnetic dipoles of some iron oxide particles to face in the same direction and some others in the opposite direction. Figure 1.4 shows how data is recorded on the surface of a magnetic disk. Note that the dipoles on the track are arranged in groups facing opposite directions.

Data representation on optical media

In optical devices, the presence of light is interpreted as ‘1’ while its absence is interpreted as ‘0’. Optical devices use this technology to read or store data. Take an example of a CD-ROM. If the shiny surface is placed under a powerful microscope, the surface can be observed to have very tiny holes called pits. The areas that do not have pits are called land (Figure 1.5).

In Figure 1.5 (a) the laser beam reflects from the land which is interpreted as ‘1’ while in Figure 1.5 (b) the laser beam enters a ‘pit’ and is not reflected. This is interpreted as ‘0’. The reflected pattern of light from the rotating disk falls on a receiving photoelectric detector that transforms the patterns into digital form.

 

Reason for use of binary system in computers

It has proved difficult to develop devices that can understand or process natural language directly due to the complexity of natural languages. It is, however, possible to develop devices that can understand binary language. Devices that read, process and output data in digital form are used in computers and other digital devices such as calculators. Binary logic has therefore simplified the technology needed to develop both hardware and software systems. Other reasons for the use of binary are that digital devices are more reliable, small in size and use less energy as compared to analog devices.

 

Bits, bytes, nibble and word

The terms bits, bytes, nibble and word are used widely in reference to computer memory and data size. Let us explain each term.

Bits: A bit can be defined as binary digits that can either be 0 or 1. It is the basic unit of data or information in digital computers.

 

Byte: A group of bits (often 8) used to represent a character is called a byte. A byte is considered as the basic unit of measuring memory size in computers.

A nibble: Half a byte, which is usually a grouping of 4 bits is called a nibble.

 

Word: Two or more bytes make a word. The term word length is used as a measure of the number of bits in each word. For example a word can have a length of 16 bits, 32 bits, 64 bits etc.

 

Types of data representation

Computers not only process numbers, letters and special symbols but also complex types of data such as sound and pictures. However these complex types of data take a lot of memory and processor time when coded in binary form. This limitation necessitates the need to develop better ways of handling long streams of binary digits. Higher number systems are used in computing to reduce these streams of binary into manageable form. This helps to improve the processing speed and optimise memory usage.

 

Number systems and their representation

As far as computers are concerned, number systems can be classified into four major categories:

  1. Decimal number system.

2, Binary number system

  1. Octal number system.
  2. Hexadecimal number systems.

 

Let us now consider each number system and its representation.

 

Decimal number system

The term decimal is derived from a Latin prefix deci which means ten. Decimal number system has ten digits ranging from 0-9. Because this system has ten digits, it is also called a base ten number system or denary number system,

 

A decimal number should always be written with a subscript 10 e.g. XIO

But since this is the most widely used number system in the world, the subscript is usually understood and ignored in written work. However, when many number systems are considered together, the subscript must always be put so as to differentiate the number systems.

 

The magnitude of a number can be considered using three parameters.

  1. Absolute value.
  2. Place value or positional value.
  3. Base value.

The absolute value is the magnitude of a digit in a number. For example, the digit 5 in 7458 has an absolute value of 5 according to its value in the number line as shown in the Figure 1.6.

 

The place value of a digit in an number refers to the position of the digit in that number i.e. whether “tens”, “hundreds”, “thousands” etc. as shown in Table 1.1.

 

Table 1.1

 

Thousands, 103 Hundreds, 102 Tens, 101 Ones, 10°
7 4 5 8

 

The total value of a number is the sum of the place value of each digit making the number. For example, the total value of the digits in Table 1.1 can be worked out by as shown below:

 

7 x 1000 = 7 000

4x 100     = 400                                                                                                                      400

5 x 10    =         50

8  x   l     =          8

Total =           7458

 

The base value of a number also known as the radix, depends on the type of number system that is being used. The value of any number depends on the radix. For example the number 10010 is not equivalent to 1002,

 

Binary number system

Binary number system uses two digits namely, 1 and 0 to represent numbers. Unlike in decimal numbers where the place values go up in factors of ten, in binary system, the place values increase by factors of two. Binary numbers are written as X2. Consider a binary number such as 10112. The right most digit has a place value of 1 x 2° while the left most has a place value of 1 x 23 as shown in Table 1.2.

 

Table 1.2

 

Place values (2n) Eights 23 =8 Fours 22 =4 Twos 21 = 2 Ones 2° = 1
Binary digit 1 0 1 1

The decimal equivalent of 10112 can be worked out as shown below.

1 x 8 = 8   Ox4 = 0   1 x 2 = 2   l  x  l =1      Total = 11

 

;Octal number system

The octal number system consists of eight digits running from 0 – 7. The place value of octal numbers go up in factors of eight from right to left as shown in Table 1.3. For example to represent an octal number such as 724\, we proceed as follows:

Table 1.3

 

Place values 83 =512 82 =64 81 = 8 8° = 1
Octal digit 7 2 4 5

The decimal equivalent can be worked out as follows:

7 x 512 = 3 584     2 x 64 = 128    4 x 8=32 5xl = 5    Total = 3749

 

Hexadecimal number system

This is a base sixteen number system that consist of sixteen digits ranging from 0 – 9 and letters A – F where A is equivalent to 10, B to 11 up to F which is equivalent to 15 in base ten system. The place value of hexadecimal numbers goes up in factors of sixteen as shown in Table 1.4. Table 1.5 gives digits for base 10 and base 16.

 

Table 1.4

 

Place value 162= 256 161 = 16 16° = 1
Hexadecimal digit 9 4 6

 

Table 1.5

 

Base 10 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Base 16 0 1 2 3 4 5 6 7 8 9 A B C D E F

 

A hexadecimal number is usually denoted using 16 as a subscript or capital letter H to the right of the number. For example, 94B can be written as 94BI6 or 94BH.

The decimal equivalent of94BI6 can be worked out as shown below.

 

9 x 256 =2304     4 x 16 = 64    11xl =11  total = 2379

 

Further conversion of numbers from one number system to another

So far, we have looked at the four types of number systems and introduced their basic concepts in a general and limited way. However, in this section, we shall have a detailed look at how to convert numbers from one system to another. The following conversions will be considered.

  1. Conversion between binary and decimal numbers.
  2. Converting octal numbers to decimal and binary form.
  3. Converting hexadecimal numbers to decimal and binary form.

 

Conversion between binary and decimal numbers

 

Converting binary numbers to decimal numbers

To convert a binary number to decimal number, we proceed as follows:

  1. First write the place values starting from the right hand side.
  2. Write each digit under its place value.
  3. Multiply each digit by its corresponding place value.
  4. Add up the products. The answer will be the decimal number in base 10.

Converting decimal numbers to binary                                                    

To convert a decimal number to binary, there are two possible methods, the long division method and the place value method.

In long division method, the decimal number is continuously divided by 2. However, at each level of the division, the remainder which is either a 1 or 0 is written to the right of the quotient. Starting from bottom upwards, read the series of the remainder digits. The series of 1 ‘s and O’s obtained represent the binary equivalent of the number.

To convert a decimal number to a binary number using place value method proceed as follows:

Write down the place values in factors of 2 up to the value immediately larger or equal to the number being considered. For example, to convert 24710 into binary, we write” down the place values up to 28 i.e.256. Similarly to convert 25810‘ write down the place values up to 29 i.e. 512. If the number being considered is itself a factor of 2 such as 64, 128, 256 etc., then place values should be written up to the number itself.

Let us now convert 24710 to binary. Starting from the left as shown in Table 1.6, subtract the place value from the number being converted. If the difference is a positive number or a 0, place a 1 in the binary digit row. If the difference is negative, place a Zero.

 

In Table 1.6, a 0 is placed in the binary digits row of the first column because 247 – 256 gives a negative value. The number 247 is then carried forward to the next lower place value i.e. 128.

 

Table 1.6

 

Place value 28 27 26 25 24 23 22 21
Difference 247 – 256 247 – 128              
Binary digit 0                

 

Since 247 – 128 gives a positive difference of 119, the digit 1 is placed in the second column of the binary digit row and the difference is carried forward to the next lower place value as shown in Table 1.7.

Table 1.7

 

256 128 64 32 16 8 4 2 1
247 – 256 247 – 128 119 – 64            
0 1              

 

Table 1.8 shows the completed operation.    Table 1.8

 

256 128 64 32
247 – 256 247 – 128 119 – 64 55 – 32
0 1 1 1

 

16 8 4 2 1
23 – 16 7-8 7-4 3-2 1 – 1=0
1 0 1 1 1

 

Converting a binary fraction to decimal number

A decimal number which has both an integral and fractional part is called a real number. The weight of the integral part of a real number increases from right to left in factors of I 0 while that of the fractional part decreases from left to right in factors of 10-x. Table 1.9 shows how a real number 87.537 can be represented using the place values.

Table 1.9

 

Place value 101 10° . 10-1 10-2 10-3
Decimal digit 8 7 . 5 3 7
Value 80 7 . 0.5 0.03 0.007

 

For a binary number, the same approach as in Table 1.9 can be used, only that the place values (weight) are based on factors of 2. For example, the binary number 11.110112 can be represented as shown in Table 1.10.

Table 1.10

 

Place value 21 . 2-1 2-2 2-3 2-4 2-5
Binary digit 1 1 . 1 1 0 1 1
Value in base ten 2 1 . 0.5 0.25 0 0.0625 0.03125

 

NB: When converting a real number from binary to decimal, work out the integral and fractional parts separately then combine them.

 

Converting a decimal fraction to binary

Remember that to convert a decimal integer to its binary equivalent we continuously divide the number by 2. In real decimal numbers, we do the same for the integral part. However to convert the fractional part to its binary equivalent, we proceed as follows:

  1. Multiply the fractional part by 2 and note down the product.
  2. Take the fractional part of the immediate product and multiply it by 2 again.
  3. Continue this process until the fractional part of the subsequent product is 0 or starts repeating the value of the original fractional part of the number being converted:
  4. The binary equivalent of the fractional part is extracted from the products by reading the respective integral digits from the top downwards as shown by the arrow in
  5. Combine the two parts together to get the binary equivalent.

 

Converting octal numbers to decimal and binary numbers

 

Converting octal numbers to decimal numbers

To convert a base 8 number to its decimal equivalent we use the same method as we did with binary numbers. However, it is important to note that the maximum absolute value of an octal digit is 7. For example 982 is not a valid octal number because digits 8 and 9 are not octal digits, but 7368 is valid because all the digits are in the range of 0 – 7. Example 1.13 and 1.14 show how to convert an octal number to a decimal number.

 

Converting octal numbers to binary numbers

To convert an octal number to binary, each digit is represented by 3 binary digits because the maximum octal digit i.e. 7 can be represented with a maximum of 3 digits. See Table 1.11.

 

Table 1.11

 

Octal digit Binary equivalents
0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111

 

Examples 1.15, 1.16 and 1.17 show how to convert octal numbers to binary numbers.

 

Converting hexadecimal numbers to decimal and binary numbers

 

Converting hexadecimal numbers to decimal number

To convert a hexadecimal number to its base ten equivalents, we proceed as follows:

  1. First write the place values starting from the right hand side.
  2. If a digit is a letter such as an ‘A’ write its decimal equivalent.
  3. Multiply each hexadecimal digit with its corresponding place value and then add the products.

The following examples illustrate how to convert a hexadecimal number to a decimal number.

Converting hexadecimal numbers into binary numbers

Since F is equivalent to a binary number 11112, the hexadecimal numbers are represented using 4 digits as shown in Table 1.12.

 

Table 1.12

 

Decimal. Hexadecimal Binary
equivalent digit equivalent
00 00 0000
01 01 0001
02 02 0010
03 03 0011
04 04 0100
05 05 0101
06 06 0110
07 07 0111
08 08 1000
09 09 1001
A 10 1010
B 11 1011
C 12 1100
D 13 1101
E 14 1110
F 15 1111

 

The simplest method of converting a hexadecimal number to binary is to express each hexadecimal digit as a four bit binary number and then arranging the groups according to their corresponding positions as shown in Example 1.21.

 

Symbolic representation using coding schemes

In computing, a single character such as a letter, a number or a symbol is represented by a group of bits, the number of bits per character depends on the coding scheme used.

The most common coding schemes are the Binary Coded Decimal (BCD), Extended Binary Coded Decimal Interchange Code (EBCDIC) and American Standard Code for Information Interchange (ASCII).

 

Binary Coded Decimal

Binary Coded Decimal is a 4-bit code used to represent numeric data only. For example, a number like 9 can be represented using Binary Coded Decimal as 10012, Binary Coded Decimal system is mostly used in simple electronic devices like calculators and microwaves. This is because it makes it easier to process and display individual numbers on their Liquid Crystal Display (LCD) screens.

 

A standard Binary Coded Decimal, an enhanced format of Binary Coded Decimal, is a 6-bit representation scheme which can represent non­numeric characters. This allows 64 characters to be represented. For example, letter A can be represented as 1100012 using the standard Binary Coded Decimal. A set of Binary Coded Decimal and standard Binary Coded Decimal code are provided in Appendix II.

 

Extended Binary Coded Decimal Interchange Code (EBCDIC)

Extended Binary Coded Decimal Interchange Code (EBCDIC) is an 8­bit character coding scheme used primarily on IBM computers. A total of256 (28) characters can be coded using this scheme. For example, the symbolic representation of letter A using Extended Binary Coded Decimal Interchange Code is 110000012, See Appendix II for a detailed scheme.

 

American Standard Code for Information Interchange (ASCII)

American Standard Code for Information Interchange (ASCII) is a 7-bit code, which means that only 128 characters i.e. 27 can be represented. However manufacturers have added an eighth bit to this coding scheme, which can now provide for 256 characters. This 8-bit coding scheme is referred to as an 8-bit American Standard Code for Information Interchange. The symbolic representation of letter A using this scheme is 10000012, See Appendix II for more details,

 

»Binary arithmetic operations

In mathematics, the four basic arithmetic operations applied on numbers are addition, subtraction, multiplication and division. In computers the same operations are performed inside the central processing unit by the arithmetic and logic unit (ALU). However the arithmetic and logic unit cannot perform binary subtraction directly. It performs binary subtraction using a process known as complementation. For multiplication and division, the arithmetic and logic unit uses a method called shifting before adding the bits; however, because the treatment of this method is beyond the scope of this book, we shall only explain how the computer performs binary addition and subtraction.

 

Representation of signed binary numbers

In computer technology there are three common ways of representing a signed binary number.

  1. Prefixing an extra sign bit to a binary number.
  2. Using ones complement.
  3. using twos complement.

 

Prefixing an extra sign bit to a binary number

In decimal numbers, a signed number has a prefix “+” for a positive number e.g. +2710 and “-” for a negative number e.g. -2710 However in binary, a negative number may be represented by prefixing a digit 1 to the number while a positive number may be represented by prefixing a digit O. For example, the 7-bit binary equivalent of 127 is 11111112, To indicate that it is positive, we add an extra bit (0) to the left of the number i.e. (0) 11111112, To indicate that it is a negative number we add an extra bit (1) i.e. (1) 11111112, The problem of using this method is that the zero can be represented in two ways i.e. (0)00000002 and (1 )00000002,

 

Ones complement

. The term complement refers to a part which together with another makes up a whole. For example in geometry two complementary angles add up to one right angle (90°). The idea of complement is used to address the problem of signed numbers i.e., positive and negative.

In decimal numbers (0 to 9), we talk of nine’s complement. For example the nines complement of 9 is 0 that of 5 is 4 while that of 3 is 6. However, in binary numbers, the ones complement is the bitwise NOT applied to the number. Bitwise NOT is a unary operator (operation on only one operand) that performs logical negation on each bit. For example the bitwise NOT of 11002 is 00112 i.e. Os are negated to Is while I’s are negated to O’s. Likewise the bitwise NOT of 00 1 0 11 0 1 is 110100102 which represents -4510‘ The bitwise NOT of 8-bit zero 000000002 is 111111112, Looking at the two numbers, the most significant digit shows that the number has a sign bit “0” for “+0″ and” 1″ for “-0”. Like in the method of using an extra sign bit, in ones complement, there are two ways of representing a zero.

 

Twos complement

Twos complement, equivalent to tens complement in decimal numbers, is the most popular way of representing negative numbers in computer systems. The advantages of using this method are:

  1. There are no two ways of representing a zero, as is the case with the other two methods.
  1. Effective addition and subtraction can be done even with numbers that are represented with a sign bit without a need for extra circuitries to examine the sign of an operand.

The twos complement of a number is obtained by getting the ones complement then adding a 1. For example, to get the twos complement of a decimal number 4510‘ first convert it to its binary equivalent then find its ones complement. Add a 1 to the ones complement i.e.

4510 = 001011012

Bitwise NOT (00101101) = 11010010

 

Two’s complement = 110100112

 

Binary addition

The five possible additions in binary are:

  1. 0+0=0
  2. 0 + 12= 12
  3. 12 + 0 = 12
  4. 12 + 12 =102 (read as 0, carry 1)
  5. 12 + 12 + 12 = 112 (read as 1, carry 1)

 

Binary subtraction

 

Direct subtraction

The four possible subtractions in binary are:

  1. 0-0=0
  2. 12-0= 1
  3. 12 – 12 = 0
  4. 102 – 12 = 12 (Borrow 1 from the next most significant digit to make 0 become 102, hence 102 – 12 = 12)

The following examples illustrate binary. Subtraction using the direct. method.

 

Subtraction using ones complements

The main purpose of using the ones complement in computers is to perform binary subtractions. For example to get the difference in 5 – 3, using the ones complement, we proceed as follows:

  1. Rewrite the problem as 5 + (-3) to show that the computer performs binary subtraction by adding the binary equivalent of 5 to the ones complement of 3.

2.Convert the absolute value of 3 into 8-bit equivalent i.e. 000000112,

3.Take the ones complement of 000000 112 i.e. 111111002 which is the binary representation of -310

  1. Add the binary equivalent of5 to the one’s complement of3 i.e.

000000101

+  111111000

(1)00000001

 

Looking at the difference of the two binary numbers, you will observe that:

  1. It has a ninth bit. The ninth bit is known as an overflow bit.
  2. The result show that the difference between the two numbers is 00000001. This is not true! We know that it should be 00000010.

To address this problem in a system that uses ones complement, the overflow digit is added back to the magnitude of the 8-bit difference. Therefore the difference becomes 00000001 + 1 = 00000010, which is the correct answer.

Subtraction using twos complements

Like in ones complement, the twos complement of a number is obtained by negating a positive number to its negative counterpart. For example to get the difference in 5 – 3, using the two’s complement, we proceed as follows:

  1. Rewrite the problem as 5 + (-3).
  2. Convert the absolute value of 3 into 8-bit binary equivalent i.e. 00000011.
  3. Take the ones complement of 000000 11 i.e. 11111100.
  4. Add a 1 to the ones complement i.e. 11111100 to get 11111101
  5. Add the binary equivalent of 5 to the twos complement of 3 i.e.

000000101

+ 111111001

(1 )000000 1 0

  1. Ignoring the overflow bit, the resulting number is 00000010 which is directly read as a binary equivalent of +2.

 

DATA PROCESSING

 

Chapter outline

 

2.1 Introduction

2.2 Data processing cycle

2.3 Description of errors in data processing

2.4 Data integrity

2.5 Data processing methods

2.6 Computer files

2.7 Types of computer processing files

2.8 File organisation methods

2.9 Electronic data processing modes

 

Introduction

Data refers to the raw facts that do not have much meaning to the user and may include numbers, letters, symbols, sound or images. Information, on the other hand, refers to the meaningful output obtained after processing the data.

 

Therefore the data processing refers to the process of transforming raw data into meaningful output i.e. information. Data processing can be done manually using pen and paper, mechanically using simple devices like typewriters or electronically using modem data processing tools such as computers. Electronic data processing has become so popular that manual and mechanical methods are being pushed to obsolescence.

 

Data processing cycle

Data processing cycle refers to input-process-output stages that data goes through to be transformed into information. It is often referred to as a cycle because the output obtained can be stored after processing and may be used in future as input. The four main stages of data processing cycle are:

  1. Data collection
  2. Data input
  3. Processing
  4. Output

 

 

Data collection

Data collection is also referred to as data gathering or fact-finding. It involves looking for crucial facts needed for processing.

 

Methods of data collection

Some methods of data collection include interviews, use of questionnaires, observation etc. In most cases, the data is collected after sampling. Sampling is the process of selecting representative elements (e.g. people, organisations) from an entire group (population) of interest. Some of the tools that help in the data collection include source documents such as forms, data capture devices such as a digital camera etc.

 

Stages of data collection

The process of data collection may involve a number of stages depending on the method used. These include:

Data creation: This is the process of putting together facts in an organised format. This may be in form of manually prepared document or captured from the source using a data capture device such as a bar code reader.

Data transmission: This will depend on whether data need to be transmitted via communication media to the central office.

 

Data preparation: This is transcription (conversion) of data from source document to machine-readable form. This may not be the case for all input devices. Data collected using devices that directly capture data in digital form do not require transcription.

 

. Media conversion: Data may need to be converted from one medium to another e.g. from a floppy disk to hard disk for faster input.

Input validation: Data entered into the computer is subjected to validity checks by a computer program before being processed to reduce errors at the input.

Sorting: In case the data needs to be arranged in a predefined order, it is first sorted before processing.

 

Data input

Data input refers to a process where the collected data is converted from human readable form to machine-readable form (binary form). The conversion takes place in the input device.

 

Processing

This is the transformation of input data by the central processing unit (CPU) to a more meaningful output (information). Some of the operations performed on data include calculations, comparing values and sorting.

 

Output

The final activity in data processing cycle is producing the desired output also referred to as information. The information can then be distributed to the target group or stored for future use. Distribution is making the information available to those who need it and is sometimes called information dissemination. This process of dissemination may involve electronic presentation over radio or television, distribution of hard copies, broadcasting messages over the Internet or mobile phones etc.

 

Description of errors in data processing

The accuracy of computer output is very critical. As the saying goes, garbage in, garbage out (GIGO), the accuracy of the data entered in the computer directly determines the accuracy of the information given out.

 

Some of the errors that influence the accuracy of data input and information output include transcription, computation and algorithm errors.

 

Transcription errors

Transcription errors occur during data entry. Such errors include misreading and transposition errors.

 

Misreading errors

Incorrect reading of the source document by the user and hence entering wrong values bring about misreading errors. For example, a user may misread a hand written figure such as 589 and type S86 instead i.e. confusing 5 for S.

 

Transposition errors

Transposition errors results from incorrect arrangement of characters i.e. putting characters in the wrong order. For example, the user may enter 396 instead of369.

 

Transcription errors can be avoided by using modem data capture devices such as bar code readers, optical character readers, and digital cameras etc., which enter data with minimum user intervention.

 

Computational errors

Computational errors occur when an arithmetic operation does not produce the expected results. The most common computation errors include overflow, truncation and rounding errors.

 

Overflow errors

An overflow occurs if the result from a calculation is too large to be stored in the allocated memory space. For example if a byte is represented using 8 bits, an overflow will occur if the result of a calculation gives a 9-bit number.

 

Truncation errors

Truncation errors result from having real numbers that have a long fractional part that cannot fit in the allocated memory space. The computer would truncate or cut off the extra characters from the fractional part. For example, a number like 0.784969 can be truncated to four digits to become 0.784. The resulting number is not rounded off.

 

Rounding errors

Rounding errors results from raising or lowering a digit in a real number to the required rounded number. For example, to round off 30 666 to one decimal place, we raise the first digit after the decimal point if its successor is more than 5. In this case, the successor is 6 therefore 30.666 rounded up to one decimal place is 30.7. If the successor is below 5, e.g. 30.635, we round down the number to 30.6.

 

Algorithm or logical errors

An algorithm is a set of procedural steps followed to solve a given problem. Algorithms are used as design tools when writing programs. Wrongly designed programs would result in a program that runs but gives erroneous output. Such errors that result from wrong algorithm design are referred to as algorithm or logical errors.

 

Data integrity

Data integrity refers to the accuracy and completeness of data entered in a computer or received from the information system. Integrity is measured in terms of accuracy, timeliness and relevance of data.

 

Accuracy

Accuracy refers to how close an approximation is to an actual value. As long as the correct instructions and data are entered, computers produce accurate results efficiently. In numbers, the accuracy of a real number depends on the number. For example 72.1264 is more accurate than 72.13.

 

Timeliness

Timeliness of data and information is important because data and information have a time value attached to them. If received late, information may have become meaningless to the user. For example, information on the newspaper that is meant to invite people for a meeting or occasion must be printed prior to the event and not later.

 

Relevance

Data entered into the computer must be relevant in order to get the expected output. In this case, relevance means that the data entered must be pertinent to the processing needs at hand and must meet the requirements of the processing cycle. The user also needs relevant information for daily operations or decision making.

 

Threat to data integrity

 

Threats to data integrity can be minimized through the following ways:

 

  1. Backup data preferably on external storage media.
  2. Control access to data by enforcing security measures.
  3. Design user interfaces that minimize chances of invalid data entry.
  4. Using error detection and correction software when transmitting data.
  5. Using devices that directly capture data from the source such as bar code readers, digital cameras, optical character readers etc.

 

Data processing methods.

As mentioned earlier, data can be processed manually, mechanically or electronically.

Manual data processing

In manual data processing, most tasks are done manually with a pen and a paper. For example in a busy office, incoming tasks (input) are stacked in the “in tray”. The processed tasks are then put in the “out tray” (output). The processing of each task involves a person using the brain in order to respond to queries. The processed information from the out tray is then distributed to the people who need it or stored in a file cabinet.

 

Mechanical data processing

Manual processing is cumbersome and boring especially when processing repetitive tasks. Mechanical devices were developed to help in automation of manual tasks. Examples of mechanical devices include the typewriter, printing press and weaving looms. Initially, these devices did not have any electronic intelligence.

 

Electronic data processing

For a long time, scientists have researched on how to develop machines or devices that would simulate some form of human intelligence during data and information processing. This was made possible to some extent with the development of electronic programmable devices such as computers.

The advent of microprocessor technology has greatly enhanced data processing efficiency and capability. Some of the microprocessor-controlled devices include computers, cellular (mobile) phones, calculators, fuel pumps, modem television sets, washing machines etc.

Computer files

A file can be defined as a collection of related records that give a complete set of information about a certain item or entity. A file can be stored manually in a file cabinet or electronically in computer storage devices. Computerized storage offers a much better way of holding information than the manual filing systems, which heavily rely on the concept of the file cabinet. Some of the advantages of computerized filing system include:

  1. Information takes up much less space than the manual filing.
  2. It is much easier to update or modify information.
  3. It offers faster access and retrieval of data.
  4. It enhances data integrity and reduces duplication.

 

Elements of a computer file

A computer file is made up of three elements namely: characters, fields and records.

 

Characters A character is the smallest element in a computer file and refers to a letter, number or symbol that can be entered, stored and output by a computer. A character is made up of a set of seven or eight bits depending on the character-coding scheme used.

 

Fields

A field is a single character or collection of characters that represents a single piece of data. For example, in a student’s record, the student’s admission number is an example of a field.

 

Records

A record is a collection of related fields that represent a single entity. For example, in a class score sheet, details of each student in a row such as admission number, name, total marks and position make up a record.

 

Logical and physical files

Computer files are classified as either logical or physical.

 

Logical files

A logical file is a type of file viewed in terms of what data items it contains and details of what processing operations may be performed on the data items. It does not have implementation specific information like field, data types, size and file type. Logical files are discussed in system design later in the book.

 

Physical files

As opposed to a logical file, a physical file is one that is viewed in terms of how data is stored on a storage media and how the processing operations are made possible. Physical files have implementation specific details such as characters per field and data type for each field. Physical files are discussed later in system implementation and operation in this book.

 

Types of computer processing files

There are numerous types of files used for storing data needed for processing, reference or backup. The main common types of processing files include master files, transaction, reference, backup, report and sort file.

 

Master file

A master file is the main file that contains relatively permanent records about particular items or entries. For example a customer file will contain details of a customer such as customer ID, name and contact address.

 

Transaction (movement) file

A transaction file is used to hold input data during transaction processing. The file is later used to update the master file and audit daily, weekly or monthly transactions. For example in a busy supermarket, daily sales are recorded on a transaction file and later used to update the stock file. The file is also used by the management to check on the daily or periodic transactions.

 

Reference file

A reference file is mainly used for reference or look-up purposes. Look­up information is that information which is stored in a separate file but is required during processing. For example, in a point of sale terminal, the item code entered either manually or using a bar code reader looks up the item description and price from a reference file stored on a storage device.

 

Backup file

A backup file is used to hold copies (backups) of data or information from the computers fixed storage (hard disk). Since a file held on the hard disk may be corrupted, lost or changed accidentally, it is necessary to keep copies of the recently updated files. In case of the hard disk failure, a backup file can be used to reconstruct the original file.

 

Report file

A report file is used to store relatively permanent records extracted from the master file or generated after processing. For example you may obtain a stock levels report generated from an inventory system while a copy of the report will be stored in the report file.

 

Sort file

A sort file is mainly used where data is to be processed sequentially. In sequential processing, data or records are first sorted and held on a magnetic tape before updating the maste file.

 

File organization methods

File organization refers to the way data is stored in a file. File organization is very important because it determines the method of access, efficiency, flexibility and storage devices to be used. There are four methods of organizing files on a storage media. This includes: sequential, random, serial and indexed-sequential

Sequential file organisation

In sequential file organisation, records are stored and accessed in a particular order sorted using a key field. Retrieval requires searching sequentially through the entire file record by record from the beginning to the end. Because the records in the file are sorted in a particular order, better file searching methods like the binary search technique can be used to reduce the time used for searching a file. Since the records are sorted, it is possible to know in which half of the file a particular record being searched is located. Hence this method repeatedly divides the set of records in the file into two halves and searches only the half in which the record is found. For example, if the file has records with key fields 20, 30, 40, 50, 60 and the computer is searching for a record with key field 50, it starts at 40 upwards in its search, ignoring the first half of the set.

 

Random or direct file organisation

In random or direct file organisation, records are stored randomly but accessed directly. To access a file stored randomly, a record key is used to determine where a record is stored on the storage media. Magnetic and optical disks allow data to be stored and accessed randomly.

 

Serial file organisation

With serial file organisation, records in a file are stored and accessed one after another. The records are not sorted in any way on the storage medium. This type of organisation is mostly used on magnetic tapes.

Indexed-sequential file organisation method

This method is almost similar to sequential method, only that an index is used to enable the computer to locate individual records on the storage media. For example, on an magnetic drum, records are stored sequentially on the tracks. However, each record is assigned an index that can be used to access it directly.

 

Electronic data processing modes

There are several ways in which a computer, under the influence of an operating system is designed to process data. Examples of processing modes are:

 

  1. Online processing
  2. Real-time processing
  3. Distributed processing
  4. Time-sharing.
  5. Batch processing
  6. Multiprocessing
  7. Multitasking
  8. Interactive processing

 

On-line processing

In online data processing data is processed immediately it is received the computer is connected directly to the data input unit via a communication link. The data input may be a network terminal or an online input device attached to the computer.

 

Real-time processing

In a real-time data processing, computer processes the incom111g data as soon as it occurs, up-dates the transaction file and gives an immediate response that would affect the events as they happen. This is different from online in that for the latter an immediate response may not be required. The main purpose of a real-time processing is to provide accurate, up-to-date information hence better services based on a true (real) situation. An example of real-time processing is making a reservation for airline seats. A customer may request for an airline booking information through a remote terminal and the requested information will be given out within no time by the reservation system. If a booking is made, the system immediately updates the reservations file to avoid double booking and sends the response back to the customer immediately.

 

Distributed data processing

Distributed data processing refers to dividing (distributing) processing tasks to two or more computers that are located on physically separate sites but connected by data transmission media. For example, a distributed database will have different tables of the same database residing on separate computers and processed there as need arises. The users of the distributed database will be completely unaware of the distribution and will interact with the database as if all of it was on their computer.. This distribution of processing power increases efficiency and speed of processing. An example is in the banking industry where customers’ accounts are operated on servers in the branches but all the branch accounts can be administered centrally from the main server as if they resided on it. In this case, we say that the distributed database is transparent to the user because the distribution is hidden from the user’s point of view.

 

Time-sharing

In a time-sharing processing, many terminals connected to a central computer are given access to the central processing unit apparently at the same time. However in actual sense, each user is allocated a time slice of the CPU in sequence. The amount of time allocated to each user is controlled by a multi-user operating system. If a user’s task is not completed during the allocated time slice, he/she is allocated another time slice later in a round robin manner.

 

Batch processing

In batch processing, data is accumulated as a group (batch) over a specified period of time e.g. daily, weekly or monthly. The batch is then processed at once. For example in a payroll processing system, employees’ details concerning number of hours worked, rate of pay, and other details are collected for a period of time, say one month. These details are then used to process the payment for the duration worked. Most printing systems use the batch processing to print documents.

 

Multiprocessing

Multiprocessing refers to the processing of more than one task at the same time on different processors of the same computer. This is possible in computers such as mainframes and network servers. In such systems, a computer may contain more than one independent central processing unit, which works together in a coordinated way. At a given time, the processors may execute instructions from two or more different programs or from different parts of one program simultaneously. This coordination is made possible by a multiprocessing operating system that enables different processors to operate together and share the same memory.

 

Multiprogramming

Multiprogramming, also referred to as multi-tasking refers to a type of processing where more than one programs are executed apparently at the same time by a single central processing unit. It is important to note that, as opposed to multiprocessing. In multiprogramming, a computer has only one central processing unit. The operating system allocates each program a time slice and decides what order they will be executed. This scheduling is done so quickly that the user gets the impression that all programs are being executed at the same time.

 

Interactive processing

In interactive data processing, there is continuous dialogue between the user and the computer. As the program executes, it keeps on prompting the user to provide input or respond to prompts displayed on the screen.

 

ELEMENTARY PROGRAMMING PRINCIPLES

 

Chapter  outline

 

3.1 Introduction

3.2 Computer programming

3.3 Description of terms used in programming

3.4 Levels of programming languages

3.5 Advantages and disadvantages of low level and high-level languages

3.6 Program development

3.7 Program documentation

3.8 Development of algorithms

3.9 Program control structures

3.10 Designing more complex algorithms

 

Introduction

Human beings have evolved from the Stone Age to a highly sophisticated and advanced society by inventing things like the wheel, fire, transistors and today’s ultra modem devices like computers. The idea of computers started way back in the nineteenth century.

The first generation computers called Electronic Numeric integrator and Calculator (ENIAC 1) were operated by plugging wires into a control panel that resembles the old telephone switchboards

Computer programming

A computer works by executing a set of instructions known as a program. The term programming refers to the process of developing computer instructions (programs) used to solve a particular task. It involves use of special characters, signs and symbols found in a particular programming language to create computer instructions. A programming language is a special set of symbols that can be translated into machine-readable form by the computer when arranged in a particular sequence or order. Each language has a special sequence or order of writing characters usually referred to as syntax.

It was John von Neumann of Princeton University (USA) who first came up with the proposition to store programs in the computer memory. Perhaps, this was one of the most dramatic developments in the computer history. Why? Because not only did the new stored-program way of computing increase-processing speed but also allowed easy and flexible methods of editing and updating the program.

 

Description of terms used in programming

Before we go further with programming, it is important to define some common terms used in computer programming.

 

Source program

The term source program refers to the program code that the programmer enters in the program editor window that is not yet translated into machine-readable form. The source program is usually created using a particular programming language as discussed later.

 

Object code

The term object code refers to the program code that is in machine-readable. A source code that is not in machine-readable form must be translated into object code.

 

Translators

The term translator is used to refer to language processors such as assemblers, interpreters and compilers that convert the source program into object code.

 

Assembler

An assembler translates assembly language into machine language that the computer can understand and execute.

 

Interpreter

An interpreter translates the source program line-by-line, allowing the CPU to execute one line before translating the next. The translated line is not stored in the computer memory. It means that every time the program is needed for execution, it has to be translated. This method of translating programs was very common in early computers that did not have enough memory to store the object code as a file that can be executed later

 

Compiler

A compiler translates the entire source program into object code: The object code file can be made into a fully executable program by carrying out another process known as linking which joins the object code to all the other files that are needed for the execution of the program. After the linking process, an executable file (application file) is generated. This file is stored on a storage media such as a disk with a name that has a unique extension (.EXE). Examples of executable files are WINWORD.EXE and PM70.EXE used to start Microsoft Word and Adobe PageMaker 7.0 respectively.

 

The difference between the interpreters and compilers are summarised below:

 

Interpreters Compilers
1. Translates the source program

one statement at a time

1. Translates the entire source code

at once before execution

2. Translates the program each

Time it is run hence slower than

Compiling

2. Compiled program (object code) can be saved on a storage media and run as required, hence

Executes faster than interpreted

Programs.

3. Interpreted object code takes

Less memory compared to

Compiled program.

3. Compiled programs require

More memory as the object file

Are larger.

 

Levels of programming languages

Many programming languages have been developed over the years. These languages are classified into two major levels namely:

  1. Low-level languages
  2. High-level languages

 

These levels are further subdivided into five generations. The first and second generations consist of low-level languages while the third to the fifth generation consist of high-level languages.

 

Low-Level languages

Low-level languages are classified as low because the computer can easily understand them directly or they require little effort to translate into computer understandable form. These languages are hardware oriented and therefore they are not portable i.e. a program written for one computer cannot be installed and used on another. Two types of low level languages are the machine languages and assembly languages.

 

Machine languages (First generation languages)

In machine languages, instructions are written using binary logic. Given that data and instructions are in binary form, many lines of code are needed to accomplish even a simple task like adding two numbers. A program written in machine language might look like this:

It is evident from the above code that it is hard for a person to guess what the program is all about unless they have special knowledge in machine level programming. Furthermore, different CPU’s have different machine codes e.g. those for the Intel Pentium processors may differ from Motorola or Cyrix processors. Therefore before decoding the meaning, a programmer has to know for which CPU the program was written. Obviously, such programs are hard to understand from the programmer’s point of view, but very easy to execute from the computer’s perspective.

 

Assembly languages (Second generation languages)

Assembly languages were developed in order to overcome the difficulties of understanding and using machine languages. These languages represented the first successful attempt to make computer languages readable. The languages allowed programmers to write programs as a set of symbolic operation codes called mnemonics. Mnemonics are basically shortened two or three letter words.  Programs written in assembly language require an assembler in order to convert them into machine language that the computer can understand. Just like the machine languages, assembly languages are also machine dependent and therefore a program written for one computer cannot be used on another.

 

High-level languages

High-level languages are very close to the human language (English like) and they can be read and understood even by people who are not experts in programming. There are many types of high-level languages and each of them was developed to address a particular problem-solving domain while others came about due to advancement in technology. These languages are machine independent. This means that a programmer concentrates on problem solving during a programming session rather than how a machine operates.

High-level languages can be classified into five groups:

  1. Third generation languages. (3 GLs)
  2. Fourth generation languages. (4 GLs)
  3. Fifth generation languages. (5 GLs)
  4. Object oriented languages. (OOPs)
  5. Web scripting languages.

 

Third generation languages (3 GLs)

Third generation languages (3 GLs) are also called structured or procedural languages. A procedural language makes it possible to break a program into components called modules each performing a particular task. This is referred to as structured programming. The structured programming approach emphasizes the following:

  1. Large programs can be broken down into smaller sub programs each performing a single task.
  2. Use of a few simple control structures in problem solving. These control structures include sequence, selection and iteration as covered later in this book.

Structured programming offers many benefits because it is flexible, easier to read and modify. Examples of third generation programming languages include:

Pascal: Pascal was initially developed as an academic language, to help in the teaching and learning of structured programming.

FORTRAN: (FORmula TRANslator): This language was developed for mathematicians, scientists and engineers. It enables writing of programs with mathematical expressions.

COBOL: (Common Business Oriented Language): This language is designed for developing programs that solve business problems e.g. developing data processing applications such as computer-based inventory control systems.

BASIC: (Beginners All-purpose Symbolic Instructional Code): This language was mainly developed to enable students to easily learn programming. Basic is a simple general-purpose language used for developing business and educational applications. Because of its simplicity, it is a powerful tool for students who wish to learn programming. It was the first high-level language that was available for microcomputer users.­

C: This is a programming language mainly used for developing system software such as the operating system. It is one of the most popular and powerful high-level languages in the business world because of its ability to provide the programmer with powerful features of low-level languages and at the same time easily understandable as a high level language.

Ada: This language was named after the first lady programmer, Ada Lovelace. Ada is suitable for developing military, industrial and real­ time systems. .

A sample program written in Pascal language

Imagine the task of developing a program that would solve the equation of a straight line given by the algebraic expression:

Y = MX + C.

To enter the program code below in Pascal, proceed as follows:

  1. From Windows explorer, locate a folder called TP and open it.
  2. From the TP folder select BIN
  3. From BIN window, double click a file named turbo.EXE. Pascal program window is displayed on the screen.
  4. Enter the program code exactly as it is but ignore the numbering.
  5. Program Straight Line (Input, Output);
  6. Var
  7. y, m, x, c: Integer;
  8. Begin
  9. Writeln (‘Input the value of m‘);
  10. Readln (m);
  11. Writeln (‘Input the value of x’);
  12. readln (x);
  13. Writeln (‘Input the value of c ‘);
  14. Readln (c);
  15. Y: = m * x + c;
  16. Writeln (The value of y is:’, y);
  17. End.

Explanation

Line 1: This is the program header. The word “Program” indicate the beginning of the program whose name is Straight-Line. The (input, output) statements shows that the program will expect some input from the keyboard and display the output on the screen.

Line 2: Var is short form for variable. A variable is a location for data in the computer memory. This statement tells the computer that variables are about to be declared. When a variable is declared, the computer sets aside some memory space to store a value in the variable.

Line 3: F our variables have been declared of type integer. This means that the memory spaces that will be set aside can only hold values that are whole numbers.

Line 4: The Begin statement shows that this is the start of the program body. The computer executes statements in this section. For example, the execution starts by asking the user to input the value of m.

Line 5: The writeln statement displays whatever is in the brackets on the screen. Notice that the statements in brackets are written between inverted commas. The string will be sent to the screen exactly the way it appears in the brackets. If you wish to display the value held in a variable on the screen, then you have to remove the inverted comma’s and write the name of the variable in the brackets e.g. writeln (y) will display the value held in the variable y.

Line 6:The read or readln statement reads a value and stores it in a variable. When the program is running, a read/readln statement in the code will display a blinking cursor that indicates to the user where to type the input.

Line 11: Calculates the value of y. Notice the symbol’: =’. In Pascal! This is called the assignment statement. The values on the righ1 are calculated then stored in the variable y, which is on the left of the assignment symbol.

Line 12: The writeln displays the value stored in yon the screen. Notice that y is not within the inverted commas. If you gave the value of m as 10, x as 2 and c as 20 then the following should appeal on your screen: The value of y is: 40.

This is because the statements between the inverted comma’ are meant to make the output readable on the screen. Otherwise: only the value 40 would have been displayed.

Line 13: The ‘End.’ statement shows the end of a program.

 

Fourth generation languages (4 GLs)

Fourth generation languages make programming an even easier task that the third generation languages because they present the programmer with more programming tools. Examples of such tools include command buttons, forms etc. With the advent of these languages, gone are the days when a person had to write lines upon lines of code. Instead, the programmer selects graphical objects on the screen called controls then uses them to create designs on a base form. The programmer may also use an application generator that works behind the scenes to generate the necessary code; hence the programmer is freed from the tedious work of writing the code. Examples of fourth generation languages are: Visual Basic, Delphi Pascal and Visual COBOL.

 

A sample form designed using Visual basic programming language

The programmer in this case simply picks a tool from the toolbox and uses it to create objects such as command buttons, textboxes etc. on the form by dragging the mouse pointer on the form during design.

Fifth generation languages (5 GLs)

Fifth generation languages are designed around the concept of solving problems by enabling the computer to depict human like intelligence. These programs are designed to make the computer solve the problem for the programmer rather than the programmer spending a lot of time to come up with the solution. With such languages, the programmer only worries about what problem needs to be solved and what conditions need to be met without worrying about how to implement an algorithm to solve them. Examples of these languages are those used in artificial intelligence like PROLOG, Mercury, LISP and OCCAM.

 

Object-oriented programming languages (OOP)

The idea behind object-oriented programming (OOP) was developed in the 1960’s but its significance was not appreciated until lately. The concept behind object oriented programming languages is to look at a program as having various objects interacting to make up a whole. Each object has specific data values that are unique to it (called state) and a set of the things it can accomplish called (functions or behavior). This process of having data and functions that operate on the data within an object is called encapsulation. Several objects can then be linked together to form a complete program. Examples of object-oriented languages include Simula, which was developed in the 1960’s. However, C++, Java and SmallTalk are contemporary languages in this range. Although Java is sometimes associated with development of web sites it can be used to create whole application programs that do not need a web browser to run. OOP has contributed greatly to the development of graphical user interface operating systems and application programs.

I

Web Scripting languages!

Web scripting languages are used to develop or add functionalities on web pages. Web pages are hypertext documents created in a language called Hypertext Markup Language (HTML). The language simply consists of tags that are interpreted by the web browser software to display text when the HTML file is opened on the screen by a web browser software. A tag is a special word enclosed between the less than and greater than (<>) symbols and the browser can interpret it as a command. For example, to start a HTML page, one must use the <HTML> tag at the very top of the document. Other languages like Extended HTML (XML) have been derived directly from HTML with the only difference being that XML allows the user to define their own tags instead of using the standard HTML tags.

Unlike other programming languages, HTML does not have the declaration part and control structures (to be covered later in the book). Due of this reason, it is not considered as a true programming language.

Due to its simplicity, HTML has many limitations and cannot be used alone when it comes to developing functional websites. Some special blocks of code known as scripts may be inserted in HTML pages using scripting languages like JavaScript, VBScript and Hypertext Preprocessor (PHP) in order to add functionality to the HTML page. A script is a small program fragment, written in a different language other than HTML but inserted into the HTML program.

Most HTML tags have an opening tag and a closing tag. An opening tag is enclosed between < > while a closing one between </ >. Text that is to be displayed on the screen is enclosed between an opening and closing tag. For example, the statement <B> Hello </B> will display the word “Hello” in boldface on the screen. Table 3.1 shows examples of HTML tags and their meanings:

 

 

 

1

Table 3.1

Tag Meaning
1. <HTML></HTML> Marks the beginning and end of a HTML

document. All other tags and text fall

between these two tags.

2. <HEAD> </HEAD> Marks the header part of the document.
3. <TITLE> </TITLE> Gives title of the web page. Text between

this tags appears in the title bar when the

page is browsed.

4. <BODY></BODY> Marks the body part of the document.
5. <CENTER></CENTER> Centres text and objects on the web page.
6. <B></B> Bolds the text on the web page.
7. <1></1> Italicise the text.
8. <Hl></Hl> Sets size of text on the web page with H6

displaying the smallest and H1 the largest

Size.

Creating a script using Javascript

Javascript is a popular scripting language. Before writing your HTML program with a script inserted, make sure that you have the latest browser software installed on your computer. Older browsers may not have support for Javascript. If you are using Internet Explorer, it should be version 5.0 and above.

Open Notepad and key in the following program. Do not write the numbers to the left of each line of code.

  1. <HTML>
  2. <HEAD>
  3. < TITLE> Scripting Example </TITLE>
  4. </HEAD>
  5. <BODY>
  6. <HI> < CENTER. <B> We are the world </B> </CENTER> </HI>
  7. <SCRIPT LANGUAGE = ‘JavaScript’>
  8. Document. Write (‘My name is strongman’);
  9. alert (‘congratulations for succeeding to run this script’);
  10. </SCRIPT>
  11. </BODY></HTML>

After typing the entire program, save your file on the desktop as Example.html and then close the notepad. Notice that the icon to your file on the desktop look like that of the default web browser in your computer.

To view the web page, double click the icon of the file Example .htm1 on the desktop. Figure 3.3. shows an open webpage.

 

 

 

Fig. 3.3: A web page with a script.

Explanations

Line I: The tag <HTML> marks the beginning of the HTML document.

Line 2: The <TITLE> </TITLE> tags show the title of the web page. The text between this tags will appear in the title bar of the running HTML document as can be seen in Figure 3.2. Notice that the title is written in the header section i.e. between <HEAD> and </HEAD> tags.

 

Line 5: It marks the beginning of the body section. Anything between <BODY> and </BODY> will be executed and displayed when the webpage starts running.

Line 6: This line will display the text “We are the world” on the screen. The text will be large i.e. size HI and it will be centred on the screen. The text will also be bolded.

 

Line 7: It marks the start point of the script. Notice the line LANGUAGE = ‘JavaScript’ which tells the browser that the script will be written in JavaScript language.

Line 8: The statement Document. Write tells the browser using JavaScript to write whatever is in the brackets. Notice that in JavaScript, the end of a statement is marked by a semicolon (;).

Line 9: The word alert displays a message box on the screen with an OK button. Clicking the button makes the message box to disappear. The text in the brackets appears in the dialog box. Line 10: Closes the script.

Line 11: Marks the end of the body and the HTML code.

Practical activity 3.1

  1. Open a text editor program on your computer like NotePad or WordPad. I
  2. Type the following program exactly the way it is in the editor:

<HTML>

<HEAD><TITLE> This is my first webpage</TITLE></HEAD> <BODY bgcolor = “red” >

<H l><CENTER><B>Hello World</B></CENTER></HI>

</BODY> </HTML>

  1. Save your work as webpage.html on the desktop. Make sure that the Save As Type box reads “All Files” before clicking the save button in order to avoid saving a text file with two extensions i.e. webpage.html. txt
  2. Close your text editor. Notice that your file on the desktop has the icon of the default web browser installed on your computer. Double click it to view the web page! Figure 3.4 shows a sample of the display expected when the file is loaded to the browser. If you have a colour monitor, it should look as below only that it will have black bold text on a red background!
  3. Check your program and change your background to blue, save then click the refresh button. What happens?

 

 

Fig. 3.4: Sample web page

Advantages and disadvantages of low-level and high-level languages

Having looked at the various programming languages, it is important to identify the advantages and disadvantages associated with each level of programming languages.

Advantages and disadvantages of low level languages

Advantages

  1. The CPU understands machine language directly without translation.
  2. The processor executes them faster because complex instructions are already broken down into smaller simpler ones.
  3. Low level languages are stable and hardly crash or break down once written.

Disadvantages

  1. Low level languages are difficult and cumbersome to use and learn.
  2. They require highly trained experts both to develop and maintain programs.
  3. Removing errors (debugging) in low level language programs is difficult.
  4. Low level programs are machine dependent i.e. they are not transferable from one hardware or software platform to another.

Hence we say they are not portable.

Advantages and disadvantages of high level languages

Advantages

  1. High level languages are portable i.e. they are transferable from one computer to another.
  2. High level languages are user friendly and easy to use and learn.
  3. High level languages are more flexible; hence they enhance the creativity of the programmer and increase productivity in the workplace.
  4. High level languages are far much easier to correct errors (debug).

 

Disadvantages

  1. Their nature encourages use of many instructions in a word or statement hence the complexity of these instructions causes slower program processing.
  2. They have to be interpreted or compiled to machine readable form before the computer can execute them.

(Review questions 3.1)

  1. Define the term computer program.
  2. What is programming?
  3. State three advantages of high level languages over low level, languages.
  4. List four examples of high level languages and for each state its most appropriate application area.
  5. Why is an executable file unique as compared to any other file?
  6. Differentiate between a compiler and an interpreter. Why did early computers work well with interpreters?
  7. List the various examples of programming languages per generation.
  8. State one advantage of machine language over all the other languages.
  9. Write the following in full:

(a) HTML                        (b) OOP

  1. Distinguish between source program and object code in programming.
  2. Define the term encapsulation as used in object oriented programming.

Program development

The process of program development is not an easy task. Remember that in our definition of programming, we said that the program must solve a particular problem or accomplish a task. Hence, before developing a program, the requirements of the eventual users and its expected functions should be fully understood.

Program development can be broken into the following stages:

  1. Problem recognition.
  2. Problem definition.
  3. Program design.
  4. Program coding.
  5. Program testing and debugging.
  6. Implementation and maintenance.

The completion of one stage leads to the beginning of the next. At the same time, some stages have to be continuously reviewed in light of the step just before them to make sure that they meet the requirements. For example, after coding, the code has to be compared to the design to see whether it meets the design specification. Therefore, this method becomes very expensive if the correct requirements are not identified at each stage before the next is initiated.

It is important to note that although some people consider documentation as an independent stage, it is done at all stages of the program development lifecycle as shown in Figure 3.5. This is important so that the facts are recorded when they are still fresh and in the required detail by the programmer.

 

Problem recognition

Problem recognition refers to the understanding and interpretation of a particular problem. In order to understand a problem you need to look for the key words such as compute, evaluate, compare etc. You can then rewrite the problem in a more simplified way using the keywords.

A programmer identifies problems in the environment and seeks to solve them by writing a computer program that would provide the solution. Many of the privileges of automation that we enjoy today are as a result of people who wrote computer programs to do the tasks. For example, the intelligent control of traffic lights, the autopilot in aircraft and the use of robots in industry are good examples where problems were recognised and the computer was used as a tool to solve them. Think of the person who after seeing the tedious nature of typing using a manual typewriter decided to develop a word processor program!

In any given circumstance, the following three situations can cause the programmer to identify a problem that is worth solving:

  1. Problems or undesirable situations that prevent an individual or organisations from achieving their purpose.
  2. Opportunity to improve the current program. It can be argued that any unexploited opportunity is a problem.
  3. A new directive given by the management requiring a change in the status quo.

Sample problem

Consider a mathematical problem such as calculating the area of a circle. In this case, the problem is finding the area of a circle. As a programmer, it will be your interest to develop a program that can be used to calculate the area of any circle. The equation for calculating the area of a circle is given by A = лr2.

Problem definition

In problem definition, also referred to as problem analysis, the programmer tries to determine or define the likely input, processing activities and the expected output using the keywords outlined at the problem recognition stage.

At the end of this stage, the boundaries of the expected program will have been established i.e. a clear view of what the program needs to accomplish must be in place. In case, several methods are identified that can be used to solve the same problem, then the best alternative should be chosen.

In our problem of calculating the area of a circle, an investigation reveals that the parameters needed to determine the area of any circle are:

  1. Input: (a) Pie (л) which is a constant.

(b) The radius of the circle.

  1. Process: The formula of calculating area of a circle which is л x radius x radius.
  2. Output: The area of the circle (A).

The problem definition stage ends with the writing of a requirements report or document for the new program. It is this document that enables a programmer to come up with a program design that meets the needs at hand.

Program design

Program design is the actual development of the program’s processing or problem solving logic called the algorithm. An algorithm refers to a limited number of logical steps that a program follows in order to solve a problem. It is the programmer who will usually come up with the algorithm after carefully analysing the requirements specification. Many programs are not usually made up of one large block of code i.e. they are not monolithic. Instead, several units called modules work together to form the whole

In modular programming, each module performs a specific task. This approach makes a program flexible, easier to read and carry out error correction.

The design phase enables the programmer to come up with models of the expected program. The models show the flow of events and data throughout the entire program from the time data is input to the time the program gives out expected information. The development of algorithms is covered later in the chapter.

Program coding

Program coding is the actual process of converting a design model into its equivalent program. This is done by creating the program using a particular programming language. The end result of this stage is a source program that can be translated into machine readable form for the computer to execute and solve the target problem. Programs can be written in many different languages but the general trend in the world today is to use programs that are easy to learn and understand such as, Pascal, C++, Visual Basic and Java. Below is a comparison of the same program written in Pascal and C++ used to calculate the area of a circle.

Program in Pascal Program in c++
Program AreaCircle (input, output);

Const Pi = 3.142;

Var

Radius, Area: real;

Begin

Writeln (‘Enter the radius’);

Readln (radius);

Area: = Pi *Radius *Radius;

Writeln (‘The area is’, Area)

End.

#include<iostream.h>

main ( )

{

double radius, area;

const double pi = 3. 142;

cout«”Enter the radius”« “\n”;

cin»radius;

area = pi *radius * radius;

cout«”The area is”« area «”\n”;

return 0;

}

NB: Use lowercase when coding using C++.

Going through the two programs, you will realise that they are fairly similar, irregardless of the language that was used to code them. The table below explains the program codes.

Pascal code C++ code Explanation  
Program AreaCircle

(input, output);

#include<iostream.h» The header of the programs. The statements in ( ) and < > shows that the user inputs data via the keyboard and the program display information on the screen.  
Const Pi = 3.142; double pi = 3.142; A constant has been

declared with a name pi

and value 3.142.

Var

radius, area:real

double area, radius; Real variables with fractional

parts have been declared.

Begin { Marks the beginning of the

program body or c++

function

Writeln (‘Enter

the radius’);

cout< <“Enter radius”; Displays on the screen the

string between inverted

commas

Readln (Radius) cin> >radius; Displays a blinking cursor

that tells the user that an

input is needed before the

program can continue.

Area: = Pi*Radius

*Radius;

area = pi*radius

* radius;

Calculates the area. Notice

the assigment statement in

Pascal is : = while in C++ it

IS =

Writeln (‘The area

is’ Area)’

, ,

cout< <“The area

is” area « “\n”;

Display the value stored in

the variable Area.

End. return 0;

}

Marks the end of the

program

NB: “\n” is a C++ syntax of directing the character to a new line. It is equivalent to PASCAL’s “In” used in writeln and readln.

Program testing and debugging

After coding, the program has to be tested and the errors detected corrected (debugged).

There are two types of errors (bugs) that can be encountered when testing a program. These are:

1 Syntax errors: These errors emanate from improper use of language rules e.g. grammar mistakes, punctuation; improper naming of variables and misspelling of user defined and reserved words. Reserved words are those words that have a special meaning to the programming language and should not be used by the programmer for anything else. These errors are detectable by the translator and must be corrected before the program runs.

  1. Logical errors: They are not detectable by the translator. The program runs but gives wrong output or halts during execution. Such errors that occur during program execution are sometimes called runtime or execution errors.

Methods of error detection

There are several methods of testing the program for errors. These include:

  1. Desk checking (Dry-run)

It involves going through the program while still on paper before entering it in the program editor. This helps the programmer to detect the most obvious syntax and logical errors.

  1. Using debugging utilities

After entering the program in the program editor, you can run the debugging utilities during translation to detect syntax errors in order to correct them before execution.

  1. Using test data

The programmer carries out trial runs of the new program. At each run, the programmer enters various data variations and extremes including data with errors to test whether the system will grind to a halt. For example, if the input required is of numeric type, the programmer may enter alphabetic characters to see whether the program will grind to a halt unexpectedly. A good program should not crash due to incorrect data entry but should inform the user about the anomaly and request for the entry of the correct data.

Implementation and maintenance

Implementation

Implementation refers to the actual delivery and installation of the new program ready for use. New programs will obviously change the way things are done when implemented hence the need for review and maintenance.

Review and maintenance

Review and maintenance is important because of the errors that may be encountered after the program has been implemented or exposed to extensive use. A program may also fail not because of poor development but also due to poor use. Therefore proper training and post implementation support of users will always reduce the chances of having them entering invalid data that can crash the program.

 

Program documentation

Program documentation is the writing of support materials explaining how the program can be used by users, installed by operators or modified by other programmers. All stages of program development should be documented in order to help during future modification of the program.

Documentation can either be internal or external. Internal documentation, is the written non-excutable lines (comments) in the source program that help other programmers to understand the code statements. External documentation refers to reference materials such as user manuals printed as booklets. User manuals are common examples of external documentation There are three target groups for any type of documentation:

  1. User oriented documentation. These type enables the user to learn how to use the program as quickly as possible arid with little help from the program developer.
  2. Operator oriented documentation. It is meant for computer operators such as the technical staff. It helps them to install and maintain the program.
  3. Programmer oriented documentation. It is a detailed documentation written for skilled programmers. This documentation provides necessary technical information to help in future modification of the program. In this type of documentation, all stages of the program development should be documented because.

(a) There may come a need to revise or modify the program.

(b) Other programmers may think of ways of improving your program.

Development of algorithms

As defined earlier an algorithm can be defined as a limited number of logical steps that a program follows in order to solve a problem. In most cases, algorithms can be depicted using a number of tools such as decision tables, decision tree’s, flowcharts and pseudocodes. In this book, we shall mainly discuss program flowcharts and pseudocodes because they are the most widely used by programmers.

Pseudocode

As mentioned earlier, a pseudocode is a set of statements written in a readable language (usually English-like phrases) but expressing the processing logic of a program. Some of the words used in a pseudocode may be drawn directly from a programming language and then mixed with English to form structured statements that are easily understood by non-programmers and also make a lot of sense to programmers. However pseudocodes are not executable by a computer.

Guidelines for designing a good pseudocode

  1. The statements must be short, clear and readable
  2. The statements must not have more than one meaning i.e. should be unambiguous
  3. The pseudocode lines should be clearly outlined and indented clearly.
  4. A pseudocode should show clearly the start and stop of executable statements and the control structures (to be discussed later in the section).
  5. The input, output and processing statements should be clearly stated, using keywords such as PRINT, READ, INPUT etc. Below are some examples that demonstrate how to write a pseudocode.

Example 3.1

Write a pseudocode that can be used to prompt the user to enter two numbers, calculate the sum and average of the two numbers and then display the output on the screen.

 

Solution

START

PRINT “Enter two numbers”

INPUT X, Y

SUM = X + Y

AVERAGE = SUM/2

PRINT SUM

PRINT AVERAGE

STOP

Example 3.2

Write a structured algorithm that would prompt the user to enter the length and width of a rectangle, calculate the area and perimeter then display the result.

Solution

(i) First draw the rectangle of length (L) and width (W)

(ii) Write down the pseudocode

START

PRINT “Enter length and width”:

READ L, W

AREA = L * W

PERIMETER = 2(L + W)

PRINT AREA

PRINT PERIMETER

STOP

Example 3.3

Write a pseudocode for a program that can be used to classify people according to age. If a person is more than 20 years; output “Adult” else output “Young person”

Solution

START

PRINT “Enter the age” INPUT AGE

IF AGE> 20 THEN

PRINT “Adult”

ELSE

PRINT “Young person”

 

Program flowcharts

Unlike a pseudocode which expresses ideas in form of short statements, a flowchart does the same using both statements and special symbols that have specific meaning. Therefore, a flowchart is a diagrammatic representation of a program’s algorithm. The symbols are combined with short text clues which are a form of shorthand understood by programmers. The special symbols used to draw program flowcharts vary but the most common ones are as outlined below:

 

Ellipse: denotes the beginning and end of the program algorithm.

 

 

 

 

 

  1. Parallelogram: used to denote an input or output operation. For example, READ A, B, PRINT SUM.
Process

 

 

 

 

  1. Rectangle: Indicates that a processing or data transformation is taking place. For example SUM=A+B.

 

 

 

 

 

 

  1. Rhombus: Used to specify a condition. A condition must evaluate to a boolean value (True or false) for the program to execute the next instructions.

 

 

 

 

 

                                             

 

 

 

  1. Connector: Used as a connecting point or interface for arrows coming from different directions.

 

 

 

Arrow: Used to indicate the direction of flow of the program logic.

 

 

 

Guidelines for drawing a flowchart

  1. There should be only one entry/starting point and one exit point of the program algorithm.
  2. Use the correct symbol at each stage in the flowchart. For example, it is wrong to use a decision symbol where input is required.
  3. The logical flow should be clearly shown using arrows.

 

Comparison between a pseudocode and a flowchart

Taking our example of calculating the area of a circle mentioned in the earlier subtopic the algorithm by both methods are shown below.

 

 

 

Program control structures

Program control structures are blocks of statements that determine how statements are to be executed. In structured programming languages, there are three control structures namely; sequence, selection and iteration (looping).

Sequence

In sequence control structure, the computer reads instructions from a program file starting from the first top line and proceeding downwards one-by-one to the end. This is called sequential program execution.

Therefore, sequential program execution enables the computer to perform tasks that are arranged consecutively one after another in the code. However, most programs that solve real world problems need to enable the computer either to repeat tasks or to make decisions when certain conditions are true or false hence the need for selection and iteration.

Selection

In selection control, execution of statements depends on a condition that returns true or false. The condition must be a boolean expression. One example of a boolean expression is x > = 20. In such a case the condition is true if x is equal to or greater than 20. Any other value that is less than 20 is therefore false.

Generally, the four types of selection controls used in most high-level programming languages are:

  1. IF… THEN.
  2. IF … THEN … ELSE.
  3. Nested IF.

4 CASE selection.

In this book, we shall demonstrate how to implement these controls by using both pseudocodes and flowcharts.

IF … THEN

IF … THEN selection is used if only one option is available. In this case, all other options are ignored. For example, in a school environment, the administration may decide to reward only those students who attain a mean mark of 80% and above. Therefore, if a students attains 80% and above, he or she is rewarded while the rest are ignored. The following pseudocode and flowchart illustrate this condition:

 

IF … THEN… ELSE

IF … THEN… ELSE selection is suitable when there are two available options. For example, in a football match, if a player does a mistake which is considered serious by the rules of the game, he/she is given a red card. Otherwise, he/she is given a yellow card. The algorithms below illustrates this situation using the IF … THEN… ELSE selection.

 

Nested IF selection

Nested IF selection is used where two or more options have to be considered to make a selection. For example, in an Olympics track event, medals are awarded only to the first three athletes as follows:

(a) Position  1.Gold medal

(b) Position 2: Silver medal

(c) Position 3: Bronze medal

The pseudocode segment and flowchart extract below shows the structure of the Nested IF selection.

Pseudocode segment

IF position = 1 THEN

medal = “Gold”

ELSE

IF position = 2 THEN

medal = “silver”

ELSE

IF position = 3 THEN

medal = “bronze’

ELSE

medal = “nil”

END IF

ENDIF

ENDIF

Flowchart extract

 

 

 

The general format of the Nested IF is

IF < condition> THEN

statements

ELSE

     IF < condition> THEN

statements

ELSE

IF < condition> THEN

statements

ELSE

statements

              END IF

     END IF

ENDIF

CASE Selection

CASE selection is an alternative to the Nested IF especially where there are several options to choose from. This selection is preferred to the Nested IF in order to reduce the many lines of code. However, it is important to note that the boolean expression for the case selection can only be expressed using integers and alphabetic characters only. Generally the boolean expression should be CASE integer OF or CASE Char OF as illustrated in the example below. In this case, average must be an integer.

Pseudocode

CASE average OF

80..]00: Grade = ‘A’

70.. 79: Grade = ‘B’

60.. 69: Grade = ‘C’

50.. 59: Grade = ‘D’

40 .. 49: Grade = ‘E’

ELSE

        Grade = ‘F’

ENDCASE

Flowchart extract

General format of case

CASE x OF

Label: statement

Label 2: statement 2

Label 3: statement 3

                   Label n: statement n -1

ELSE

statementn

ENDCASE

Note that the flowchart is not different from that of the Nested IF construct-­

Iteration ( looping)

Iteration, also referred to a looping or repetition is designed to execute the same block of code again and again until a certain condition is fulfilled. Iteration is important in situations where the same operation has to be carried out on a set of data many times. For example, assume that you are writing a program that will use the same formula to calculate the average marks of three subjects for each student in a class and that the student records are stored in a computer file.

To calculate the average score for each student in a class, the program should repeatedly read record by record from the file, and then use the formula after each read operation to calculate the average.

Generally, the three main looping controls are:

( a) The WHILE loop

(b) The REPEAT. .. UNTIL loop

(c) The FOR loop

The WHILE loop

The ‘WHILE’ loop is used if a condition has to be met before the statements within the loop are executed. Therefore, this type of loop allows the statements to be executed zero or many times. For example in banking, to withdraw money using an automated teller machine (ATM) a customer must have a balance in his/her account.

This scenario can be represented as follows using an algorithm

Pseudocode segment

WHILE balance> 0 Do

Withdraw cash

Flowchart extract

Update account

END WHILE

Withdraw cash Update account

In our case above,

  1. The condition balance> 0 is first tested.
  2. If it is true, the account holder is allowed to withdraw cash.
  3. The program exits the loop once the balance falls to zero.

In general, the WHILE loop can be represented using a pseudocode and a flowchart extract as shown below.

Pseudocode segment

WHILE < condition> DO

statements

ENDWHILE

The REPEAT … UNTIL loop

Unlike the ‘WHILE’ loop, REPEAT… UNTIL allows the statements within it to be executed at least once since the condition is tested at the end of the loop. For example, consider the ATM cash withdrawal case discussed under the ‘WHILE’ loop. If the REPEAT … UNTIL is used, then the client will be able to withdraw the cash at least once since availability of balance is tested at the end of the loop as shown below.

Pseudocode

REPEAT

Withdraw cash

Update account

UNTIL balance > 0;

The general format of the REPEAT. .. UNTIL loop is;

Pseudocode

REPEAT

statements

UNTIL < condition>

The FOR loop

The FOR loop is used in circumstances where execution of the choosen statements has to be repeated a predetermined number of times. For I

example, consider a program that can be used to calculate the sum of ten numbers provided by the user. The ‘FOR’ loop can be used to prompt the user to enter the 10 numbers at most ten times. Once the numbers have been entered, the program calculates and displays the accumulated sum. The loop is predetermined because it has to be repeated 10 times as shown by the algorithms below.

Pseudocode

FOR count = 1 to 10 DO

PRINT “Enter a number (N)”

INPUT N

Sum=Sum+N

END FOR

Display SUM

Explanation

The FOR loop in the problem above functions as follows:

  1. The loop variable (count) is first initialised to the lower limit, in this case a value of 1.
  2. The lower limit is then tested against the upper limit whose value is set at 10.
  3. If the lower limit is less than or equal to 10, the program prompts the user to enter a number N, otherwise the computer exits the loop.
  4. After the last statement in the loop has been executed, the loop variable count is incremented by a 1 and stored in the lower limit i.e. lower limit = count + 1.
  5. The lower limit is then stored in count and step (2) is repeated

The FOR loop can also be used to count downwards from the upper limit to the lower limit. For example, in the above problem, the upper limit 10 can be tested against the lower limit 1 as follows.

FOR count = 10 DOWN TO 1 DO

Therefore the general format of the FOR loop can be represented using two sets of algorithms.

  1. Pseudocode for ‘FOR’ loop that counts from the lower limit

      FOR loop variable = lower limit To upper limit DO.

      statements

ENDFOR

  1. Pseudocode for a ‘FOR’ loop that counts from the upper limit down to the lower limit

FOR loop variable = Upper limit DOWN TO Lower limit DO

statements;

ENDFOR.

Designing more complex algorithms

The following examples demonstrates how to design more complex algorithms based on what has been covered previously. This is aimed at helping a beginner programmer understand how control structures are used to design logically correct algorithms.

Example 3.7

With aid of a pseudocode and a flowchart, design an algorithm that:

(a) Prompt the user to enter two numbers X and Y.

(b) Divide X by Y. However, if the value of Y is 0, the program should display an error message “Error: Division by zero”.

Solution

Using a pseudocode

START

PRINT “Enter 2 numbers X and Y”

INPUT X, Y

IF Y = 0 THEN

PRINT “Error: Division by zero”

ELSE

Quotient = X/Y

PRINT X, Y, Quotient

ENDIF

STOP

Example 3.8

Tusaidiane Savings Society (TSS) pays 5% interest on shares exceeding 100 000 shillings and 3% on shares that do not meet this target. However no interest is paid on deposits in the member’s TSS bank account. Design an algorithm for a program that would:

(a) Prompt the user for shares and deposit of a particular member.

(b) Calculate the interest and total savings.

(c) Display the interest and total savings on the screen for a particular member of the society.

Solution

Using a pseudocode

START

PRINT “Enter member name, share and deposit”

INPUT Name, Shares, Deposit

If shares> 100 000 THEN

Interest = 0.05 x shares

ELSE

Interest = 0.03 x shares

ENDIF

 

 

Total savings = Deposit + shares + Interest PRINT Name, Total Saving, Interest

STOP

Example 3.9

In an athletics competition, an athlete is rewarded as follows:

1 st position: Gold

2nd position: Silver

3rd position: Bronze

Draw a flowchart for a program that would be used to determine the type of medal to be rewarded to each athlete.

Example 3.10

The class teacher of Form 3W in a secondary school requested a programmer to design for her a simple program that would help her do the following:

(a) Enter the names of students and marks obtained in 8 subjects – Mathematics, English, Kiswahili, Biology, Chemistry, Business studies, Computer studies and History.

(b) After entering each subject mark, the program should calculate the total and average marks for each student.

(c) Depending on the average mark obtained, the program should assign grade as follows:

(i) Between 80 and 1 00 – A

(ii) Between 70 and 79 – B

(iii) Between 60 and 69 – C

(iv) Between 50 and 59 – D

(v) Below 50                  – E

 

(d) The program should then display each student’s name, total marks and the average grade. Using both a flowchart and a pseudocode, write an algorithm that shows the design of the program.

Solution

Using pseudocode

START

REPEAT

PRINT “Enter name and subject marks”

INPUT Name, Mathematics, English, Kiswahili, Biology, Chemistry, Business, Computer, History

SUM = Mathematics + English + Kiswahili + Biology + Chemistry +Business + Computer + History

AVG = SUM/8

IF (AVG <80) AND (AVG<100) THEN

Grade = ‘A’

ELSE

IF (AVG >70) AND (AVG > 79) THEN

Grade = ‘B’

ELSE

IF (AVG >60) AND (AVG >69) THEN

Grade = ‘c’

ELSE

IF (AVG >50) AND (AVG >59) THEN

Grade = ‘D’

ELSE

Grade = ‘E’

ENDIF

ENDIF

ENDIF

ENDIF

PRINT Name, Sum, AVG, Grade UNTIL Count = Number of students

STOP.­

 

 

Example 3.11

The gross salary of employees in KARU BOOKS ENTERPRISE is based on basic salary and additional benefits as follows:

(a) Employees who have worked for the company for more than 10 years receive an additional pay of 10% to their basic salary.

(b) Monthly salary bonus based on monthly sales of books as follows:

Monthly sales Bonus Rate (%)
Above 500 000 15
Between 250 000 and 500 000 10
Below 250 000 5

Draw a flowchart for a program that would be used to calculate the gross salary then output each employee’s basic salary, gross salary and all benefits.

 

 

 

SYSTEM DEVELOPMENT

Chapter outline

Introduction

Description of a system

Information system

Theories of system development

Stages of system development

System documentation

 

Introduction

The concept of a system emerged from early psychologists who believed that the mind was a whole unit, rather than a collection of psychological parts as the belief was by that time. However, it was Ludwig von Bertalanff, a German biologist, who gave the name “general systems theory” to the discipline that devoted itself to coming up with principles that apply to all systems.

A system is a set of organised components which interact in a given environment and within a specified boundary to achieve collective goals and objectives that are emergent. Emergent characteristics are those that result from interaction of various components and may not exist in the individual component. Therefore, once the components come together, they become interrelated and generate new goals and objectives. For example, a bicycle system has all the components working together to provide motion when ridden. The individual components cannot provide these services to a rider when on their own!

 

Description of a system

A system can be described as being either soft or hard.

Soft systems

Human activity systems are said to be soft systems. They are described as soft because of three main reasons:

  1. Their boundaries may be fluid or keep on changing.
  2. Their goals and objectives usually conflict and may not be captured clearly at anyone time because they are based on human factors like attitudes and preferences.
  3. It is difficult to precisely define exact measures of performance for them.

One example of a soft system is the political system. It is very difficult for instance to model a system that will predict the political mood in a country over a period of time. Another example is a sales tracking and prediction system in an organisation. Sales in an organisation depend on human factors like attitude in the market place.

Hard systems

Hard systems are systems whose goals and objectives are clearly defined and the outcomes from the systems processes are predictable and can be modeled accurately. Such systems are based on proven scientific laws like mathematical formulas or engineering solutions.

An example of a hard system would be a stock management system in a supermarket. It is possible to know exactly the stock levels, cost and sale price and to predict accurately the profit if all the stock is sold.

A good system incorporates both hard and soft aspects of a system. For example, a stock management system should be able to show when the demand for a certain item rises so that a decision can be made to stock more. New demand is driven by soft aspects in people’s lives like attitude and seasons!

 

Characteristics of systems

All systems have some common characteristics. Some of these characteristics are explained below.

Holistic thinking

In holistic thinking a system is considered as a whole. Aristotle, a Greek philosopher, once said that the whole is more than the sum of the parts. The various components that make up a system may be simple in nature and process but their combination creates a complex whole, whose overall goals are more sophisticated than those of the individual components. Hence, a system should be considered as a whole unit rather than considering its parts individually.

 

Subsystems

A system is made up of different components (subsystems). Therefore a system does not exist in solitude but it may be a component of larger a system. For example, the classroom system is part of a school system, which is part of the Ministry of Education. The Ministry of education is part of the Government which is part of the global system!

Boundary and environment

Each system has a space (boundary) within which the components operate. Any entity that falls outside the boundary but interacts with the system is part of the system environment. Such entities are called external entities. They provide the inputs and receive the outputs from the system. For example, the external entities to a school system may include the parents, various suppliers and the society at large.

Purpose

The purpose of each system is to perform a particular task or achieve a goal. The objectives that a system is supposed to achieve enable system developers to measure the performance of a system during its operation. One main objective for a school system for instance is to enable the students to excel in national examinations.

Process

A system usually will transform or process data from one state to another.

System entropy

The word entropy means decay. Systems “decay” naturally over time. This means that a system slowly becomes useless to the user either due to improvement in technology, new management policies or change in user requirements. Therefore a system must be reviewed in order to

improve it or to develop a new one.                                 .

Inputs and outputs

A system communicates with its environment by receiving inputs and giving outputs. For example, a manufacturing firm can be considered as a system that gets raw materials (inputs) from the environment and transforms them into finished products (outputs) released into the environment.

Open and closed systems

A system can be described as being open or closed. An open system receives input from and gives output to the environment while a closed system does not. Open systems normally adapt to changes in the environment.

Control

Control can be defined as the method by which a system adapts to changes in the environment in order to give the expected output or to perform to the expected level. Control is achieved through feedback which involves having outputs from the process of the system being fed back to the control mechanism. The control mechanism in turn adjusts control signals that are fed to the process which in turn makes sure that the output meets the set expectations. Fig. 4.1 depicts a typical system that has feedback to the control function. Imagine a motor vehicle manufacturing company that is producing several vehicles per day. Assuming that the demand rises, then feedback would show that the company is underperforming. Hence, control signals that would speed up movement of units on the assembly line can be issued to increase production.

 

Information system

An information system is an arrangement of people, data processes and information that work together to support and improve the day-to-day operations in a business and the decision making process. The main purposes of an information system in an organisation are:

  1. Supporting information processing by enhancing tasks such as data collection, processing and communication.
  2. Helping in decision making by collecting operational data, analyzing it and generating reports that can be used to support the decision making process. This process is referred to as on-line analytical processing.

 

  1. Enable sharing of information. Perhaps, this is one of the greatest powers of information systems. For example, any departments in a given organisation can now share the same electronic information stored in a central database at the click of a mouse button.

 

Why develop new information systems?

The need for developing information systems is brought about by three circumstances:

  1. New opportunities: A chance to improve quality of internal processes and service delivery in the organisation.
  2. Problems: These are undesirable circumstances that prevent the organisation from meeting its goals.
  3. Directives: These are new requirements imposed by the government, management or external influences.

Role of information system analyst

A system analyst is a person who is responsible for identifying an organisation’s needs and problems then designs and develops an information system to solve them. The system analyst does this by:

  1. Reviewing the existing system and making recommendations on how to improve or implement an alternative system.
  2. Working hand in hand with programmers to construct a computerized system.
  3. Coordinating training of the new system users and owners.

Project management

The system analyst is the overall project manager of the information system being implemented. His project management skills like assuring quality, keeping within schedule and budget determine whether the system will be successfully implemented or not. For example, a project that does not stick to its schedule will most likely overshoot its budgeted cost leading to unsuccessful completion.

 

Theories of system development

Several theories or methods are used in system development. The aim of all these theories and methods is to identify business requirements and to develop information systems that effectively meet them. This helps to support the day to day operations and decision making processes in an organisation.

Some of the most common system development theories include:

  1. Traditional approach.
  2. Rapid application development (RAD).
  3. The structured approach.

At this level, we will concern ourselves mostly with the structured approach. However, we shall briefly discuss the other two methods of system development.

Traditional approach

Traditional approach relies mostly on the skills and experience of individual staff members carrying out the project. This means that there is no formal documented methodology to be followed by all system developers in the organisation. This obviously presents a chaotic scene in system development especially where more than one persons are involved in the development effort. In most cases, success depends on the heroic efforts of an individual. This means that all other projects heavily rely on a particular person for their success.

In this approach, the manual system is replaced with a computerised one without change in overall structure of the former system. Hence the weaknesses of the former system are not addressed and are carried forward to the new system. For example, in a banking hall, a manual system is characterised by long queues and poor controls. If the traditional approach is followed, each cashier will simply be given a computer. The long queues might remain and lack of controls increase because no value was added to the former information system. This method is not recommended for today’s business environment.

Rapid application development (RAD)

Rapid application development (RAD) model evolved from the theory that businesses today heavily rely on information technology. Many information’ systems that were manual in nature are now fully computerised. Therefore, development and implementation of information systems needs to be quick enough for the organisation to maintain a competitive advantage in the market place.

Recent developments in programming software have seen the release of fourth generation languages (4GL’s) which are user-friendly because of their graphical interfaces. Rapid application development makes it possible for system developers to quickly capture user requirements by designing system interfaces in the presence of the user. This rapid application development technique is known as prototyping, and assumes that the user knows what they want when they see it. A prototype is a smaller working model of a real world system. Other approaches used in rapid application development include small team with advanced tools (SWAT) and joint application development (JAD).

The main disadvantage of rapid application development is that the working system may have oversights and weaknesses due to the quick Development. For example, a system may be working well but lack the necessary inbuilt security mechanisms. This would be undesirable in today’s insecure operating environment.

The structured approach

Structured approach to system development defines a set of stages that should be followed when developing a system. Each stage is well documented and specifies the activities to be carried out by the system analyst and his team while developing a system.

Stages of system development

The main stages in system 4evelopment as depicted by the structured approach include:

  1. Problem recognition and definition.
  2. Information gathering.
  3. Requirements specification.
  4. System design.
  5. System construction (coding).
  6. System implementation.
  7. System review and maintenance.

Figure 4.2 is a diagrammatic representation of the seven stages of the system development lifecycle (SDLC).

The stages of developing a system are also called the system development lifecycle. Each stage serves a role in the problem solving process. The lifecycle divides the life of an information system into two major parts namely:

  1. The development stage.
  2. The operation and support stage.

To demonstrate how to undertake each stage, we shall consider a case study.

Case study

Computer-based library management system

Mutito high school library has 3000 text books. Each book is identified by its author, ISBN number, book ID and title. The books are arranged on the shelves using their book ID. Card catalogues are maintained for all the books. There are two types of catalogues, one arranged according to the author’s names while the other is arranged according to the titles of the books. Each member is issued with three borrower cards that have a registration number and name of the member. To locate a book for borrowing, a member checks in the card catalogue for its classification then moves to the shelve to retrieve it. The member surrenders a borrower’s card .at the issue counter where the staff gives out the book and stamps the date of return. A member is not allowed to borrow more than three books at anyone time. Members are charged for overdue books at a fixed rate multiplied by the number of days delayed.

We now look at each of the stages of system development in more detail with this case study in mind.

Problem recognition and definition

Problem recognition is done during the preliminary investigation. During the recognition phase, the system analyst seeks to answer two questions. The first is whether the proposed project is worth looking at while the second is if the project is worth pursuing. After this, the system analyst has to define the scope of the project and establish the constraints, budget and schedule. The most common constraints are usually lack of finance, lack of enough expertise and/or lack of appropriate technology to develop the system.

Problem definition, also called problem analysis is the process of identifying the problem, understanding the problem and finding out any constraints that may limit the solution. This stage requires the analyst to find out as much as possible about the current system in order to draw up a good and relevant proposal for the new system. Remember that there is always an existing system whether manual or computerised. After this, several alternative solutions are modeled. The main question asked at this point is whether the proposed solution is the right one.

Looking at our case of the school library management system, the problem at hand is to replace the inefficient manual operations such as cataloguing with an efficient computerised system. The system analyst tries to answer the following questions.

  1. What are the shortcomings of the current systems?
  2. What types of records are used for books and students in the library?
  3. What procedure is followed to borrow/lend books?
  4. How are overdue books handled when returned?

In this first stage, a special study will be carried out to establish the costs and benefits of a new system. This study is called a feasibility study. A new system will only be developed if its benefits are more than its costs. The end of this stage is marked by presentation of a feasibility report to the management.

The feasibility of a system is assessed in four ways:

Operational feasibility: This establishes the extent to which the users are comfortable or happy with the proposed or new system.

Schedule feasibility: This establishes whether the development of the proposed system will be accomplished within the available time.

Technical feasibility: This establishes whether the technology available is sufficient or can be upgraded for the new system. It also seeks to find out whether the staff has relevant technical skills to develop and use the new system.

Economic feasibility: This establishes whether developing the new system is cost effective by analysing all the costs and benefits of the proposed system.

 

Information gathering

After the feasibility study report has been approved by the management, the system analyst can then proceed to the next stage referred to as information gathering or fact finding. Some of the methods used to collect or gather data include:

  1. Study of available documents.
  2. Interviews.
  3. Questionnaires.
  4. Observation.
  5. Automated methods.

 

Studying available documentation

The available documentation describes the current system and all its procedures. It forms a rich source of information for the analyst. Examples of such documents are card catalogues, receipts, reports, technical manuals, organisational charts and archival or backup files.

 

Interviews

Interviews should be carried with the relevant stakeholders in order to get views about the current system and gather information about the requirements for the proposed system. The interview method is powerful because it enables the analyst to have face to face contact with the interviewee.

Therefore in executing an interview, the following guidelines should be followed:

  1. The interviewee must be informed in good time and the topic of discussion communicated accordingly to allow for adequate preparation.
  2. Avoid personal biases in your questions and perspectives.
  3. Be careful about body language and proxemics. Proxemics refers to things like sitting arrangement, body closeness and how people react when their private distance is violated.

Figure 4.3 shows a verbatim introduction of sample interview with the library manager.

INTERVIEW TITLE

BRIEF INTRODUCTION         Interviewer: ……………

Interviewee:… .

Interviewer: Hello…………

Interviewee: Hello. Welcome to my office.

Interviewer: Thank you. Please call me Pat. I would like to ask you a few questions about the system that we are developing

Interviewee: …………………………………………………

…………………………………………………

…………………………………………………

Fig. 4.3: Example of an interview

 

Advantages of interviews

  1. Non-verbal communication like facial expressions can be used and observed.
  2. Questions can be rephrased instantly for clarification and to probe the interviewee further.

 

Disadvantages of interviews

  1. It is difficult to organise interviews and they are time consuming.
  2. The interviewee may not fully open up on some issues that may be personal or sensitive.

 

Questionnaires

A questionnaire is a special purpose document that allows a person to collect information and opinions from the people who receive and respond to it. The main advantage of using this method is that the questionnaires give the respondents privacy when filling them and they can do so at their own pleasure. This may enhance the sincerity of the information given.

Figure 4.4 below shows an extract of a questionnaire used to gather data from library attendants.

QUESTIONNAIRE

BRIEF INTRODUCTION                Date: …,………….

.

………………………………………………………………………

QUESTIONS

  1. How long have you worked as a library attendant:

1 yr.       2yrs.       over 2 yrs.

  1. How long does it take to rearrange books on the shelves?

days        weeks        months

Fig. 4.4: An example of a questionnaire

 

Advantages of questionnaires

  1. Since they are filled and returned in privacy, more sincere responses are possible.
  2. The respondent can fill the questionnaire at their own pace.

 

Disadvantages of questionnaires

  1. Good questionnaires are difficult to prepare.
  2. The respondent may not fully understand the questions because of ambiguity of language hence give erroneous responses.

 

Observation

Observation requires the observer to participate or watch closely as a person performs activities in order to learn about the system. This method gives the analyst first hand experience about the problems and exposes him/her to the system requirements. The main advantage of observation is that concepts that are too difficult for non-technical staff to explain can be observed. However, this method has some drawbacks too. These include:

  1. The person being observed might alter behaviour leading to wrong equirements being observed.
  2. The need to be on-site consumes a lot of time.

 

Automated methods

Automated data collection is mostly used when actual data is required but difficult to get through interviews, observation or questionnaires. Such data may be collected using devices that automatically capture data from the source such as video cameras, tape recorders etc.

 

Preparing and presenting the fact finding report

At the end of the information gathering stage, the analyst must come up with a requirements definition report that has the following details:

  1. Cover letter addressed to the management and IT task force written, by the person who gathered the facts.
  2. Title page which includes the name of the project, name of analyst and the date the proposal is submitted.
  3. Table of contents.
  4. Executive summary which provides a snapshot of how the new system is to be implemented. It also includes recommendations of the system analyst because some people will only have to read the summary to make decisions.
  5. Outlines of the system study which provides information about all the methods used in the study and who and what was studied.
  6. Detailed results of the study which provide details of what the system analyst has found out about the system such as problems, constraints and opportunities that call for an alternative.
  7. Summary which is a brief statement that mirrors the contents of the report? It also stresses the project’s importance.

This report is then presented to the management for evaluation and further guidance.

fig 4.5 shows a sample general outline of the fact finding report presented to the management of the school library and the head of the I

 

Library management information system

Fact finding report

1.0 Table of contents.

2.0 Executive summary.

2.1 Objectives: The new computerised system is intended to improve efficiency in the library by:

(a) Keeping an inventory of all the books in the library and automatically updating the stock hence eliminating the tedious physical counting         process.

(b) Reducing the time needed to seek for a book by 60%.

(c) Tracking overdue and lost books.

2.2 Recommendation:

This system could result in efficient processing of library transactions. It will replace the tedious manual system.

3.0 Methods used to study the system

3.1 Interviews: Used when seeking facts from management.

3.2 Questionnaires: Circulated to user staff.

3.3 Observation: Observed book search and issue.

4.0 Detailed results

4.1 Problems: Duplication of records, delays and book loss.

4.2 Opportunities: Efficiency, stock management etc.

4.3 Alternatives: Enforce controls in current system, more staff etc.

5.0 Summary.

The new system is highly recommended because the other alternative of enforcing controls and employing more staff will add operating costs with little additional value.

Fig. 4.5: A sample outline of a fact finding report

NB: The sample report is simplified for purposes of instruction at this level and should not be taken as a complete report. A complete report lay comprise of several bound pages.

 

Requirements specification

Requirement specification, the system analyst must come up with the detailed requirements for the new system. Remember that in the long run the hardware and software used to develop the system mainly depends on input, output and file requirements. For example, if one of the input requirements is that the system would require data in picture format then one input device that cannot be avoided is an image capturing device such as a digital camera or a scanner. At this stage the following requirements specifications are considered:

  1. Output specification.
  2. input specification
  3. File/data stores.
  4. Hardware and software requirements.

 

Output specifications

As opposed to data processing cycle where we follow the input-process-output m­odel in system development, consideration is given to the output requirements of the new system first. This is because; the main interest from a system is information (output). For example the management of the library in our case study is interested in whether the system can generate reports on overdue books, charges on late return, inventory etc.

The quality of system output depends on how well management and user requirements were identified. The Output is usually in the form of reports either in hardcopy or softcopy form.

The following factors should be put into consideration when designing the output

  1. The target audience. For example, top management would require a summary of overall performance in the organisation while a user report may show only the transactions carried out or transactions at hand
  2. The frequency of report generation. Some reports are required daily, others weekly, monthly or annually. However, some are required in an ad hoc manner i.e. at random.
  3. Quality and format: The quality and format of information to be generated should be put into consideration.

For our case study outlined earlier, the following outputs are needed from the library management system:

  1. A report about all the overdue books showing charges against each borrower.
  2. A search report for a particular book showing its classification and whether its on the shelve or not.
  3. A search report about a particular member showing which books he/she is currently holding. Table 4.1 below shows a sample report expected to be generated from the computerised library system showing all the overdue books.

       Table 4.1

  OVERDUE BOOKS    
ISBN Number Title Member

Name

Date

Issued

Date Due Overdue Days
1.9966495746

2. 9966 49 600 x

3. ……………

4. ……………

5. ……………

Computer studies

Mathematics 1

………………

………………

………………

James L. Wak

Linda Were

……………

……………

……………

10/01/2005

12/01/2005

……………

……………

……………

24/01/2005

26/01/2005

……………

……………

……………

6

4

……

……

……

 

Input specifications

Once the system analyst has identified the information (output) requirement of the new computerised system, he/she goes ahead to identify the input needed to obtain the relevant information from the system. In our case of the library, the following inputs can be deduced from the output specification:

  1. The type of data needed to add a book to the books file or database in the library. For example in the library database the following data items may be entered:

(a) Title of the book.

(b) Names of the author(s) of the books.

(c) The ISBN number of the book.

(d) Book ID

  1. Determine data that is needed for someone who wishes to borrow a book.

 

After identifying all the inputs, the analyst designs the user interface by designing data entry forms or screens. An example of an input form is the new member registration form as shown in Figure 4.6.

New member registration

Surname:

Registration number:

First name:

Gender:

Save
exit

 

 

 

Fig. 4.6: Data entry form design

The user interface is an important determinant of whether the system will be happily accepted by the users or not. Hence, it must be designed with a lot of care. The following guidelines should be observed:

  1. Objects placed on forms like text boxes, labels and command buttons must be neatly aligned and balanced on the form.
  2. The size of the form must not be too small for user legibility or too big to fit on the screen
  3. The colour for the interface must be chosen carefully to avoid hurting the eye. Avoid colours that are too bright.

 

File/data stores

File requirements specification involves making an informed decision on files required to store data and information in the system. The system analyst should identify the number of files that will be needed by the system and determine the structure of each of the files. For example, will the files allow direct access? Will the files be sequential files stored on a magnetic tape?

The attributes of the records in a file should also be identified. An attribute is a unique characteristic of a record for which a data value can be stored in the system database. If it is a student, one attribute can be the name and the other is the student’s registration number. For a book record, the attributes that can be identified include: Book ID, international serial book number (ISBN), the title, publisher, year of publication, date of issue and date of return.

However, only those attributes that are of importance to the system will be picked and used to store data for each record. In our case study for instance, we only need the Book ID, title, author, ISBN number, date of .issue and return.

These attributes will form the basis for table design in the database. Each attribute will become a field in the table. For example, there will be a Books table that will have fields for each record.

 

Factors to consider when designing a file

In order to design a good file, you need to consider the following aspects:

  1. The key attribute or field: This is usually an attribute that is unique for each record.
  2. The type of data: Each field has a data type. Book titles can be stored as data of type “text” while the date of borrowing a book as of the type “date” in the database.
  3. The length of each field: This is important because the longer the field, the slower the system takes to process transactions. A name field can be specified to be 30 characters long while the integer field can be 10 characters long. However, these vary depending on the system developer’s perception of how the system should store the data.
  4. Back up and recovery strategies: The updated copies of data and information files need to be stored in a different place other than the location of the current system. This makes sure that even if the current file gets corrupted or crashes, the backed up data can be used to recover or reconstruct the original file.

 

Hardware and software requirements

The system analyst should specify all hardware and software requirements for the new system. Some of the factors to consider in hardware and software specification are:

  1. Economic factors such as price and acquisition method.
  2. Operational factors e.g. reliability, upgradeability and compatibility with the existing resources.
  3. User-friendliness.

 

System design

There are several tools for designing an information system. Examples of such tools are flowcharts, data flow diagrams, entity relationship models and structured charts. In this book, we shall concentrate on the use of the system flowcharts as the primary tool for system design.

A system flowchart is a tool for analysing processes. It allows one to break process down into individual events or activities and to display these in shorthand form showing the sequential or logical relationships between them.

After drawing the system flowchart, other algorithm design tools like pseudo codes and program flowcharts can be used to extract the processing logic for each module in the system before system construction.

 

The system flowchart has many similarities to the program flowchart covered earlier in the book. However, it has its own set of symbols and it seeks to depict the whole system rather than the individual program modules. Figure 4.8 shows some common system flowchart symbols.

Other symbols that are of great importance at this level are as follows:

Rectangle with rounded corners: represents an event which occurs automatically and usually triggers a chain of other events. For example, the book lending process is triggered by a student request!

Kite: represents the sort operation.

Designing a system flowchart

Designing system flowcharts gives a concise picture of the way particular processes are done within the business organisation. After this has been achieved, the next logical step of making changes to the processes for the better can be handled easily.

Although there is no formal approach for designing a system flowchart, the following guidelines are important:

  1. Start by writing the title of the flowchart. For our case study, the title “Library Books Management Information System” could be sufficient.
  2. If possible, start drawing the flowchart with the trigger event. In this case, our trigger would be a student request to borrow a book or to return an overdue book.
  3. Note down the successive actions taken in their logical order until the event or process is concluded. Use few words to describe the actions.
  4. When there are many alternatives at the decision stage, follow the most important and continue with it. Other significant but less important alternatives can be drawn elsewhere and reference made to them by using the on/or off page connectors. Figure 4.9 shows the system flowchart for the proposed computerised library management system for the school.

Explanation

From the system flowchart, we observe that:

  1. A member e.g. a student requests for a particular book.
  2. The system checks for the students record in the system. If the student has more than three books, a message to this effect is displayed and cannot borrow an extra book.
  3. If the student has less than three books, then the book can be given out to him/her.

From the system flowchart, a program flowchart for a particular task can be extracted. Figure 4.10 illustrates the book lending process extracted from the library management system flowchart.

 

System construction

System construction refers to the coding, installation and testing of the modules and their components such as outputs, inputs and files.

The purpose of the construction phase is to develop and test a functional system that fulfils the business and design requirements. Indeed, programmers come in at this stage and are briefed on the system requirements as illustrated using various design tools in order for them to construct a computerised working model of the same.

System construction methods

There are a number of programming techniques that can be used to construct a designed system. These include:

  1. Using the high-level structured language such as Pascal, COBOL etc
  2. Using fourth generation languages (4GL) – These are easy to use programming languages. Some of the fourth generation languages            are Visual Basic, Visual COBOL, Delphi Pascal etc.
  3. Customising the standard packages – This involves the use of a ready made software package mostly a database software, financial package or enterprise management system.

Due to the varied approach to system construction available, Chapter 5 in this book introduces you to Visual Basic programming while Appendix I explains how a database package can be customised to construct a system. Figure 4.11 shows a data entry form constructed to enable entering a new book record into the library information database.

Testing the system

After construction, the system is tested by entering some test data to find out whether its outputs are as expected. The system is tested using the requirements specifications and the design specifications to find out whether it meets all requirements specified.

For example, if one of the requirements of the computerised library management system is to ensure that no member is allowed to borrow more than three books at the same time, it must do that without fail. Figure 4.12 shows a message box to this effect.

 

System implementation

System implementation is the process of delivering the system for use in day to day operating environment for the users to start using it. The areas to be addressed during system implementation include file conversion, staff training, and changeover strategies.

File conversion

Every time a new system is implemented, the format of data files might require modification or change. This process is referred to as file conversion. A new system may require a change in file format e.g. from manual to computerised. The factors to consider at this point are:

  1. Whether the new system requires a new operating system and hardware. The best practice today is to develop systems that do not need hardware change unless it is very necessary.
  2. Whether you need to install new application software. For example if you have developed a new system by Customising a database application software, you need to install that software if it is not installed.
  3. Whether you need to create new database files for the new system. For example, where files are manual, electronic ones will have to be made. However, remember that we strive to develop systems that are data independent too. That means that the systems can be changed without affecting the organisational data structures in the databases.

Staff training

Availability of appropriate documentation like user manuals goes a long way to make staff training easy, quick and effective. System implementation can fail if the staff are not trained properly leading to great loss of company resources.

Changeover strategies

Changeover simply means how to move from the old system and start using the new. Most businesses especially those that are driven by information technology need as smooth a changeover as possible. Some of the system changeover strategies are:

Straight changeover

In straight changeover, the old system is stopped and discarded and the new system started immediately. This sudden change of old to new means that the project faces higher risks in case the new system faces problems. This is because the old system would not be there to fall back to. The advantage of this method is that it is cheaper because you do not have to run the two systems in parallel. Figure 4.13 shows the straight changeover strategy diagramatically. At a time t, a switch is made from the old to new system.

Parallel changeover

In parallel changeover, both the old and new system are run parallel to each other for some time until users have confidence in the new system then the old system is phased out. This method is a bit costly because extra resources have to be engaged to run the two systems in parallel.

However, its lower risk to business operations and thorough testing of the new system are some of its advantages. This method is not suitable for large systems because of the high operational costs during changeover. Figure 4.14 depicts a parallel changeover process.

Phased changeover

In phased changeover, a new system is implemented in phases or stages. A good example is the way the education system is changed from the old to the new curriculum. Each year at least one class level changes over to the new syllabus.

Sometimes, one phase may run a new system for testing before it is implemented into all the other phases. This is called piloting. The main”, disadvantage of phased changeover is the danger of incompatibility between various elements i.e. hardware or software of the same system. However, its advantage is that it ensures slow but sure changeover.

 

Security control measures

Information and data security have become some of the most important aspects of information systems. A lot of careful planning has to be done in order to have what is called inbuilt security in the system. This is because information is under constant threat of being illegally accessed or disclosed to unauthorised parties. Therefore, the system implementers must make sure that the security features built in the system are properly configured during the implementation stage.

System maintenance and review

System maintenance is the adjustment and enhancement of requirements or correction of errors after the system has been implemented. Regardless of how well the system is constructed and tested, errors may be detected when the system is in use.

System review is a formal process of going through the specifications and testing the system after implementation to find out whether it still meets the original objectives. This act is sometimes called review and audit. If the system does not meet the stated objectives, system development might start all over again.

System documentation

System documentation is a life long process in the system development lifecycle. After a system has been implemented, any maintenance work must be documented in order to update the existing documentation. In this chapter, we have constantly provided sample documentation in every stage of system development using the school library management system case study. Generally comprehensive system documentation consists of the following:

  1. Report on fact finding
  2. Requirement specification
  3. System and module flowcharts
  4. Table/file structures description
  5. Sample test data and expected output
  6. Output reports

Reports on fact finding

At the end of fact finding stage, the system analyst should prepare a well detailed report that mainly outlines:

  1. The methods used to collect data.
  2. Weaknesses of the current system as evidenced by the collected data.
  3. Recommendations: Why there is a need to replace or upgrade the current system.

Figure 4.5 on page 104 shows a sample fact finding report for the school library system.

Requirement specification

The report on requirement specification outlines mainly the:

  1. Output requirements for the new system such as reports.
  2. Input requirements.
  3. Hardware and software required to develop the new system.

Table 4.1 on page 106 gives a sample report expected from a computerised library system, while Figure 4.6 on page 107 gives a simple illustration of an input form for new library members.

System flowchart

The system flowchart shows the overall functionality of the proposed information system. Therefore at the end of the designed phase, the system analyst should write a report that contains:

  1. The system flowchart or data flow diagrams that shows the processing logic of the information system.
  2. Any module flowchart that may help programmers in construction of the required subsystem or modules. a sample module flowchart.

Table file structures description

Depending on approach used in system construction, the report should contain file or table structure definitions. For example, if you opt to construct a system using customisation approach, details on table structures should be well documented (see Appendix I). Figure 4.15 shows a sample table structure of the Books table in a library system.

Sample test data

To test whether the new computerised information system is working as expected, you need to use test data for every module (subsystem). For example, in our library case study, we need to test sample data for books entry, book borrowing etc. Table 4.2 shows a sample test data that can be entered in the database whenever a book is borrowed.

Table 4.2

Last name Middle name Class Stream Book Date Return
        borrowed borrowed date
Mburu James 3 C Maths Form I 8/6/2005 26/6/2005
Janet Achieng 3 A Kamusi sanifu 23/6/2005 30/6/2005
Helen Mutua 4 B Elementary

chemistry

6/6/2005 24/6/2005
Ali Mohamed 2 A Computer

studies

6/5/2005 23/5/2005
Kerich Dennis I A Biology

form I

6/6/2005 24/6/2005
James Kamau 3 B Computer

studies

7/6/2005 25/6/2005

Output reports

To prove that the system is working and giving the desired result, you should provide a number of sample output from various system modules. Figure 4.16 shows a sample report showing a list of members who have borrowed books.

 

User manual

User manuals are supposed to help a person to use the system with as little guidance as possible. Therefore, the manual must contain information such as:

  1. How to install, start and run the system.
  2. How the system appears when running (interface).
  3. How to carry out various tasks e.g. in our case study, this would include new books entry, lending/borrowing, data entry etc.
  1. Error correction and how to get help when faced by exceptions. This would be in a troubleshooting guide.

Figure 4.17 shows a sample main menu screen switchboard from which the user can access other modules.

 

PROGRAMMING WITH VISUAL BASIC

Chapter outline

5.1 Introduction

5.2 Starting Microsoft Visual Basic

5.3 Features of Visual Basic Integrated Development Environment (IDE) window

5.4 Saving a Visual Basic project

5.5 Opening an existing project

5.6 Visual Basic fundamental concepts

5.7 Control structures

5.8 Working with graphical objects

5.9 Modules and procedures

5.10 Creating menus, messages and dialog boxes

5.11 List boxes and combo boxes

5.12 Visual Basic data structures

5.13 Linking Visual Basic forms to a database

5.14 Creating a Visual Basic executable file

Introduction

In the previous chapter, we studied how to develop a system using some system analysis and design methods without necessarily referring to any particular programming language. Therefore, we have been looking at what a system analyst ought to do rather than how a particular task should be done. In this chapter, we shall learn how to develop programs using Visual Basic programming language. Note that any other programming language can be used to develop programs. Therefore, as a leaner, you are at liberty to select any other programming language and learn how to use it to construct systems.

Definition of Visual Basic

Visual Basic (VB) is a graphical user interface programming language for creating software systems that run under Microsoft Windows environment. It is modeled in line with BASIC language which was originally created to help students learn how to program.

Visual Basic has the following features:

  1. It is an event driven programming language. An event is a response generated by the program when the user performs an action e.g. a mouse click. The response depends on the code held in an event procedure. An event procedure is a group of self contained statements that are executed by the computer when a trigger action is performed. For example, a mouse click may cause a menu to be displayed on the screen.
  2. It has a collection of tools that are used by programmers. These tools are called controls. The controls can be accessed easily by clicking their icons on the toolbox to select them.
  3. It has special objects called forms that have a title bar at the top. The programmer can then add controls such as a menu bar, status bar, toolbars, buttons, and slide bars to the form when creating an application.

Starting Microsoft Visual Basic

You can start Visual Basic from the Programs menu by pointing to Microsoft Visual Studio and then selecting Microsoft Visual Basic. Depending on the way the application has been setup, you may see the New Project dialog box

This dialog box allows you to set up a new project. You can set up several types of projects as shown by the different icons in this dialog box. However, for the purposes of learning, let us select the Standard.EXE project found on the New tab. Click the Open button. The application window will appear. This is the Visual Basic Integrated Development Environment (IDE).

Features of Visual Basic Integrated Development Environment (IDE) window

The Visual Basic application window (Figure 5.2) has many similarities to common windows based applications.

The following is a summary of the various features identified in the window:

The standard toolbar

Like in many other applications, the standard toolbar has the standard icons that are shortcut commands to the menu bar commands. Simply point to an icon and a text tip will appear telling you the name of the icon. Of great interest to us this time are the three commands of Start, Break and End.

To execute a Visual Basic project, simply click the Start button or select Start1from the Run menu. Execution of the program can be temporarily suspended by clicking the Break button. Resume the run by selecting Continue from the Run menu. Finally, the execution can be stopped by clicking the End button.

Forms and controls

Forms and controls are generally called objects. An object is usually associated with an event hence most objects have their own properties and methods. The properties define the appearance of the object while the method is a predefined action that can be set to occur or affect the object. For example show method makes a form visible on the screen.

The form design window is the place where the programmer does the actual design of the user interface for the program. This is accomplished by selecting the relevant control icons from the toolbox then placing them on the form design window. The control can then be moved and resized as desired by the programmer.

The entire form can be moved around on the screen by holding the title bar of the project container window then dragging it to the required position.

Project window

The project window displays a hierarchical list of files associated with a particular project. The files represent forms and program modules in the project. For example, Figure 5.2 shows a form whose title is Form 1.

Properties window

The properties window displays a set of various characteristics unique to each active object in the project. Some examples of properties include name, caption, colour, height etc.

When a new project starts, it is most likely that the form design window is active. In this case, the properties for the form will be displayed and can be changed by the programmer as appropriate. For example, we can change the caption of the form by clicking on the Alphabetic tab in the properties window then changing the value associated to Caption property from Form.l to say “Book Data Form”. Notice that the caption in the title bar of the active form changes simultaneously as you type the new name in the properties window.

 

 

Code editor window

Figure 5.2 shows that the project window has three icons at the top left hand comer. One of them is called the code view icon. Point to the icon with the mouse pointer and a tool tip will appear showing its name. If you click it, the code editor window opens displaying the code of the object that is currently selected. Alternatively, double click the object on the form for which you want to edit its code. The code editor window will open (Figure 5.4). In this case, we double clicked the form.

Form layout window

The form layout window allows you to specify the screen location of the form when the project is Executed. This can be done by dragging the form in this window to the desired location.

The Visual Basic toolbox

Visual Basic tool box has controls that enable a person to design and customise forms. Figure 5.5 depicts the toolbox.

Pointer: This is not actually a control but a tool used to select an object or objects to be worked on.

Picture box: A picture box is used to display graphical objects or text and to initiate event actions. It is similar to an image box but has more properties, redraws slower and cannot be stretched.

Label: A label displays text on a form. The text cannot be reassigned during program execution though its appearance can be altered.

Text box: A text box provides a means of entering or displaying text. The text may be already available or can be entered during the program execution.

Frame: A frame is a tool rather than a control used as a container for a group of controls.

Command button: A control used to activate an event driven procedure.

Check box: As opposed to the option buttons a check box is used if more than one selection are to be made.

Option button: Option buttons are used when one selection must be made before an action is carried out. For example, if you want to turn off a computer running on Microsoft Window 9x, check the shut down option button then click Yes/OK.

Combo box: A combo box is a special type of list box that combines the capabilities of a text box and a list box. It provides a list of text items for selection by the user during program execution. Items can also be added during program execution.

List box: The list box control provides a list of text items for selection by the user.

Horizontal scroll bar: A horizontal scroll bar is used for drawing horizontal scroll bars on a form.

Vertical scroll bar: A vertical scroll bar is used for drawing vertical scroll bar on a form.

Timer: Timer control allows timed events to occur repeatedly at a specific time intervals.

Drive list box: A drive list box provides a means of selecting a drive from a list of existing drives.

Directory list box: A directory list box provides a way of selecting a directory from a list.

File list box: A file list box provides a way of selecting files within a group of files.

Shape tool: A shape tool is used to draw circles, ellipses, squares and rectangles within forms.

Line tool: A line tool is used when drawing straight lines within forms.

Image box: An image box control is used to display graphical objects.

Data control: A data control when placed on a form provides a means of displaying information from an existing database.

NB The number of tools available on the tool box depends on the edition and release of Visual Basic you are using

Saving a Visual Basic project

Saving a project in Visual Basic is a bit different compared to other applications. This is because Visual Basic operation involves saving multiple files.

( a) To save a new Visual Basic project for the first time, select the Save project As command from the File menu. The Save File As dialog box of Figure 5.6 (a) appears. You will first have to enter a form name e.g. bookdata and then click the Save button. The form is saved as a file with extension .frm.

(b) After this, the Save Project As dialog appears. Type the name of the project and it will be saved as a file with extension. vbp (Visual Basic project

Opening an existing project

You can open a project when Visual Basic starts or from the file menu. To open a project during startup, from the New Project dialog box that appears when Visual Basic is starting, click the Existing tab. A list of existing projects will be displayed as shown in Figure 5.7

(a). Alternatively, if Visual Basic is already running, close all other projects then click the Open Project command on the File menu. The Open Project dialog box appears from which you can select the Existing tab. (Figure 5.7 (b)). Type the name of/or select the project to open.

Visual Basic fundamental concepts

Before going further into detailed discussion on how to develop programs in. Visual Basic, it is important to highlight some of the fundamental concepts used in Visual Basic.

Data types

Table 5.1 shows the data types supported by Visual Basic:

Table 5.1

Data type Description
Integer A whole number with no fractional part. Integers range

from -32768 to 32767.

Long integer Numbers which are integers but have a bigger value and

range. They range from -2,147,483,648 to 2,147,483,647.

Single

 

A single precision real constant includes a fractional part. The largest value is 3.4 x 1038
Double

 

It includes a fractional part but has far much larger magnitude than the single real number constant. However, it cannot be larger than l.2x 1 0308
String

 

Characters enclosed in quotation marks
Boolean

 

Data types that have only two logical states i.e. true or false.

 

 

­Constants

In programming, a constant is a value that remains the same. It does not change during the execution of the program. There are three types of constants: string, numeric and named constants.

String constants

A string constant can be defined as a sequence of characters enclosed in quotation marks. They are used to write non-numeric values like telephone numbers, addresses and names. The following are examples of string constants: “Holiday season”, “345678”, “Why don’t you call”, “$72.10”

Numeric constants

Numbers are usually referred to as constants in Visual Basic. In most cases, the numeric constants are either whole numbers (integer) or double or single. Some examples of numeric constants are:

0, 3, 6000 +70,   1.4E+2, 1.674,  -.00456,

Named constants

A named constant is identified by name rather than its actual value. In Visual Basic, the reserved word Canst is used to declare this type of constants e.g. Canst Price As Integer = 20, means that an integer value 20 is identified using the name price.

Variables

A variable is a memory location referred to by name used to hold a value that is subject to change during program execution. When a variable is declared in a program, the computer sets aside memory space to hold a value in the variable. The variable may be a numeric constant, a character, a string or any other data item.

In Visual Basic, the following rules should be followed when declaring variables:

  1. The variable name must not have more than 255 characters.
  2. The variable name must start with a letter.
  3. The letter case is not important when declaring variables.
  4. A variable name must not be a reserved word. A reserved word is a special word that Visual Basic understands as a command, internal function name or simply set aside for use by the program. Examples of reserved words are Case, Else, Dim, etc.
  5. Variable names should not have spaces.

A variable is declared using the reserved word Dim. Dim is the short form of the word dimension (size). It is used to associate a variable with a specific data type. For example to declare a variable that will store the first name of a student in a program, the following declaration can be used:

Dim FirstName As String

This means that the variable FirstName is of the type string.

Variants

A variant is a variable whose data type has not been explicitly declared by the programmer. In this case, the variable type will be determined by the value held by the variant. These types of variables are called variant type because their data type keeps on changing with the values they hold. Although this may sound okay, it is not a good programming practice. All variables should be explicitly declared.

Scope

The word scope refers to the level of the program that a variable, a constant or a procedure is recognised. The scope of a variable constant is said to be global or local. The scope of a procedure variables or constants is set by declaring it as either private or public. The following terms are used in this regard:

  1. Private subprocedure.
  2. Public subprocedure.
  3. Global variables/constants.
  4. Local variables/constants.

A public procedure can be accessed from any module or form in the program. However, a private procedure is accessed in the module or form within which it is declared.

A variable or constant that is declared within a procedure is said to be local. This means that it can only be accessed within that procedure. However, a variable or constant that is declared outside the standard module but within the same project is said to be global. Such variables can be accessed by all procedures within the project.

If a public procedure is to be accessed from a module or a form other than the one it is contained in, the form or module name must be preceeded by the module containing the definitions i.e. GlobalModuleName.Active FormName (Arguments).

In Visual Basic, to declare variables as either private or public use the syntax:

  1. Private X As Integer
  2. Public Y As String

In the first declaration, the private variable X can only be accessed in the module within which it is declared. In the second example, it can be accessed by other subroutines in the same project.

User defined data types

Sometimes, a programmer may want to have a single variable that can store several data types as a unit. Such a data type whose individual components are standard data items are referred to as user defined data types. Some examples of user defined data types are records, arrays, enumerated types, lists etc. They are user defined because it is the programmer who creates them in the program. Each element or member can be accessed individually by using a period between the user defined variable and the member name e.g. if a record known as schoolrecord has a name field, then to access the name field, a programmer will type schoolrecord.name in the code.

Using suffixes to declare variables and constants

Suffixes are special symbols appended to the end of a variable or constant name in order to associate them with a particular data type. It makes programming easier and faster. Table 5.2 summarises some common

suffixes.                                     Table 5.2

    Examples  
Suffix Data type Long declaration Short declaration
% Integer Dim A As Integer A%
! Single Dim X As Single X!
$ String Dim Q As String Q$
& Long integer Dim C As Long Integer C&
# Double Dim P As Double P#

Mathematical operators

In order to write correct mathematical expressions, you need to understand some of the operators used in Visual Basic. These include arithmetic, relational and logical operators.

Arithmetic operators

Arithmetic operators are special symbols that are used to write arithmetic expressions like addition, subtraction, division and multiplication. However, it is also possible to carry out other mathematical operations using other operators. Table 5.3 shows a summary of symbols used in arithmetic operations:

Table 5.3

Symbol Name Operation
+ Plus sign Addition
Minus sign Subtraction
* Asterisk Multiplication
/ Slash Division
/\ Caret Exponentiation
Back slash Integer division
MOD Modulus Integer remainder

NB: The last two rows in the table can be explained as follows:

  1. In an integer division, each of the numbers being divided is first rounded to become an integer then the quotient is truncated to an integer. For example, 2.4/3.5 will result in 2/4 being evaluated.
  2. The MOD operator returns the remainder of an integer division. For example, 4 MOD 3 returns 1 and 5MOD3 returns 2.

Operator precedence/hierarchy

Arithmetic operators in Visual Basic have the following order of precedence when used in a program. Notice that the order may not be the same as that of algebra in mathematics. Table 5.4 illustrates how to carry out operations.

Table 5.4

precedence symbol Explanation
1 Exponentiation All exponential expressions are performed first
2 Multiplication/division Carried out after exponentiation; left to right In an expression.
3 Integer division Done after all multiplication and normal division operations
4 Integer remainder Done after integer division
5 Addition and subtraction Are carried out last, left to right.

For example write down the order of evaluation of the following expression:

(b /\ 2 – 4 * a * c )/2 * a.

Relational operators

A relational operator is used in an expression that returns a true or false value when evaluated. The operators can compare numeric variables, constants or expressions. Table 5.5 shows a summary of relational operators used in Visual Basic.

Table 5.5

Operator Name
= Equal to
<> Not equal to
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to

 

The following are examples of relational expressions:

  1. Y < > 100 2. Y> 60    3. S< = sqr(G + V) 3. Loss = (Expenses – Profit)

The expression in 1 will evaluate to true if y is not equal to 100 otherwise it will evaluate to false.

A decision construct in a program based on a relational expression would make a decision depending on the outcome of the evaluation.

Logical operators

Logical operators are used to combine expressions to form compound expressions. Table 5.6 summarises some common logical operators used in Visual Basic.

Table 5.6

Operator Operation
And Results in a condition that is true if both expressions are true.
Or Results in a condition that is true if one of the conditions is true or both are true.
Xor Results in a condition that is true if one of the conditions is true and the other is false.
Not Negates the value of a logical expression.

For example:

  1. (x = 30) AND (student = “John”)
  2. IF (x = 20) OR (y = 30) THEN
  3. IF x NOT 0 THEN

The assignment statement

An assignment statement is an executable statement that assigns whatever is on the right of the assignment operator to the variable on the left. In Visual Basic, the assignment operator is the equal sign (=). A variable can be assigned a value as follows:

Variable = Expression

Examples of assignment statements are:

  1. P = 0.25 2. E = M*C”2                3. Area = 1/2 * base* height 4. X = X + I

NB: The last statement on the right (X = X + I) does not make mathematical sense. Yet, this is the beauty of the assignment statement in programming. The statement can be interpreted as follows:

Add 1 to the original value of X and assign the sum to X.

The Print statement

The Print statement displays data on the active form of your Visual Basic project. It can be used to display processing results of a program. If you run the project, you will notice that the result of the Print statement starts being displayed in the top left comer of the form. The structure of the Print statement is:

Print VariableName (this prints out the value held in a variable).

or

Print “String”

(this prints out the string between the two quotation marks. If there is nothing between the two quotation marks, a blank line will be the output)

The skeletal code listing below shows a sample code that displays the values stored in the variables StudentName, TotalMarks and AverageMark on a form.

Private sub Form_Load ( )

Dim StudentName As String, TotalMarks As Single, AverageMark As Single

…………

StudentName = “Edward”

 TotalMarks = 1000

AverageMark = 200

……………

Print, StudentName, TotaIMc;zrks,AverageMark

End sub

The following output will be displayed on the form: Edward 1000 200

NB: The use of a comma to separate the various elements to be output by the Print statement makes them to be widely spaced on the screen. To have a compact display with the various outputs close to each other, then use a semicolon to separate the various elements e.g. Print StudentName; TotalMarks AverageMark would display

Edward       1000           200

Library functions

Library functions are modules that have been pre-written and included in the Visual Basic language. A function performs a single task like calculating a mathematical expression then returns a value. A function will usually have a name and can be called when needed to perform a particular task. Visual Basic has many library functions. A library function is accessed by stating its name followed by the information that must be supplied to the function enclosed in parenthesis. This process is called calling a/unction. The values held in the parenthesis are called arguments. When the function is called, it uses the supplied arguments to perform an operation and return a value. Table 5.7 shows a summary of some the library functions used in Visual Basic.

Table 5.7

Function Call Description
Date z = Date ( ) Returns the current date
Exp z = Exp(w) Returns the value of eW
Sqr z = Sqr(w) Returns the square root of w
Log z = Log(w) Returns the natural logarithm of w
Str z = Strew) Returns a string whose characters are w e.g.

Str(6.80) = “6.80”

Cos z = ‘Cos(w) Returns the cosine of w
Abs z = Abs(w) Returns absolute value ofw e.g. Abs(-8) = 8
U case z = Ucase(w) Returns the upper case equivalent of w
Int

 

 

z = Int(w) Returns the largest integer that is algebraically less than w e.g. Int(2.2) = 2
Time z = Time Returns the current system time.
Format z = Format Formats the output to appear as stated.

Using the format function

The format function helps the programmer to display data in many different formats. Table 5.8 below shows how data can be formatted.

Table 5.8

EXPRESSION SAMPLE FORMATTED OUTPUT
Print format(16.778994,”##,##”) 16.78(notice the rounding)
Print format(now, “mm-dd-yyyy”) 1-20-2006
Print format (15678, “##,###.00”) 15,678.00
Label1.caption=format$(sprice, “##,###,##”) 10,630.75

 

NB: The dollar sign may be used with the format function depending on the type of output required. In the last row of the table, the formatted output is displayed on a label control.

Program comments

Comments are English statements included in the code to document a program. The comments are not executed when the program is running. In Visual Basic, a comment starts with a single apostrophe (‘) followed by the comment statement. For example:

X = Sin(p) ‘find the sine of p and store it in X

Print X        ‘display the value ofX on the screen

Converting a numeric string to a value

If you enter a number in a text box, the best way to convert it into a value is to use the Val function This is because the computer treats anything typed in the textbox as a string. The Val function operates on the string and returns a numerical value.

Hence, if the name property of a text box is set to txtLength, then the number typed in it can be read as a value into a variable x as follows:

x = Val(txtLength.Text)

Converting a value to a string

Assuming a particular variable has a numeric value and you wish to display the value in a text box, then you have to convert the value to a string first. Suppose that the name of the text box is txtArea and the integer variable is x then:

txtArea.Text = Str(x) ‘ display the value in x as a string in txtArea.

 

Project 5.1

Create a program that can be used to calculate the area of a rectangle. The program should prompt the user to enter the length and width of the rectangle. Figure 5.8 shows an overview of such a program.

 

 

To create the project, proceed as follows:

  1. Open Visual Basic and select the Standard.EXE from the New Project dialog box. A blank form will be displayed as shown in Figure 5.9.

 

  1. Place the necessary controls on the form. We need three text boxes and two command buttons. Double click the text box tool on the toolbox then the command button. The controls are automatically placed on the form and are given default names like Text! and Commandl. Add another command button. Use the shape tool to place a rectangle on the form. Drag the controls to the desired location on the form and repeat the process until you have the interface as shown in Figure 5.10.
  2. The next step is to define the set of properties for each control. To do this, right click the control then click properties. Set each control properties in the properties window as shown in the Table 5.9 below:

Table 5.9

Object Property Value
Label1 Caption

Name

“Rectangle”

IblRectangle

Text1 Font

Name

Text

Arial

txtLength

(blank)

Text2 Font

Name

Text

Arial

txtWidth

(blank)

Text3 Font

Name

Text

Arial

txtArea

(blank)

Shape Shape

Border Width

FillStyle

FillColor

0- Rectangle

2

4-Upward Diagonal

Blue

Commandl Caption

Name

Font

Exit

cmdExit

Arial

Command2 Caption

Name

Font

Calculate

cmdCalculate

Arial

 

 

NB: The conventional way of setting the name property of any object in Visual Basic is to use object prefixes such as txt for text or boxes, lbl for labels, cmd for command buttons etc.

  1. After setting the properties, we can now write the event procedures that calculate the area of the rectangle once values are entered in the txtLength and txtBreadth text boxes. To write the code, double click calculate button and add the code listing between Private sub cmdCalculate click and the End sub.

Dim L As Single, W As Single, A As Single

 L= Val(txtLength. Text)

W= Val(txt Width. Text)

A=L*W

txtArea= Str( A)

For the cmdExit button, just write End between Private sub cmdExit click and the End sub.

Figure 5.11 shows how your code should look like in the code window.

 

 

 

  1. Run the project. Enter a value in the txtLength and another in the txtWidth text boxes then click the Calculate button. Notice that the area of the rectangle is displayed as shown in Figure 5.12.

 

Explanation

  1. The first line declares the variables needed for the program to run and store values.
  2. The second and third lines assign the values in the text boxes called txtLength and txtWidth variables Land W respectively.
  3. The second last statement calculates the area of the rectangle while the last uses a function Str to display the result as a string value in the textbox named txtArea.

Adding more forms to a project

Sometimes a Visual Basic project may require the use of more than one form. To add a form to a project, the following procedure is followed:

  1. Click the Project menu then select Add Form command.
  2. In the dialog that appears, select the type of form you want to add from the New tab then click Open button.

 

Control structures

In Chapter 3, we introduced the three control structures that determine the execution of statements in a program. In this topic we shall discuss how these controls are implemented in Visual Basic.

Selection

The most common selection controls used in Visual Basic are:

  1. IF…… THEN.
  2. IF…. THEN…… ELSE.
  3. Nested IF.
  4. CASE selection.

The IF…THEN selection

The IF. . . THEN selection is used to execute a single statement or a group of statements that represent only one alternative or option. This means that some circumstances have only one option for selection depending on whether a condition evaluates to true or false. For example IF y = 80 THEN

Print (“……..”)

END IF

The statements in the If…Then…End If will be executed if the value of y is equal to 80 otherwise the whole block will be bypassed and the statements after END IF will be executed.

IF…THEN…ELSE selection

The IF… THEN.. . ELSE allows the execution of two alternatives or options depending on whether the test returns a true or false. Consider the following example:

IF average> 80 THEN

Print(“Excellent work! Congratulations”)

ELSE

Print(“Work harder next time”)

END IF

In this case, the statements starting with  ‘Excellent Work!….. ‘ will be displayed on the screen if the average is greater than 80. Otherwise, if average is less than 80, the statement “Work harder next time” will be displayed on the screen.

Nested IF selection

Nested IF selection is used if there are more than two available options to choose from. The general format of Nested IF is

IF <condition> THEN

Statements

ELSE IF <condition> THEN

Statement

ELSE IF <condition> THEN

Statement

ELSE <condition> THEN

Statement

 

Project 5.2

Write a program that can be used to find the roots of a quadratic expression.

ax2 + bx + C = 0

The formulas to solve the values of x in this expression are:

 

Xl = -b -sqr(b2 – 4ac)

2a

X2 = -b -sqr(b2 – 4ac)

2a

X=-b

2a

i.e.b2 – 4ac = 0 or b2 = 4ac

To create the project, proceed as follows:

  1. Test whether b2 is larger than or equal to 4*a*c. If it is true, then:
  2. Create a new project that would be used to calculate the values of x, Xl and X2 also called roots of the quadratic equation.
  3. In the appropriate event procedure e.g. the calculate button, add the code listed below:

‘Calculating roots of a Quadratic Equation

Dim a,b,c As Integer

Dim z,X,X1,X2 As Double

z=(b^2-4*a*c)

IF z> 0 THEN

X1=(-b+Sqr(d)) / (2*a)

x2 –x1=(-b-Sqr(d)) / (2*a)

ELSE IF z= 0 THEN

       x = -b / (2*a)

ELSE IF z= 0 THEN

Print (“This quadratic equation is not soluble”)

END IF

ENDIF

ENDIF

 

Explanation

  1. The expression b/\2-4*a*c is first assigned to a variable z.
  2. z is then tested if it is greater than zero. If greater, the program calculates the values of Xl, X2 and x. Otherwise a message “This quadratic equation is not soluble” is displayed.

The Case construct

As discussed earlier in control structures of chapter 3, the Case construct is used to reduce the tedious work of coding associated with the nested IF… construct. Let us look at a case statement that can display the name of a weekday when its number is provided.

‘Display weekday

Dim D As Integer

SELECT CASE D

CASE 0

       Print(“Sunday”)

CASE 1

       Print(“Monday”)

CASE 2

       Print(“Tuesday”)

CASE 3

      Print(” Wednesday”)

CASE 4

      Print(“Thursday”)

CASE 5

      Print(“Friday”)

CASE 6

       Print(“Saturday”)

CASE ELSE

       MsgBox(“Error -That is not a day in the week”)

End SELECT

Looping construct

In Visual Basic looping instructs the computer to execute the same block of code many times before a particular condition is met. Common looping constructs used in Visual Basic are:

  1. DO loop.
  2. WHILE…Wendloop.
  3. FOR loop.

DO loop

There are four ways of writing the Do loop. Two of the constructs require the condition to be tested first while the other two require that the condition be tested after the statement within the construct is executed at least once. The general formats of the four Do constructs are:

  1. DO WHILE <condition>

Statements

Loop

 

2.DO Until <condition>

Statements

Loop

  1. DO

Statement,

Loop UNTIL <condition>

 

  1. DO

Statements

Loop WHILE <condition>

 

Explanation

The Do While. ..Loop in 1 continues to execute as long as the condition is true. The Do Until. ..Loop in 2 continues to execute as long as the condition remains false. The loop in 3 executes the statements at least once as long as the condition is not true. Lastly, the loop in 4 executes the statements within the construct at least once as long as the condition remains true. for the first two DO statements, the test of the condition is done at the beginning of the loop hence avoiding execution of any statements in the loop as long as the condition required is not met. On the other hand, the last two loops allow a pass through the loop at least once before the condition is tested.

example 5.1

Write a program using the DO loop that will write numbers between 1 and 20 on the screen then stop. Save the project as Example 5.1.

Solution

  1. Double click the form to display its code window
  2. Add the following code listing between the Private sub form-load and

End sub.

x=O

Counter=O

DO WHILE counter<=20

x=x+1

Counter=counter+ 1

Print x

Loop

NB: All the other DO loops can be easily implemented with little effort following the general format provided.

Looping with While-Wend

The While..Wend construct can be used in place of a Do While loop. The general format of this construct is:

While <condition>

Statements

Wend

As with the Do While loop, this loop executes the statements within the construct as long as the condition is true.

Practical activity 5.1

Open the project for Example 5.1 and replace its code with the code below.

Dim x As Integer, Counter As Integer

x=O

Counter = 0

While counter<=20

x=x+1

counter=counter+1

Print x

Wend

Save the project as Example 53.

The FOR – NEXT loop

The FOR – NEXT Loop executes the statements within the construct a predetermined number of times. The general format of the FOR – NEXT

Loop is:

For index = lower limit To upper limit                         ‘sets upper and lower limits

statements

Next index                                                  ‘increments index by 1.

You can set the STEP value of the index as follows:

For index = lower limit To upper limit STEP 2

statements

Next index                                        ‘STEP increments index by 2.

The FOR construct is very suitable for accessing values in a list or array because of their sequential nature.

 

Practical activity 5.2

Open the project for Example5.3 and replace the code with the listing below:

Dim Number As Integer, Counter As Integer

Number= 0

For counter= 1 TO 20 STEP 2

Number= Number +  counter

Print Number

Next counter

 

Working with graphical objects

To add a picture or object on to a form, simply click the picture box or the image tool on the toolbox and then drag to define the area where you want the picture to be placed. Right click the object and then click properties. Set the Name and Path properties. The Path property tells the control where the picture is located.

Notice that after setting the properties, the picture is displayed on the form. If it is lying on top of other controls and you want it to be the background, right click it then select Send to Back.

Modules and procedures

Large projects must be made modular in nature to enhance maintenance and independence of the various blocks of code. The three main modules used in Visual Basic are explained in Table 5.10.

Table 5.10

Module Definition
Standard modules Their declarations and procedures can be accessed

by other modules. They are usually stored in files

that have the extension. bas You can create a standard

module by clicking Project then Add Module.

Form module Are stored as files with extension frm Each form

may have many procedures and controls. To add a

form to the project, click the Project menu then

Add Form.

Procedures These are events or self contained blocks of code

or commands that can be accessed and used by

programmers. The called procedure will normally

carry out a specific function it was designed to do. Subroutines and functions are examples of procedures.

Declaring general subroutines

So far, we have mainly discussed event driven procedures. Visual Basic also lets the programmer create general procedures that can be called within another procedure (subroutine). The general format of a general purpose subroutine is:

Sub SubroutineName( )

statements

End Sub

Example 5.2

Write a general subroutine that would solve y = xn , given that the values of n are integers.

Solution

Sub Power of Number ( )

Dim x As Single, y As Single, n As Integer y = x^n

Print y

End Sub

Explanation

The above general subroutine is given the name PowerofNumber. To call the subroutine in another procedure such as an event procedure, simply use the call statement. For example, to call the subroutine in the cmdCalculate _Click event procedure, type:

Call PowerofNumber () or Power Of Number ()

The code is executed once the command button for the cmdCalculate click event procedure is clicked.

Project 5.3

Consider a subroutine that will determine the largest of two numbers. Use the code listing below to create a proj ect that can be used to determine the lagest value once the user clicks a command button.

Sub Largest ( )

Dim Larger As Integer, x As Integer, y As Integer

If (x>y) Then

Larger = x

Print (“The larger number is: “,x)

Else If (x<y) Then

Larger = y

Print (‘The larger number is “,y)

Else

       Print(“Both numbers are equal”)

   End If

 End If

End Sub

To create the project, proceed as follows:

  1. Open a new project and save it as LargerNumber.vbp. Save the form as LargerofTwo.frm. Set the objects properties for the three labels (Tabe 5.11) and design the interface as shown in Figure 5.13.

Table 5.11

Control Properties Settings
Labell Name

Caption

lblLarger

Larger between

Label 2 Name

Caption

lblx

x

Label 3 Name

Caption

 

y

Text! ,2,3 Name

Text

txtLarger, txtx, txty

(blank)

Command 1 Name

Caption

cmdExit

Exit

Command2 Name

Caption

cmdCompare

Compare

 

Double click the Calculate and Exit buttons and add the codes as shown:

 

Option Explicit

Dim x As Single, y As Single

Private sub cmdCompareXY- Click ()

X = Val (txtX Text)

Y = Val (txt Y. Text)

        call Largest                  ‘calls a procedure named Largest that

End Sub                                      passes the values of x and ythe

                                                          procedure.

  1. Create a general subroutine called Largest and write the code listing below:

Sub Largest ( )

Dim Larger As Single

If (x > y) Then

Larger = x

txtLarger = x

ElseIf (x < y) Then

Larger = y

txtLarger. Text = y

Else

txtLarger. Text = “The numbers are equal” End If

End Sub

Private Sub cmdExit Click()

End                                                 ‘code for the  exit button

End Sub

This code will appear as shown in Figure 5.14. The call statement in the cmdCalculate makes the Largest Sub procedure to be executed once the End sub is encountered, the control is returned back to the next statement often the procedure call.­

 

  1. Click the run button and enter a value in the text box labelled X and the other in Y. Figure 5.15 shows that the value of Y i.e. 50 is larger than that of X.

Creating menus, message and dialog boxes Menus enable the users to quickly select commands while dialog boxes enable the user to enter values and make selections when working with the computer.

Drop down menus

Drop down menus are the most common menus found in applications. When a menu is selected, a drop down list of commands is displayed.

For example to create a menu bar with the menu items File, Edit and Format with commands for each menu item as shown in the Table 5.12 below.

Table 5.12

Menu File Edit Format
Commands open

Save as

Exit

copy

Cut

Paste

font

Background

Cells

Proceed as follows:

  1. Click the Menu editor command on the toolbar. Alternatively, from Tools click the Menu Editor command. The menu editor window opens.
  2. Under caption, type the word File. This is the screen name of the menu item.
  3. In the Name box enter mnuFile. This is the name that will be used to refer to the File item when coding.
  4. Under Shortcut, select a shortcut key combination. This is optional.
  5. Click Insert button and notice that the cursor moves to the next line.
  6. Type Open in the Caption box and mnuFileOpen in the Name box.
  7. Click the flush right button to insert four dots to the left of Open i.e.

File

………. Open

This means that Open is an item of the File menu. Repeat steps 1 to 4 for all the items then click the OK button. Your complete set up should appear as shown in Figure 5.16 below.

  1. Click OK to close the menu Editor window and go to form design. You will notice that your form now has a menu bar at the top as shown in Figure 5.17 below. Clicking the File menu displays a list of the options that you defined.

It is now possible to activate the menu commands by adding code in their event procedures. To do this, simply click a menu option while in design view and the code window opens in which you can add its code.

 Message boxes

A message box is a special type of dialog box used to display a message to the user. To display a message box, use the syntax:

MsgBox “Message string”, Button/icon, “Title bar Caption”.

For Example: MsgBox(“Drive not Ready. Retry?”, vbRetryCancel + vbQuestion, “Drive Error”)

Displays a message box (Figure 5.18) that tells user that the drive is not ready. Note the Retry and Cancel buttons, the Question mark in the dialog box and “Drive Error” on the Title bar.

Table 5.13 outlines some of the buttons/icons used in Visual Basic

Table 5.13

button Constant
OK vbOKonly
Critical message icon vbCritical
Critical query icon vbQuestion
Warning message icon vbExclamation
Information message icon vbInformation

Dialog boxes

A dialog box enables the user to have a “dialog” with the computer i.e. to exchange information with the computer. You have seen these many times when you try to open or save a file; a dialog will always pop up asking you to fill or select some options. A dialog box is a special purpose form. It is usually accessed when a menu item is selected. Most dialog boxes have common controls like option buttons, list boxes and command buttons.

Simple dialog boxes

Visual Basic enables the user to create forms that can be used as dialog boxes. However, they are secondary to the primary form that is used to access them. Such a form is referred to as a modal form. This means that the form remains on top of the active form until the user clicks the OK or cancel button. To add a modal form to your project, use the Load form command. For example, if the name of the form is Form3 then the Load Form3 command will display the form into the current project. To stop the form from executing, use the unload command i.e. Unload Form3.

In most cases, a form that is loaded may not even be visible in the project window. To make it visible, simply use the Show method. Remember that a method carries out actions on objects. For example to display Form 3, use the syntax Form3.Show. To show the form as modal, use Fonn3.Show l or Form3.Show vbModal.

Project 5.4

Open a project on which you created the menu bar and do the following:

  1. From the project menu click Addform then click New from the Add Form dialog box.
  2. Select dialog A form with two command buttons ie Ok and Cancel is added to your project. Notice in the Project Explorer window that a new form called Form2 is placed hierarchically below the first form.

Change the form caption and name appropriately.

  1. From your main form file menu click the Open command.
  2. In the menuFileOpen code window that opens add the code as shown in Figure 5.19.
  3. Close the code editor window and run project. Notice that when you click File then Open the dialog box you created is displayed on top of Form 1 (Figure 5.20). Because of the Show 1 method, you cannot access the main form until you click ok or cancel button on the dialog box.

Directory list box

You can also add a directory list box on a form. To do this, proceed as follows:

  1. In the Project Explorer window, double click Form2 to open it in design view.
  2. Double click the DirListBox on the toolbar to place it on the form.
  3. Run the project and select the Open command from the File menu, you will be able to browse all the directories on your computer using the dialog box that you just created.(Figure 5.21).

Common dialog box control

Microsoft common dialog control is a component used to add dialog’ boxes such as Save As and Open onto a form. The common dialog control I is not available on the toolbox unless it is added. To add it, click Project then Components. The components dialog box as shown in Figure 5.22 will appear. Select the option Microsoft common dialog control as shown, then click the Apply button. Close the components dialog and check your toolbox for the new icon called common dialog.

Project 5.5

Using the common dialog box control, create a project that can be used to display the open and save As dialog boxes. To create the project, proceed as follows:

  1. On the form, create a menu bar with menu items File, Edit and Format and two command buttons with captions open and save as shown in Figure 5.23.
  2. Right click the common dialog control on your form to display its properties window. Set the name property e.g. commonDiagl.
  3. Double click Open from the File menu or the Open Command button on the design form then add the statement below between the Private sub and End sub.

CommonDiagl.ShowOpen

  1. Double click the mnuSaveAs or the Save Command and type the code CommonDiag I. Show Save

Save the project and run the form. Notice that if you click the Open command or button when the form is running, the Open dialog box opens as shown in Figure 5.24.

In the same way a Print dialog box can be called by adding the following to a menu or button event: CommonDiag 1.ShowPrint

Other dialog boxes supported by common dialog box are Show Color

and Show Font.

List boxes and combo boxes

List boxes and combo boxes are used to display a list of items the user can select from.

List boxes

A list box enables the user to select an item from a list of entries. Selecting an item on a list during runtime causes the value of the selected item to be assigned to the ListIndex property. The ListIndex is an integer with a range of 0 to n-I where the second item corresponds to index 1. Items can be added to a list using the AddItem method or using the list function.

Project 5.6

Create a project that leads a list of items into a list box when the form is loaded.

To create the project, proceed as follows:

  1. Place the list box on the form and then drag it to the expected size.
  2. Double click the Form and add the following code window in the Form_Load() event procedure:

Listl.List(O) = “Nairobi”                    Listl.Addltem(“Nairobi”)

Listl.List(1) = “Kisumu”                     Listl.Addltem(“Kisumu”)

Listl.List(2) = “Mombasa”                 Listl.Addltem(“Mombasa ”)

Listl.List(3) = “Bungoma”         or      Listl.Addltem(“Bungoma”)

Listl.List(4) = “Nyeri”               Listl.Addltem (“Nyeri”)

Listl.List(5) = “Nakuru”            Listl.Addltem(“Nakuru ”)

Alternatively you can add the items in the list property of the list box. To do this, display the list properties window, in the list property, enter the items. To move to the next line, during item entry, press Ctrl + Enter. Figure 5.25 shows the item list assigned to a list box using the properties window.

  1. Run the project. You will notice that the list builds dynamically as you click in the box when the form is running.

NB: The ListIndex and ListCount properties are very important. ListIndex can be used in CASE selection construct to point to the most recently selected list entry. For example,

Select Case Listlndex

       Case 0           ‘first entry in list corresponds to 0, not 1

“Nairobi”

Case 1

“Kisumu

Case 2

       “Mombasa”

Case 3

……….. ”          ..

End Select

On the contrary, the ListCount property shows the number of entries in a list and it starts from 1, not O.

Combo boxes

As opposed to a list box, a combo box allows the user not only to select but also make a new entry into the list of items.

Project 5.7

Create a project that loads a list items into a combo box when the form is loaded.

To create the project, proceed as follows:

  1. Place the combo box control on the form.
  2. Open its properties window and in the List property add the following items:

“Red”

“Yellow”

“Green”

“White”

“Black”

  1. Run the project to load the form. Click the down arrow on the combo box to view the list of item as shown in Figure 5.26 below.

Visual Basic data structures

Apart from using simple data structures such as Integer, Single, Double etc., Visual Basic comes with features that allow the programmer to create complex data structures. These include arrays, records and files.

Arrays

An array is a data structure that stores several data items of the same type hence it is called a homogeneous data structure. Table 5.14 shows how data of type Integer is stored in an array.

The array has cells. The numbers 0 to 5 are called array indices or subscripts. In Visual Basic, an array starts from cell 0 as shown in the table.

Declaring an array

To declare an array, use the statement Dim ArrayName (n), where n stands for the number of elements in the array. For example:

Dim Scores (4) is an array that holds five elements. An element is an item in an array that can be accessed using the array variable name and a subscript. For example, consider an array of 5 elements called Scores. To display the 4th element use:

Score4 = scores(3)

Print Score4

The value stored in the variable score4 is printed on the form. To store a value in an array variable, use the statement ArrayVariable (index). For example, to assign a numeric constant 90 to the fifth cell use

scores( 4) = 90

This statement will assign a value 90 in the cell 4th of the array.

NB: If the array was very large and you wish to read or enter values in it,

it would be very tedious entering a value cell by cell i.e. Score(O) = 10

Score( 1) = 20

Score(3) =30

Score(n) = x

To avoid this, the For.. loop can be used. Remember that this loop is used where the number of iterations are pre-determined hence its suitability for use with arrays.

For example, if you wish to request the user to enter six values in array named A, the following FOR loop can be used:

Dim A(5) As Integer

Dim index As Integer

Private Sub EnterArrayValues()

       For index= 0 To 5

       A(ifldex) = Val(Textl.Text)

       Next index

End Sub

Notice that the array is declared this time outside the Subroutine in order to make it a general procedure that can be accessed by other subroutines. To Display values of the array on the form the following statement can be used:

Private Sub Display Array Values ()

 For index = 0 To 5

Text2. Text= Str(A(index))

Next index

End Sub

Two dimensional arrays

A two dimensional array is a data structure in which elements are arranged in rows and columns. Two subscripts are used to identify an item. For example Dim Score(2,4) means that the element is in the 3rd row, 5th column. This is because the array was declared to start from row 0 column 0 same as Dim Score (0 to 2, 0 to 4). To manipulate elements stored in a

two dimensional array, we use the nested For.. Next or For Each.. Next

loop as shown below:

Dim iRow As Integer

Dim jColumn As Integer

For iRow = 1 T03

     For jColumn = 1 to 5

 Score(iRow, jColumn)

      Next jColumn

Next iRow

 

Records

A record comprises of a series of related data items (fields). They differ from arrays in that whereas all elements in an array are of the same data type, data items in a record may differ in type. For example, when you want to store a students record with the fields Name, Registration number and date of birth in a file as a unit, then you can define a record that

would hold all this data items in one structure. For example the following declaration will create StudentDetails record:

Type StudentDetai/s

Name As String 15

RegistrationNumber As String 10

DateofBirth As Date

…………        .

End Type

The first line in the type declaration gives the name of the data structure i.e. StudentDetails. The other three lines define fields in the data type. Notice that each field has its own data type and that the string data types are of fixed length. The last line i.e. End type marks the end of the record definition. A record is defined in a standard code module or the General Declaration section of a form module.

It is not possible to access the elements of a data structure directly. This is why after defining data structure, you must declare a variable that will be used to hold the records. This is done by declaring a variable whose type is the data structure. The general format of such a declaration is:

Dim RecordVariablelVame As RecordName

For example, the StudentDetails record can be declared as a variable using the statement:

Dim Student As StudentDetails

This means that the variable Student is of type StudentDetails. To access an element in the structure, the following syntax have to be used:

RecordVariable.FieldName e.g. Student.Name

Array of records

An set of user-defined data types can be stored and accessed in arrays too. Consider the record declared below:

Type Student

RegistrationNumber As Integer Name As String * 20

End Type

An array of the student record can then be declared as follows: Dim StudentArray(39) As Student

This means that the array can store fourty student records. To access a field in the array of records use the statement: Arrayname(index).FieldName e.g. StudentArray(20).Name will return the name of the student whose record is in the 20th cell.

Data files

A file can be defined as a storage location of related information or records. Visual Basic recognises three types of files namely: text (sequential) files, random access files and binary files. Sequential files consist of data made of text strings. A random access file contains data records each of equal length with each record having a unique identifier. Remember that a record is a data structure that has several related data items about a particular entity. In random files, a record can be accessed directly by specifying its corresponding record number or location. A binary file contains information expressed as a stream of bytes. Such files store graphics, sound files or compiled code.

Sequential files

A sequential file stores data items one after another in sequence. The keywords used in manipulating a sequential file include Output, Input, Write, Read and Close. Table 5.15 gives a summary of the keywords used in manipulating sequential files.

Table 5.15

Keyword Description
Output Data is written on the storage media at the beginning

of the file, overwriting any existing data.

Input Opens the sequential file for reading if data is to be

retrieved.

Append Data is added at the end of the last item in a file.
Write Data is output into the sequential file.
Read Reads data from the sequential file.  
Close Terminates the processing of a disk file and writes

the last partially filled buffer onto the storage media.

 
EOF(Filenumber) End of File marker. When reading data from a disk,

EOF tells the program when to stop. Attempt to read

past the EOF causes a run-time error.

 

The following statements are very important when working with this type of files:

( a) Open filename For Output As #n

(b) Open filename For Input As #n

(c) Close #n

where n refers to the file number (n is usually an integer value).

Manipulating data in a sequential file

To manipulate a text file you can use the tools that corne with Visual Basic such as the common dialog box. For example, to open a file for input, use the showOpen method of the common dialog box. The skeletal code below shows that when the user enters the name of the file in the open dialog box, it is assigned to a string variable TargetFile ready for input.

Private Sub mnuOpen _Click

Dim TargetFile As String, x As Integer, item As string

 CommonDialogl.ShowOpen

TargetFile= CommonDialog I.FileName

Open TargetFile For Input As #1

x= 0

Do Until EOF(I)

input # 1, item

‘Write a code that reads each data

‘Item from the TargetFile until the end-of file-condition is true

x=x+l

Loop

Close #1

End Sub

 

Likewise, you can write data to a new file by operating it in Output mode as shown in the skeletal code listing below. Note that the file number used is #2 to avoid overwriting the first file.

Private Sub mnuSaveAs Click

Dim NewFile As String, x As Integer, item As string

CommonDialog 1.ShowSave

NewFile= CommonDialogl.FileName

Open NewFile For Output As #2

n= 30

For x = 1 TO n

‘Write a code that writes each data item into the NewFile Next x

Close #2

End Sub

When you write to a file, all the original data in the file is lost. To avoid losing the content of a file open it in Append mode as shown in the skeletal code below.

Private Sub mnuSaveAs Click

Dim TargetFile As String, x As Integer, n As Integer

CommonDialog 1.ShowSave

TargetFile= CommonDialog.FileName

Open TargetFile For Append As #1

n= 20

For x = 1 TO n

‘write each data item at the end of an existing file Next x

Close #1

End Sub

Project 5.8

Using Visual Basic programming, develop a simple sequential file processing program that would read data from a file called ReaderFile.txt and write the contents to another file called Receive. txt . The system should be menu driven. The project should use the Open and Save as dialog boxes to access the two files on the disk.

To create the project, proceed as follows:

  1. Create a new project and save the default fonn as sequentialForm. Save the project as SequentialFiles. vbp
  2. Create a File menu having menu commands as shown in Figure 5.27 below: i.e. Click the tools then menu editor command.
  3. Place the Common dialog control, a combo box and a label on the form.
  4. Double click the form then add the code listing below.

Private Sub Form_Load()

Form I. Caption = “Text File I”

Labell. Caption = “Learning to work with text files”

mnuSave As. Enabled = False

Combo 1. Text = ” ”

End Sub

  1. Double click the Open command and type the code below:

Private Sub mnuOpen Click()

Dim TargetFile As String, Item As String

Dim x As Integer

CommonDialog I.Filter = “Text files (*. txt)/*. txt” ‘open only text files CommonDialog1.ShowOpen

TargetFile = CommonDialog1.FileName

Open TargetFile For Input As #1

x= 0

Do Until EOF(1)

Input #1, Item

ComboI.List(x) = Item  ‘Assign items to the list property of combo box

ComboI.Tag = x ‘Assign the index x to the tag property that represent the number of items read from the file.

x= x+ 1

Loop

Combo 1. Text = “Contents”

Combo I.Locked = True

mnuSave As.Enabled = True     ‘enable command after file open

Close #1

End Sub

Private Sub mnuSave _As Click()

Dim NewTargetFile As String

Dim x As Integer, m As Integer

CommonDialogI.Filter = “Textfiles (*.txt)/*.txt”

CommonDialog I.ShowSave

NewTargetFile = CommonDialogI.FileName

Open NewTargetFile For Output As #2

n = Val (Combo 1. Tag)              ‘Assign the value of the tag to n

For x = 0 To n

Print #2, ComboI.List(x)

Next x

Close #2

End Sub

 

Explanations

1.on running the program, a form is displayed on which is a combo box and a file menu.

  1. On clicking the open command in the File menu, the open dialog box is displayed from which the user can select or type the file name.The file is assigned to a variable TargetFile.
  2. Minimise the Visual Basic IDE Window and start a text editor program such as Notepad. In the window, write the text: we are the world.
  3. After saving the text file, close the program and now return to your project. Click File then Open on your running project. In the Open dialog box, locate your text file and open it. Notice now that the words “We are the World” are displayed in the Combo box as shown in Figure 5.28. You can now use the Save_As command to save the file elsewhere with another name.

NB: If we alter the text and separate the words in the sentence with commas or quotes each word will be read into the computer separately. In such a case the words will be displayed in a drop down list in the combo box.

  1. The reason why the text is displayed in the combo box is because we used the Print statement for output and directed the output to the combo box. However, to write the content into the file, use the Write #n statement instead of Print #n.

Project 5.9

Laura, a proprietor of Laura Refreshment Cafe has requested you to create a program that stores her products in a sequential file. The data entry form should display beverages in a combo box while juice flavours should be displayed in a list box. These two controls are populated with data stored in a sequential file. Using a command button, the user should be able to add more beverages in the combo box.

To create the project, proceed as follows:

  1. Create a new project with one form and add appropriate controls on the form as shown in Figure 5.29.

 

  1. Display each control properties window and set the properties of each control such as:­

(a) Name and caption of add beverages command button.

(b) A combo box with items such as Tea, Coffee, Cocoa, Beans etc.

(c) A List box with items such as Orange, Passim)., Mango etc.

(d) A menu bar with File and Edit Menus. The commands in the

File menu include Save and Exit while those in the Edit menu includes Delete an item, Clear the list and add an item

3, Write a code for each event procedure as shown by the listing below.

(a) Double click the Add Beverages command button and type the code below:

Option Explicit

Dim mbUnsaved As Boolean

Private Sub cmdAddBevarage Click()

‘Add new Beverage If cboBeverages.Text <> “” Then

       With cboBeverages

       .Add/tem cboBeverages

       .Text= “”

End With

mbUnsaved = True

Else

MsgBox “Enter the name of Beverage”, vbExclamation, “Missing Data”

End If cboBeverages.SetFocus

End Sub

 

(b) Double click the form to open the code editor window and enter the code listing below:

      Private Sub Form_Load()                .

‘Load the list

Dim stBeverages As String

On Error GoTo HandleErrors ‘Turn on the error handling routine

Open “a:BevFile.Dat” For Input As #1

Do Until EOF(1)

Input #1, stBeverages

      cboBeverages.AddItem stBeverages

Loop

Close #1

Form Load exit:

Exit Sub

HandleErrors:

                                    ‘The code below raises any type of error encountered during the file open operation

Dim iResponse As Integer

Select Case Err.Number

Case 53, 76 ‘ Invalid path or file name

  iResponse = MsgBox(“Create a new file?”, vbYesNo + vb Question, “File Not Found”) Display a message box

If iResponse = vb Yes Then

  Resume form_Load _exit ‘Exit the Procedure

Else

  mnuFileExit Click ‘Exit the program

End If

Case 71

iResponse = MsgBox(”Drive not Ready. Retry?”, .

vbRetryCancel + vbQuestion, “Drive Error”) display a message box

If iResponse = vbRetry Then

  Resume

Else

       mnuFileExit Click ‘Exit the program

End If

 

Case Else

.

Err.Raise Err display a message for any other type of error

End Select

End Sub

Private Sub mnuEditAdd Click()

‘Add a new beverage list cmdAddBevarage _Click

End Sub

(c) Double click the Add command from Edit menu and type the code below:

Private Sub mnuEditdelete Click()

‘Delete a selected item If cboBeverages.ListIndex <> -1 Then

cboBeverages.RemoveItem cboBeverages.ListIndex

mbUnsaved = True

Else

MsgBox “Select an item you want to delete”, vbInformation, – I

“Select an Item”

 End If

End Sub

(d) Double click the Exit command in the file menu and type the code listing below:

Private Sub mnuFileExit Click()

‘Exit from the program and save changes

Dim iResponse As Integer

If mbUnsaved = True Then

iResponse = MsgBox(“Save changes?”,vb YesNo + vbQuestion, “Save Changes”)

If iResponse = vb Yes Then

mnuFileSave Click

End If

End If

End

End Sub

(e) Double click the save command in the file menu and type the code listing below:

Private Sub mnuFileSave Click()

‘Save the combo box content into a sequential file

Dim iIndex As Integer

Dim iMax As Integer

Open “a:BevFile.Dat” For Output As #1

iMax = cboBeverages.ListCount – 1

For iIndex = 0 To iMax

Write #1, cboBeverages.List(iIndex)

Next iIndex

Close #1

mbUnsaved = False

End Sub

Explanation

  1. On running the program, the form is loaded and you can add a beverage item in the combo box as shown in Figure 5.30.

 

  1. When the user clicks the save command on the File menu, the Beverages list is saved on the floppy disk. You can view the items using Microsoft Windows NotePad or any Text Editor. Below is a list of items saved in the file BevFile.Dat.

“Chocolate”

       “Tea”

       “Coffee”

       ”Milo”

       “Plain Coffee”

“Soya”      I

“Cocoa”

  1. On error statement have been used in the Form Load procedure. This code ensures that the program does not halt in case the user forgets to insert a floppy disk. On error statement and the err objects are therefore used to trap run-time errors. The correct syntax of the On Error statement is: I

On Error GoTo LineLabel e.g. On Error GoTo ErrorHandler I

The lineLabel refers to the error handling code that begins with a line label such as HandleErrors:

The resume statement tells the program to resume back to the statement that caused the error. Resume Next option can also be used I to tells the program to execute the statement immediately following the line that caused the error.

The Err object holds information about an error that has occurred. The name of the application that caused the error is stored in the source property. The Number property contains error numbers ranging from 0 to 65,535. Examples of Err.Number are shown in Table 5.16.

Table 5.16

Number Err.Description Number Err.Description
7 Out of memory 58 File already Exists
11 Division by zero 61 Disk full
13 Type mismatch  71 Disk not ready
53 File not found 76 Path not found

You can use the raise method to set the error code, effectively turning on an error. This is necessary if the error that has occurred is not the one of the anticipated. The statement Err.Raise Err in the form load procedure therefore tells the program to display an error message for any other unhandled error.

Random access files

Random access files consists of fixed length records each assigned a unique identification number. The keywords use in random file manipulation are summarised in Table 5.17 below:

                                                  Table 5.17

Keyword Description
Random Records can be input or output and accessed in any,

order.

Get # FileNumber Reads data from a random disk file and place data

into the record name variable. The variable must

be a user-defined data type e.g. a record variable.

Put # FileNumber Writes the content of a record on the disk. The record

number determines the relative location within the

file. If the record number is omitted, the record will

be placed in the next location from the last Get or

Put operation.

Len Len refers to the length of a single record. For

example Len(EmployeeRecord) retUrns the size of

the employeeRecord in bytes.

LOF(FileNumber) Rather than using EOF, LOF is used to find the end

of a random file. This function returns the size of

the file in bytes. FileNumber is the file number

from the currently open file. To determine the highest

record number, divide the return value of LOF by

the size of one record. For Example

 Number _of_records = LOF(1)/

Len (EmployeeRecord).

Seek(FileNumber) Returns the current location of the file pointer. For

a sequential file the current byte number is returned

while in randof!! files, seek returns the position of

the next record. For example

NextRecord = seek (1)

To open a random file for input or output use the syntax: The following statement:

Open filename For Random As #n Len = record length

Reading records from a random file

Records are read one at a time using the following procedure

Get #n,record number, data item

Sometimes, you may ignore the record number but instead put two commas I.e.

Get #n”data item

The computer in this case will look for the record following the last’Get operation.

Writing to a random file

The statement below can be used to write records to a file.

Put #n,record number, data item or put #n”data item

The latter statement would write a record next to the last Put operation.

NB: Random files will accept data records only.

Project 5.10

You have been requested to develop a program that can store employees contact details. Create a project that has two forms namely the main form and a data form that can be used to manipulate employees records and store them in a random file. The forms should have the following controls:

Main form

  1. A List box where the names of the employees are displayed.
  2. Command buttons for Adding, Deleting, Updating and browsing employee’s records.
  3. Menu bar with File and View menus.

Data form

  1. Labels and Text boxes for LastName, FirstName, Address and City/Town
  2. Navigation buttons i.e. First, Next, Previous and Last.
  3. OK and Cancel buttons.

To create the project, proceed as follows:

  1. Create a project that has two forms namely the main form and a data form and add controls as shown in Figure 5.31 (a) and (b).

 

  1. Open the properties window and set the properties of each control such as:­

(a) Name and caption of each form controls

(b) Command buttons for both forms.

(c) A combo box with items such as Tea, Coffee, Cocoa Soya etc.

  1. Create a menu bar with File and View menus. The File menu should include at least one command e.g. Exit while the View menu should have at least View Records command.
  2. Write codes for each event procedure and standard procedure as shown by the listing below.

      Standard(Global) Procedure

Enter this code in a standard module code editor window.

Option Explicit

Type employeesRecord               ‘Define a record with five fields.

stLastName As String * 15

stFirstName As String * 15

stAddress As String * 10

stCity As String * 12

       stDeleted As String * 1

End Type                                     ‘End of record defination

Public gEmployee As employeesRecord

Public gstFileAction As String

Main form Procedures

Private Sub cmdAddNew Click()

‘Display a blank record in order to add a new employee

gstFileAction = “A”

frmFile.Show vbModal

End Sub

Private Sub cmdBrowse Click()

‘Browse the File

    gstFileAction = “B”

frmFile.Show vbModal End Sub

Private Sub cmddelete Click()

    ‘Delete an employee from the list

    iflstEmployee.ListIndex <> -1 Then

    gstFileAction = “D”

    frmFile.Show vbModal

    Else

    MsgBox “Select a record to be deleted!”, vbOKOnly + vbInformation, “Delete!”

End if

End Sub

Private Sub cmdUpdate ClickO

 ‘Update an employee record

    iflstEmployee.ListIndex <> -1 Then

    gstFileAction = “u”

    frmFile.Show vbModal

    Else

    MsgBox “Select a record to update”, vbOKOnly + vbInformation, “Update”

End if

End Sub

Private Sub Form_Load()

‘Store the details of the list box in a random file

 Dim iIndex As Integer

Dim iResponse As Integer

On Error GoTo HandleErrors

Open “a:Employee.Dat” For Random As #1 Len = Len(gEmployee)

 IfLOF(l) / Len (gEmployee) > 0 Then ‘Iffile not empty

  For ilndex = 1 To LOF(1) / Len (gEmployee)

  Get #1, ilndex, gEmployee

  If gEmployee.stDeleted <> “Y” Then

  AddtoList (iIndex)

  End If

  Next iIndex

Else

iResponse = MsgBox(“Create a new file?”, vb YesNo + vb Question, “File Not Found”)

If iResponse = vbNo Then

mnuFileExit _Click ‘Exit the program

End If

End If

form_Load exit:

Exit Sub

HandleErrors:

If Err.Number = 71 Then

     iResponse = MsgBox(“Drive not Ready. Retry?”, vbRetryCancel + vb Question, “Drive Error”)

     If iResponse = vbReiry Then

     Resume

        Else

        mnuFileExit _Click ‘Exit the program

       End If

Else

On Error GoTo 0 ‘Turn error trap off

End If

End Sub

Private Sub mnuFileExit Click()

 ‘End the program

Close #1

End

End Sub

Public Sub AddtoList(iIndex As Integer)

‘Add an employee in the list box

Dim stName As String

stName = Trim(gEmployee.stLastName) & “, “& gEmployee.stFirstName

IstEmployee.AddItem stName

IstEmployee.ItemData(lstEmployee.NewIndex) = iIndex

End Sub

Private Sub mnu ViewEmployee Click()

    ‘Display the employees file

    gstFileAction = “B”      ‘Browse

frmFile.Show vbModal

 End Sub

Data form Procedures

Option Explicit

Dim miIndex As Integer

Private Sub cmdCancel- Click()

    ‘Switch to the main form

frmFile.Hide

 End Sub

Private Sub DisplayRecords()

    ‘Display record fields in the form text controls

     txtLastName. Text = gEmployee.stLastName

      txtFirstName. Text = gEmployee.stFirstName

    txtAddress. Text = gEmployee.stAddress

    txtCity. Text = gEmployee.stCity

End Sub

Private Sub SaveRecords()

gEmployee.stLastName = txtLastName. Text

gEmployee.stFirstName = txtFirstName. Text

gEmployee.stAddress = txtAddress. Text

gEmployee.stCity = txtCity. Text

End Sub

Private Sub cmdFirst Click()

     ‘Display the first record

    frmMain!lstEmployee.ListIndex = 0

    Readrecords

End Sub

Private Sub cmdNext_Click()

    ‘Display the next record

    If frmMain! IstEmployee.ListIndex <

   frmMain!lstEmployee.ListCount -1 Then

   jrmMain!lstEmployee.Listlndex = jrmMain!lstEmployee.Listlndex + 1

   Readrecords

   Else

   cmdFirst Click

   End If

End Sub

Private Sub cmdLast Click()

     ‘Display the last record

   frmMainflstEmployee.Listlndex =

   frmMain!lstEmployee.ListCount -1

Readrecords

End sub

Private Sub cmdOK Click()

‘Select the action to perform then click OK

Dim stName As String

Select Case gstFileAction

Case “A”

         milndex = LOF(1) / Len (gEmployee) + 1

        gEmployee.stDeleted = “N”

        SaveRecords

        WriteRecords

        frmMain.AddtoList (milndex)

frmMain!lstEmployee.ListIndex = frmMain!lstEmployee.Newlndex

Case “D”

miIndex =frmMain!lstEmplayee.ItemData(frmMain!lstEmployeeListIndex)

gEmployee.stDeleted = “Y”

WriteRecords

frmMain!lstEmployee.RemoveltemfrmMain! IstEmployee.Listlndex

  Case “U”

       SaveRecords

milndex= frmMain!lstEmployee.ItemData(frmMain!lstEmplayeeListIndex)

WriteRecords

 frmMain!lstEmployee.Removeltem frmMain! IstEmployee.Listlndex

frmMain.AddtoList (miIndex)

Case “B”

End Select

frmFile.Hide ‘Return to the main form

End Sub

Private Sub ClearTextBoxes()

    txtLastName.Text = “”

    txtFirstName. Text = “”

    txtAddress. Text = “”

txtCity. Text = “”

End Sub

    Private Sub NavigationEnabled()

   cmdFirst.Enabled = True

   cmdNext.Enabled = True

    cmdPrevious.Enabled = True

cmdLast.Enabled = True End Sub

Private Sub NavigationDisabled()

cmdFirst.Enabled = False

cmdNext.Enabled = False

cmdPrevious.Enabled = False

cmdLast.Enabled = False

End Sub

Private Sub cmdPrevious Click()

If frmMain!lstEmployee.Listlndex < 1 Then

cmdLast Click

    Else

    frmMain!lstEmployee.ListIndex = .frmMain!lstEmployee.ListIndex – 1

    Readrecords

End If

End Sub

Private Sub Readrecords()

    ‘Read data from a random file

    miIndex= frmMain!lstEmployee.itemData(frmMain!lstEmployee.ListIndex}

   Get #1, miIndex, gEmployee

DisplayRecords

End Sub

 Private Sub WriteRecords()

   ‘Save data to a disk

Put #1, miIndex, gEmployee

End Sub

   Private Sub Form_Activate()

   ‘Activate the data form and set focus to the LastName field

   Select Case gstFileAction

Case ”A”

ClearTextBoxes

NavigationDisabled

txtLastName.SetFocus

Case “D”

Readrecords

NavigationDisabled

Case “U”

 Readrecords

NavigationEnabled

Case “B”

  NavigationEnabled

  cmdFirst Click

  End Select

End Sub

Explanation

  1. On running the program, the main form is loaded that shows a list of employees as shown in Figure 5.32.
  2. When the user clicks the Add New button, a blank data form is displayed with focus set on the LastName text box. (See Figure 5.33). If you add a new employee record and then click the OK button, the employee’s name is added into the list box and saved into random file.
  3. On clicking the Delete, Update or Browse buttons, the records are displayed on the form for the user to perform the appropriate action. Figure 5.34 (a) shows a record that is just about to be deleted while Figure 5.34 (b) shows the main form display after deleting the selected record.

Binary files

A binary file is used to store graphics, sound or compiled files. Applications that make use of binary files are complicated and beyond the scope of this book. However, to manipulate a binary file the keywords Put, Get, EOF, Len, LOF, Seek, Loc (pointer location) are used.

To open a binary file we use the statement; OpenfileName for Binary As #n. Below is a skeletal listing of a Visual Basic program that read and writes the same data into a binary file.

Private Sub mnuCopy Click()

Dim FileLength As Integer, Index As Integer

Dim FileName As String

Dim FileByteO As Byte

FileName =……… ‘find out the file name

Open FileName For Binary As #1

FileLength = LOF(1)

ReDim FileByte(Filelength)

For index = 1 To FileLength                    ‘read the file

 Get # 1 “FileByte(Index)                        ‘the second field has no value

Next index

For Index = 1 To FileLength

Put #1, Index, FileByte(Index)                ‘the second field has a value

 Next Index

Close #1

End Sub

Explanation

The Get #n statement start reading the first byte in the file and then reads each successive byte until the end of the file. The Put #n statement has a value hence it will overwrite the contents of the file it is writing to. To avoid this, leave index empty so that the write operation simply appends the records to the end of the file.

  1. What is an array subscript?
  2. Differentiate between a record and’ an array.
  3. Differentiate between a sequential file and a random access file.
  4. State the function of each of the following file manipulation commands.

(a) Input #1 (b) Get#n (c) Put #n (d) Qpen

  1. Differentiate between (a) EOF and LOF
  2. An employee file has the following fields: First name, Second name, Employment number, Date of employment and Date of birth. Using the type declaration, create a user defined data type that will store ail this data for one employee.
  3. Declare a variable that can store the user defined data type in question 6 above.
  4. Assuming the user wants to access the DateofEmployment field in a record variable’employeeDetails, write a statement that can do this.

Linking Visual Basic forms to a database

In Visual Basic, it is possible to access an existing database. This is done by adding data controls on a form. For example assuming a database called library exists and it has a table called students, to access this table in Visual Basic, proceed as follows:

  1. Open your Visual Basic project. Click the Project Explorer icon on the toolbar to display the explorer window. Double click Form1(Form1.frm) in the project explorer window to display the blank form as in Figure 5.35.
  2. If the properties window is not displayed, right click the form then select Properties from the shortcut menu. Change the properties as indicated below:
Property Value
Name Studentform
Caption Enter or View Students
  1. Double click the Data control tool on the toolbox. A data control is placed on the form automatically. Now move and resize it as you wish. Change the following properties of the data control:
Property Value
Name StudentFormData
Caption ViewStudents
Connect Access 98/2000/2003 (Depends on the database

type and version installed in your computer).

DatabaseN am Provide the full directory path to the database

by clicking the… icon then browse to the database.

RecordSourct STUDENTS (select this table from a drop down

menu)

The last two properties link your form to the database that has the data source records. For example, in our case, the data source is the students table found in the Library database.

  1. To view the fields of each record, add text boxes in the form that would accommodate all fields from each record. To link each text to the data source, double click the text box and then change the following properties for each text box.

Textbox 1

Property value
Name Studentregistrationtxt
Data source Studentformdata (remember this is the name you gave to the data control on the form)
Datafield Registration number (select from dropdown menu)
Text Reg no

 

Textbox 2

Property Value
Name Studentfirstnametxt
DataSource Studentformdata
Datafield First name

Repeat the above for all the available textboxes then save the project. Figure 5.36 (a) shows three textboxes linked to the STUDENT table.

  1. Run the project to display the content of the underlying table. Figure 5.36 (b) shows the sample record from the underlying table. Notice that the fields on the form do not have labels. It is the high time we add labels and command buttons.

To add labels proceed as follows:

(a) Double click the label control on the toolbox. A label is placed on the form.

(b) Drag the label and place it above the Registration number field            on the form.

(c) Change the label name and caption appropriately.

(d) Set the labels properties appropriately as shown in the table below.

Labels 1

Name Caption
Labelregno Registration no:
LabelFirstName First name:
LabelSecName Second name:

To add a command button proceed as follows:

(a) Double click the button from the toolbox.

(b) Change the name and caption of the command button.

Name Caption
EnterNewRecord New record
SaveNewRecord Save

I

(c) Change the buttons properties as indicated below

Your form should now look as shown in Figure 5.37.

 

Project 5.11

Create a new project called SchoolLibrary that can be used to access a database called Biblio.mdb that conies with Visual Basic.

To create the project, proceed as follows:

  1. Start Microsoft Access and locate for the Biblio database. The path to the database may be C:IProgram FileslMicrosoft Visual

 Studio\VB98\Biblio. mdb. Figure 5.39 shows the tables in the database.

  1. Click the queries tab and open All Titles in design view. Note that the query has four fields namely: Titles, ISBN, Author and Year Published.
  2. Create a project that contains one form, large enough to hold the four fields. Click on the Data Control tool and draw a data control at the bottom of the form as shown in Figure 5.40.
  3. Add labels and text boxes that will be used as bound controls for the fields from the query. Set Name, Caption and Text Properties for the labels and textboxes accordingly.
  4. Change the Data control properties as follows:

(a) Set the Name property to datBooks and Caption to Display a book.

(b) Make sure the connect property is set to Access.

(c) Click the DatabaseName settings button (…) to display database name dialog box. From the dialog box, locate the database called Biblio using the path C: IProgram Files \Microsoft Visual

Studio\VB98\Biblio.mdb

  1. Scroll to RecordSource property and click the down arrow. From the list of tables and queries displayed, select All Titles. Figure 5.41 shows a section of the Data control properties settings.
  2. Click each textbox and set the DataFie1d appropriately. For example, click the txtISBN, then from the DataFie1d property, select ISBN.
  3. Write the code listed below for the command Close button.

Private sub cmdClose click()

, Exit from the project

End

End Sub

  1. Save the form as books and the project as VBBiblio. Figure 5.42 shows the complete form in design view.
  2. Run the project. Notice that the form bound controls are populated with data from the All Titles query as shown in Figure 5.43. Click the navigation arrows of the data control to view other records.

Using the Recordset object to manipulate a database

When you set the record source property of a data control to the name of a table or query, you are defining a new object called a Recordset. The recordset has its own set of properties and methods which you can use to move from record to record. Below is a summary of some methods used with Recordset.

Method                                                       Description

AddNew               Clears the bound controls for a new record entry

Update              Beginning of file. Updates the underlying table or query by adding the new field.

Delete               End of file. Used for deleting the currently selected record.

BOF                 Used to check for the beginning of a file.

EOF                 Used to test the end of a file.

Move             Used to navigate through the database. Other Move methods includes MoveNext, MoveLast and MovePrevious

Project 5.12

Using the Recordset object, modify the VBBiblio project by adding three more command buttons namely Add New, Save and Delete on the Books form. Using the three buttons, the user should be able to add a new record, automatically update the underlying data source or delete a selected record.

To create the project, proceed as follows:

  1. Open VBBiblio project and add the three buttons as shown in Figure5.44.
  2. Write the code for each of the buttons. Below is a sample code for the modified VBBiblio project.

Private Sub cmdAdd Click()

‘Add a new record

If cmdAdd. Caption = “&Add New” Then

datBooks.Recordset.AddNew ‘Clear the fields for new entry

txtISBN.SetFocus

DisableNavigations

cmdSave.Enabled = True ‘Enable the save button

cmdAdd.Caption = “&Cancel” ‘Allow a cancel option

Else

datBooks.Recordset. Cancel Update

EnableNavigations

cmdSave.Enabled = False

cmdAdd.Caption = “&Add New”

End If

End Sub

Private Sub DisableNavigations()

 cmdFirst.Enabled = False

cmdNext.Enabled = False

cmdPrevious.Enabled = False

cmdLast.Enabled = False

cmdDelete.Enabled = False

End Sub

Private Sub EnableNavigations()

 cmdFirst.Enabled = True

cmdNext.Enabled = True

cmdPrevious.Enabled = True

cmdLast.Enabled = True

cmdDelete.Enabled = True

End Sub

Private Sub

cmdClose Click()       ‘Close the form

End

End Sub

Private Sub cmdDelete Click()          ‘Delete the selected record

  With datBooks.Recordset

  .Delete

  .MoveNext

If.EOF Then

      .MovePrevious

    If.BOF Then

    MsgBox The record set is empty”, vblnformation, “No

  Records”

      End If

    End If

End With End Sub Private Sub cmdFirst Click()

    ‘Move to the first record

    datBooks.Recordset.MoveFirst

End Sub

Private Sub cmdLast Click()

   ‘Move to the Last record

datBooks.Recordset

.MoveLast

End Sub

Private Sub cmdNext_Click()    ‘Move to the next record

With datBooks.Recordset

.MoveNext

    If.EOF Then

    .MoveFirst

End If

End With

End Sub

Private Sub cmdPrevious Click()   ‘Move to the previous record

With datBooks.Recordset

.MovePrevious

     If.BOF Then

        .MoveLast

    End If

  End With

End Sub

Private Sub cmdSave Click()

‘Save the current record

datBooks.Recordset.Update

EnableNavigations

cmdSave.Enabled = False

cmdAdd.Caption = “&Add New”

End Sub

Explanation

On running the program, the form is loaded that shows each record from All Titles query. The user can navigate to view other records using the navigation buttons. This project also allows the user to add, save and delete a record as shown in Figure 5.45.

 

Practical activity 5.3

Using an existing database called Hospital, write a project that access the employees Table that has at least five fields i.e. First Name, LastName, Dateofbirth, Department and Status. The project form should have Navigation, Add, save and Delete buttons

  1. Assuming you have a database containing the following fields:

(a) Names

(b) Contact numbers

(c) Town

Explain how you can access these fields in the database from Visual Basic environment.

  1. Explain the difference between a data control and a databound control.
  2. Explain how you would link up a form in Visual Basic to a database called Biblio that comes with VisualBasic located in a folder VB98. VB98 is accessed through the path C:/Program File/Microsoft Visual Studio VB98.

Creating a Visual Basic executable file

You can convert your project into an executable (.EXE) file that can be run on Microsoft Windows desktop. The EXE file contains the information for all your project files including the form files and modules. After you create the EXE file, the other files are not affected. However anytime you make changes to the source code, you must recreate the EXE file.

To create the EXE file Proceed as follows:

  1. From the:Filemenu, select Make xxxx.exewhere xxxx stands for the currently open project.
  2. In the make project dialog box, type the name of your executable file then click OK.
  3. You can then place your EXE file in the programs menu or on the desktop.

Conclusion

Therefore with knowledge in Visual Basic programming and system development discussed in Chapter 4, you can be able to create versatile information systems. This being an introduction there is a lot in Visual Basic programming. You can learn more on Visual Basic Programming from Microsoft Visual studio on-line help known as MSDN collection.

 

APPENDIX I

Introduction to database design

Most systems will involve storage of data in a database and then having different users accessing the data in their own unique way. Sometimes the data may be stored in a file that is created on the disk. This appendix demonstrates how to construct system files or tables, using Microsoft Access and finally automate your database to make it a fully-pledged application.

Remember that in system analysis, we said that for a library system, we will need to store data about books and students as entities of the system. These records have to be stored in a database. These entities have a relationship which needs to be defined during database design. For example, because a student can borrow many books, this can be represented in the database design as a “one-to-many relationship”. Figure App. 1.1 represents this relationship using a simple relationship diagram. The line that joins the two entities divides into three on the Books side to show that one student can borrow many books.

Other relationships that are possible between entities are “one-to-one” and “many-to-many”. In Figure App. 1.2. for example, one student can only have one registration number.

Student has a Registration

number

 

Fig. App. 1.2: One-to-one relationship

Similarly, in a school environment, one course unit can be done by many

students and one student can do many course units (Figure App. 1.3).

Course unit can be

\taken by /

Student
/               \  

Fig. App. 1.3: Many-to-many relationship

 

It is therefore possible to have a database design that has all the three entity relationships. However, when designing your database, best practice demands one to develop one-to-many relationships between entities. The diagram that shows the logical relationship between data entities is called the entity relationship diagram (ERD).

Defining attributes

Attributes need to be identified for each of the entities identified in the entity relationship diagram. The attributes will become the fields of the database table that will store data for each entity. A complete set of

attributes in a table will form a record. Each entity will have one attribute that will hold a unique value for each of the records entered in the database. This unique attribute is called the key attribute or the primary key (PK). To create a relationship between two tables, include the primary key of one table in the second table i.e. create a field in the second table that has the same data type as the primary key of the first table. This field created in the second table is called the foreign key (FK). Table App. 1.1 shows the attributes for two entities in a library management system.

Table App. 1.1

Entities and their attributes
Entity Attribute
Books Book number (PK)

ISBN number

Author

Publisher

Purchase price

Student Registration number

First name

Middle name.

Class

Stream

A careful study of the two tables will reveal that some of the attributes need to be separated and used to develop other entities. This is because they will encourage duplicate storage of data in the database. For example, one “Publisher” may have published many books. Hence, if you have one hundred different books in the library done by the same publisher, you will have to enter the same name a hundred times in the database!

 

Table App.I.2 shows this anomaly. This data duplication is not allowed and hence we can create an entity called “Publishers” that will have the name of a publisher entered once in the database then allow you to keep on referring to it when the need arises. The process of trying to eliminate storage of duplicate values in the database is called normalization. It is governed by some rules that are outside the scope of this book. However, the simple principle is that you try to separate off any attributes that may eventually carry repeating values in the database to form their own tables.

 

Table App. 1.2

ISBN Title Publisher Date

published

Date

issued

Return

date

09625063xx

08765432xx

GIS Data

Form 1 Geog.

Jets book

Jets book

2000

2001

1/3/2005

3/4/2005

8/3/2005

10/4/2005

To avoid repetition, Table App. 1.2 can be broken down into two, one for the books and another for publishers as shown in Table App. 1.3.

Table App. 1.3

Entities and their attributes
Entity Attribute
Book Book Number (PK)

ISBN

Title.

Date of publication.

Year published

Purchase price

Student number (FK)

Publisher ID (FK)

Student Registration number (PK).

First name.

Middle name.

Class

Stream

Publisher Publisher ID (PK).

Publisher name.

Address

City

Phone number

 

The entity relationship diagram of the system will now look as shown in Figure App. lA.

This entity relationship diagram shows that a student can borrow many books. Likewise a publisher can publish many books.

Creating the database

This section presumes that you have covered the Form 2 syllabus on databases. To create a database, proceed as follows:

  1. From the start menu, select Microsoft Access. The dialog box of Figure.App. 1.5 appears.

 

Fig.App. 1.5:

  1. Select BlankAccess Database option then click the OK button. The File New Database dialog box appears. In the File name box, type the name of the new database to be created as shown in Figure App. 1.6.

­

 

 

  1. In the Save in box select the folder where you want to save your database, then click the Create Database button.
  2. The database as shown in Figure App. 1.7 appears on the screen allowing you to create the various tables.

 

Defining a file/table structure

To define the file/table structure:

  1. Click the Tables tab in the database window and then double click Create table in Design view command.
  2. Create the three tables i.e. students, books and publisher using the attributes defined earlier in Table App. 1.3. Figure App. 1.8 shows a students table in design view.

 

Setting the primary key and foreign key

A primary key can be defined as a unique field that identifies each record in a database table. This means that the primary key in a database table holds unique values for each record and cannot accept duplicate, null or empty values. For example, if one student has the registration number 2000, no other student can be assigned the same number and a value must be entered into the field before proceeding to another record.

On the other hand, the foreign key is included as an attribute of an entity in order to create a relationship with another entity in the database. For example, the Student registration number field in the BOOKS entity creates a relationship between the STUDENT entity and the BOOKS entity. The entity with the foreign key is usually on the many side of a relationship. Values in a foreign key field of a table in a database are unique but are allowed to repeat as long as they appear in the primary key of the primary table.

To define table relationships:

  1. From the tools menu, click relationship. Show table dialog box appears as shown in Figure App. 1.9.
  2. Select the tables and click add so that they are displayed on the relationship window.
  3. To create a relationship, drag the primary key of the parent table to the foreign key of the “child” table. For example to create a relationship between Students table and Books table, drag the Fig. App. 1.10: Defining relationships registration number of the students table to the registration number of the books table. Eventually, you will get a relationship such as the one shown in Figure App. 1.10.

 

  1. Enforce referential integrity: Referential integrity governs the nature of records in a “one-to-many relationship”. This means that all foreign keys in the child table must have a matching record in the parent table. Therefore you cannot add a record in the child table if it does not have a related record in the parent table.

Check the ‘Cascade Update Related Fields’ if you want your database to update the child tables once the parent record is updated. This means that if the student’s registration number is changed, all the records in the related tables will automatically be updated. FigureApp. 1.11 shows an edit relationship for the two tables i.e. students and books.

 

Once you have created your database tables and related them accordingly, you can then enter data into the tables using forms which you create. Since database forms design was covered in Form 2 the rest of this appendix illustrates only data entry into the system.

 

Figure App. 1.15 shows a sample report generated from the database showing a summary report indicating which student has which book. The report has been generated from a query that is created using the three related tables.

 

Automating your database application

Once you finish creating the basic database objects i.e. tables, forms, reports and queries, you may wish to automate operations such as data entry, printing reports and making the user interface more user friendly.

In Microsoft Access, some of the tools used to automate a database are:

  1. Switchboard: This is a special purpose form used to automatically access to other database objects such as forms and reports.
  2. Macros: This is a set of one or more actions used to automate commonly performed tasks such as opening and closing forms and printing reports.
  3. Visual Basic for application (VBA) module: The module object in Microsoft Access is a program coding widow for a subset of Visual Basic programming language called Visual Basic for Application (VBA). VBA is similar to Visual Basic only that you cannot create a new program (project) within.

Creating a switchboard To create a switchboard;

  1. From the Tools menu, point to Database utilities then click Switchboard manager.
  2. If no switchboards are available, Microsoft Access will prompt you whether you want to create one. Click Yes.
  3. From the switchboard manager dialog box click Edit.
  4. From the Edit switchboard dialog box, click Edit. The Edit switchboard Item dialog box appears in which you can specify the menu items to be included on the switchboard. Figure App. 1.16 shows an illustration of switchboard editing dialog box for the library system.
  5. In the “Edit switchboard item” text box, enter the name of the menu. From the command list box, select the object to be accessed e.g.

“Open form in Edit mode”. In the Form list box, select the name of the object e.g. StudentsForm user click OK.

  1. Finally click Close buttons to close the switchboard dialog boxes. Figure App. 1.17 below shows a switchboard for the library management system.

Creating macros

To create a macro in Microsoft Access:

  1. Click the Macros tab then New. The macros design grid appears.
  2.  In the macros design window, Action column, click the down arrow to select an action that you want to be executed directly every time you run the macro. For example, scroll downwards and click OpenForm.
  3. In the lower part of the macro design window specify the action arguments. For example, for the action OpenForm select the name of the form e.g. switchboard, view mode.

Creating Visual Basic for application (VBA) module

Since in chapter 5 we introduced you to Visual Basic programming, you can transfer the same skills to coding using Visual Basic for Application. You will realise that the only difference between the two is that Microsoft Access modules are only limited to particular objects and that you can not create a new project using this. For more on Visual Basic for Application coding, you can get help that comes with Microsoft Access. However, it is important to note that Visual Basic for application is also available as an independent programming language which you can use just like Visual Basic.

There are two approaches for creating VBA codes:

  1. Adding a code to form and report using event procedure. To add a code in this way, open the form or report in design view and then double click the form icon located at the meeting point of the vertical and the horizontal ruler.
  2. From the objects properties list, click the events tab then click the build button from the resulting dialog box, choose Code Builder.

The coding window for the object you chose is displayed as shown in Figure App. 1.18.

Enter the VBA code between the private sub object name event and the end sub.

Securing your database from unauthorised access

There are a number of security options that can be used to set security. However the simplest methods is the use of a password.

To setup a database password in Microsoft Access,

  1. Open the database file in exclusive mode as shown in Figure App. 1.19.
  2. From Tools menu, point to Security then click Set password.
  3. Enter the password in the password text box and re-enter the same password in verify box then click: OK

When a user opens the database, he/she will be prompted to enter the password as show in Figure App. 1.20.

 

Setting up the startup options

You can finally customise your application workplace by specifying the startup options. Start up options lets you customise your database in order to make it more presentable to the users. Such a database will always be starting as an application instead of loading it from Microsoft Access application window.

To set up the start up options for your application, from Tools menu, click<start up then specify the following

  1. Applications title: The title that will appear on the title bar instead of the default Microsoft Access title.
  2. Application icon: You can choose an icon that goes together with your application title.
  3. Menu bar: You can specify the menu options that should appear when running the application.
  4. Display form: Choose the form you want automatically displayed once you start the application e.g. the switchboard.
  5. Uncheck “Display Database Window” to limit the users from viewing the objects created in your database. .

Conclusion

Although this Appendix has tried to open you to a lot of utilities, tools and commands you can use to come up with a fully fledged application, it is important to note that Microsoft Access has a lot of potential which would take hundreds of pages to explain. However, you can use this Appendix to help you explore further on skills and concepts that can help you develop information systems through customisation approach.

 

 

APPENDIX II

Coding schemes

Binary Coded Decimal (BCD)

Decimal number 0 1 2 3 4 5
Binary equivalent 0000 0001 0010 0011 0100 0101
Decimal number 6 7 8 9    
Binary equivalent 0110 0111 1000 1001    

Standard Binary Coded Decimal

Letter Binary Letter Binary Letter Binary Letter Binary
A 11 000 1 H 111 000 0 10011 0 V 010101
B 11 00 10 I 111001 P 100111 W 010110
C 11 00 11 J 100001 Q 10 1000 X 010111
D 110100 K 100010 R 10100 I Y 011000
E 110101 L 100011 S 010010 Z 011 00 1
F 110110 M 100100 T 010011    
G 110111 N 100101 U 010100    

ASCII and EBCDIC

Character 7 -bit ASCII 8-bit EBCDIC
0 0110000 1111 0000
1 0110001 1111 000 1
2 0110010 11110010
3 0110011 11110011
4 0110100 11110100
5 0110101 11110101
6 0110110 11110110
7 0110111 11110111
8 0111000 11111000
9 0111001 11111001
Character 7 -bit ASCII 8-bit EBCDIC  
A 1000001 11000001  
B 1000010 11000010  
C 1000011 11000011  
D 1000100 11000100  
E 1000101 11000101  
F 1000110 11000110  
G 1000111 11000111  
H 1001000 11001000  
I 1001001 11001001  
J 1001110 11010001  
K 1001011 11010010  
L 1001100 11010011  
M 1001101 11010100  
N 1001110 11010101  
0 1001111 11010110  
P 1010000 11010111  
Q 1010001 11011000  
R 1010010 11011001  
S 1010011 11100010  
T 1010100 11100011  
U 1010101 11100100  
V 1010110 11100101  
W 1010111 11100110  
X 1011000 11100111  
Y 1011001 11101000  
Z 1011010 11101001  
Character 7 -bit ASCII 8-bit EBCDIC  
blank 0100000 01000000  
  0101110 01001011  
, 0101100 01101011  
+ 0101011 01001110  
0101010 01100000  
/ 0101111 01011100  
= 0111101 01100001  
( 0101000 01111110  
$ 0100100 01011011  
) 0101001 01011101  

NB: Alphabetic lower case characters have their symbolic representation too but not included in this scheme