The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by aayushbhatta62, 2021-09-23 10:41:04

JBD Computer Studies Book 10

JBD Computer Studies Book 10

Keywords: JBD Publication, JBD Computer Studies, Book 10,Kathmandu, Nepal, aayushbhatta62

Number/Currency Format

Number/Currency format allows numbers to some predefined number formats.
The following table shows the predefined Format property settings for numbers.

Setting Description

General It is the default.

Number Displays number as entered.

Currency Uses thousand separator (e.g., 32,767) and displays negative
numbers enclosed in parentheses (e.g., (31, 015.25) is a
negative number).The amounts are displayed to two
decimal places.

Fixed No rounding off is done. Generally it displays at least one
digit with two decimal places.

Standard This property uses thousand separator with two decimal
places.

Percent This property multiplies value by 100 and appends a
percent sign (e.g., if you enter a value 7 in the field, it will
show 700%). Default is two decimal places.

Scientific This property uses standard scientific notation for
displaying numbers.

The custom Number and Currency formats also use special characters to indicate

how you want the values to appear. The table given in the next page describes
symbols and their effects.

Symbol Effect

. (period) Indicates the decimal point that separates the parts of a
number.

, (comma) Used as the thousands separator.

0 A digit placeholder that displays a digit if one is there or, if
none are there, displays zero.

# A digit placeholder that displays a digit if one is there or, if
none are there, closes up the adjoining digits.

$ Displays a dollar sign.

% Value is multiplied by 100 and a percent sign is added.

JBD
Computer Studies-10 101

Text/Memo Format

There is no standard format for text/memo field. However, following symbols

can be used to create user-defined formats. These symbols can be used to specify

whether a text character is allowed and whether all characters are displayed in

uppercase or lowercase.

Symbol Effect

@ Indicates a character or a space is required

& Indicates a character or a space is optional

< Converts all characters to lowercase

> Converts all characters to uppercase

Logical Format

Access automatically displays a default check box control when you specify a
Yes/No data type. Any format settings you make are ignored with this choice.
Access provides three predefined formats for displaying Yes/No, On/Off or True/
False.

Decimal Places property

The decimal places can either be set to a specific number or to Auto (Default). If
Auto is chosen then numbers appear as specified by the Format property setting.
You can use the Decimal Places property to display numbers differently from the
way specified by the Format property setting. For example, the Currency format
displays only two decimal places ($5.35). To display Currency numbers with four
decimal places (for examples, $5.3523), you must use the Decimal places property.

Input Mask property

An input mask controls the value of a record and sets it in a specific format. An
input mask can do a couple of different things:

• It forces you to enter field values in a pattern such as 999-99-9999 or 123-456-
6777.

• It can fill in constant characters like dash (-) and slash (/) and optionally store
these characters as part of the field value as you do not have to enter them
yourself.

Caption property

The caption property specifies a string to be displayed as the column heading
whenever the field is displayed in Datasheet view. If the field is added to a form,
this value is used as the caption for the label also that is added along with the
field. In a table, the Caption property is used to put spaces in field names that use
mixed case, such as LastName and FirstName.

JBD
102 Computer Studies-10

Default Value property
The default value is used to specify the default value for a field or control i.e., the
value that gets entered automatically in the field at the time of data entry. If you
want to enter a value other than default value, you can overwrite it.
The maximum length for a default value is 255 characters.
The default value is automatically entered in a field or control when a new record
is created. For example, in an address table you might set the default for the City
field to Kathmandu. When users add records to the table, they can either accept
this value or enter the name of a different city.

Validation Rule property
Validation rules specify requirements (change word) for the data entered in the
worksheet. A customized message can be displayed to the user when data that
violates the rule setting is entered. Click the expression builder (”...”) button at
the end of the Validation rule box to write the validation rule.

Validation Text property
Validation text is a customized message that is displayed on user’s screen when
we enter data that does not follow the applied validation rule.

Required property
The Required property specifies whether the field is required to have a value
entered in it. If this property is set to Yes and you attempt to change the field to
be empty, Access displays a message informing you that a value is required in
the field.

Indexed property
The Indexed property field is used to set a field as an index. The Yes (No Duplicates)
setting for the Indexed property indicates that the information in the field will be
indexed for faster searching, and that duplicate values are not allowed.

JBD
Computer Studies-10 103

Add a table
You can add new tables to an existing database by using the commands in the
Tables group on the Create tab.

Create a table, starting in Datasheet view
In Datasheet view, you can enter data immediately and let Access build the table
structure behind the scenes. Field names are assigned numerically (Field1, Field2,
and so on), and Access automatically sets each field’s data type, based on the data
you enter.
• On the Create tab, in the Tables group, click Table.
Access creates the table and selects the first empty cell in the Add New Field

column.
• On the Datasheet tab, in the Fields & Columns group, click New Field. Button

image
Access displays the Field Templates pane, which contains a list of commonly

used field types. If you double-click or drag one of these fields into your
datasheet, Access adds a field by that name and sets its properties to
appropriate values for that type of field. You can change the properties
later, if you want. If you drag the field, you must drag it onto an area of the
datasheet that contains data. A vertical insertion bar appears, showing you
where the field will be placed.
• To add data, begin typing in the first empty cell, or paste data from another
source, as described in the section Copy data from another source into an
Access table.
• To rename a column (field), double-click the column heading, and then type
the new name.
• To move a column, click its heading to select the column, and then drag the
column to the location you want.
You can also select multiple contiguous columns and then drag them to a
new location all at once. To select multiple contiguous columns, click the
column header of the first column, and then, while holding down SHIFT,
click the column header of the last column.

JBD
104 Computer Studies-10

Create a table, starting in Design view
In Design view, you first create the new table’s structure. You then switch to
Datasheet view to enter data, or enter data by using some other method, such as
pasting, or importing.
• On the Create tab, in the Tables group, click Table Design.

• For each field in your table, type a name in the Field Name column, and then
select a data type from the Data Type list.

Note:
If you don’t see the Field Name and Data Type columns, you might be in

Datasheet view instead of Design view. To switch to Design view, right-
click the table in the Navigation Pane, and then click Design View Button
image. Access prompts you for a name for the new table, and then switches
to Design view.
• If you want, you can type a description for each field in the Description
column. The description is then displayed on the status bar when the cursor
is located in that field in Datasheet view. The description is also used as the
status bar text for any controls in a form or report that you create by dragging
the field from the Field List pane, and for any controls that are created for
that field when you use the Form Wizard or Report Wizard.
• After you have added all of your fields, save the table:
• Click the Microsoft Office Button, and then click Save, or press CTRL+S
Button image.
• You can begin typing data in the table at any time by switching to Datasheet
view and clicking in the first empty cell.

JBD
Computer Studies-10 105

Inserting/Deleting Fields
To insert a field between two other fields in the list, click the name of the field that
should be just below the new field and then click the Insert Row button.
Click a row and then click the Delete Row button to delete a field.

Entering a Caption and Default Value for a Field
Caption appears at the top of a field in the table and next to the field on a form.
For example, next to the field named “fname” in which you enter some one’s first
name, you can create a caption that reads “First Name”. Entering a default entry
allows you to set a value for a field that the user can still override. For example,
you can set the default value for a Yes/No field to Yes.
To enter caption and default value, follow these steps:
• In the Table Design window, click the name of the field to format.
• Click the Caption box and enter the text that will be used to label the field on

the form.
• Click the Default Value box and then enter the default value.
• Save the changes to the table design.

Viewing Table
You can view a table by double clicking upon its name in the database window.
A table can be viewed in two different views.
Tables have two views: Design view and Database view. Design view is used to
create and modify the structure of a table. Datasheet view is used to view, add,
delete and edit data in a table.

JBD
106 Computer Studies-10

Defining a Primary Key Field

The primary key of a relational table uniquely
identifies each record in the table. It can either
be a normal attribute that is guaranteed to be
unique (such as Social Security Number in a
table with no more than one record per person)
or it can be generated by the DBMS (such as a
globally unique identifier, or GUID). Primary
keys may consist of a single attribute or multiple
attributes in combination. Imagine we have a
STUDENTS table that contains a record for each
student at a university. The student’s unique
student ID number would be a good choice
for a primary key in the STUDENTS table. The
student’s first and last name would not be a good
choice, as there is always the chance that more
than one student might have the same name.

To define a primary key, follow these steps:

• Click on the field that you want to set as the primary key. An arrow will
appear in the field selector column.

• Select the Primary Key option from the Edit menu. The field will be set as the
primary key, indicated by a small key in the field selector column.

Adding records and entering data

Entering data into tables in Access is similar to entering data in Excel. To work
with records, you’ll have to enter data into cells. If you need help entering data
into records, you may want to review our Excel 2010 Cell Basics lesson.

To add a new record:

There are three ways to add a new record to a table:

• In the Records group on the Home tab, click the New command.

• On the Record Navigation bar at the bottom of the window, click the New
Record button.

• Simply begin typing in the row below your last added record. Occasionally
when you enter information into a record, a window will pop up to tell
you the information you’ve entered is invalid. This means the field you’re
working with has a validation rule, which is a rule about the type of data that
can appear in that field. Click OK, then follow the instructions in the pop-up
window to re-enter your data.

JBD
Computer Studies-10 107

To delete a record:
• Select the entire record by clicking the gray border at the left side of the

record.
• Select the Home tab, and locate the Records group.
• Click the Delete command. The record will be permanently deleted.

The ID numbers assigned to records stay the same even after you delete a
record. For example, if you delete the 34th record in a table, the sequence of
record ID numbers will read “...32, 33, 35, 36...” rather than “...32, 33, 34, 35,
36...”

Record Validation Rules
Record validation rules are enforced whenever you add or edit data, whether
it is through table Datasheet view, a form bound to the table, an append query,
an update query, Visual Basic for Applications code, or by importing data from
another table.
A Field Validation Rule validates a value being entered in a field and a Record
Validation Rule controls when an entire record is saved. Record Validation Rule
can compare values from more than one field. For instance, if we have to make
sure that in Marks table, value of field Marks obtained must be less than or equal
to Maximum Marks field then, we’ll have to create a Record Validation Rule as
this rule has to refer to more than one field.
To create a Record Validation Rule, follow these steps:
• Open a table in Design view.
• Click Properties on the toolbar to display the table’s property sheet.
• In the Validation Rule property box of Table Properties dialog, type the

validation rule. Or click the Build button to create the validation rule using
the Expression Builder.
For example, you could define the validation expression “[RequriedDate] <=

JBD
108 Computer Studies-10

[OrderDate] + 30” to make sure that the data entered into the RequiredDate
field is within 30 days of the date in the OrderDate field.

• In the Validation Text property box, type the message that you want Microsoft
Access to display when the rule is broken.

For example, for the validation expression:
“[RequiredDate] <=[OrderDate] + 30”
You could enter “The required data must be within 30 days of the order

data”.
If you set a validation rule in a table that contains data, Microsoft Access will

ask if you want to apply the new rule to existing data when you save the
table.

Sorting Data
Sorting arranges the records in specific order. Access automatically sorts records
by the value in the primary key field. In Access you can sort data in ascending order
or descending order. The ascending order arranges text values in alphabetical
order (A to Z), date/time values from earliest to latest, and number/currency
values from lowest to highest. Use descending to reverse the order. You cannot
sort on Memo, Hyperlink, or OLE Object fields. You can sort all records in a table
by a single field or you can select adjacent columns and sort by more than one
field. When you select multiple columns to sort, Access sorts records starting with
the column farthest left, then moves to the right across the columns. Access saves
the new sort order with your table data and reapplies it automatically each time
you open the table. To return to the primary key sort order, you must remove the
temporary sort.

• Select a field in the cell you wish to sort by. In this example, we will sort by
customers’ last names.

• Click the Home tab on the Ribbon, and locate the Sort & Filter group.

• Sort the field by selecting the Ascending or Descending command.

Select Ascending to sort text A to Z or to sort numbers from smallest to
largest. We will select this in our example, since we want the last names to be
in A to Z order.

Select Descending to sort text Z to A or to sort numbers from largest to
smallest.

• The table will now be sorted by the selected field.

• To save the new sort, click the Save command on the Quick Access toolbar.

JBD
Computer Studies-10 109

Filtering Records
When you want to see only certain records in your datasheet, subdatasheet, or
form, you can filter out the records you don’t want to see. The filter process screens
the records and lets through only those that meet your criteria. The criteria is a set
of conditions you specify to limit the display to a certain subset of records. This
can save time by focusing your attention on only the records that are important at
the moment. Filtering doesn’t remove the records from the table, it only removes
them from your view of the table.
• Click the drop-down arrow next to the field you would like to filter by. We

will filter by city, as we want to see a list of customers who live in a certain
city.
• A drop-down menu with a checklist will appear. Only checked items will be
included in the filtered results. Use the following options to determine which
items will be included in your filter:
Select and deselect items one at a time by clicking their check boxes. Here, we
will deselect all of the options except for Cary.
Click Select All to include every item in the filter. Clicking Select All a second
time will deselect all items.
Click Blank to set the filter to find only the records with no data in the selected
field.

• Click OK. The filter will be applied. Our customers table now displays only
customers who live in Cary.

JBD
110 Computer Studies-10

MS-Access Query
Query in Access is a way of extracting information from a database in Microsoft
Access. The query usually involves certain criteria or requesting certain data. You
can use queries to:
• view data from multiple tables sorted in a specific order.
• perform many types of calculations on selected groups of records.
• find and display duplicate or unmatched records
• update data, delete records or append new records to a table.
• create a new table with records from one or more tables.

The five types of queries in MS-ACCESS are as follows:
Select query
Select query is the most common type of query. A select query is the query, which
can retrieve data from one or more tables by using the user-specified criteria and
later display the retrieved data in the desired order. A select query can also be
used to group records and calculate sums, counts, averages and other types of
totals.

Parameter query
Parameter query is a query that lets the user retrieve records depending upon the
value specified by the user at runtime. In other words, when a parameter query is
run, it displays its own dialog box wherein user is asked to provide some value(s)
on the basis of which, the records are retrieved from the table.

Crosstab query
Crosstab query displays summarized values (sums, counts and averages) from
one field in a table and groups them by one set of facts listed down the left side
of the datasheet and another set of facts listed across the top of the datasheet. A
crosstab query calculates a sum, average, count, or other type of total for data
that is grouped by two types of information, with one displayed down the left-
hand side of the datasheet and another across the top of the datasheet.

Action query
An action query is a query that makes changes to many records in just one
operation. There are four types of action queries: delete, update, append and
make-table.

JBD
Computer Studies-10 111

Let us talk about each of these types one by one.
Delete query
This type of action query deletes a group of records from one or more tables. For
example, you could use a delete query to remove products that are discontinued
or for which there are no orders. With delete queries, you always delete entire
records, not just selected fields within records.

Update query
This type of action query makes global changes to a group of records in one
of or more tables. For example, you can raise prices by 10 percent for all dairy
products, or you can raise salaries by 5 percent for the people within a certain job
category. With an update query, you can change data in existing tables.

Append query
This type of action query adds a group of records from one or more tables to
the end of one or more tables. For example, suppose that you acquire some new
customers and a database containing a table of information on those customers.
To avoid typing all this information in, you’d like to append it to your Customers
table. Append queries are also helpful for:
Appending fields based on criteria. For example, you might want to append only
the names and addresses of customers with outstanding orders.
Appending records when some of the fields in one table don’t exist in the other
table. For example, in a database, the Customers table has 11 fields. Suppose that
you want to append records from another table that has fields that match 9 of
the 11 fields in the Customer table. An append query will append the data in the
matching fields and ignore the others.

Make-table query
This type of action query creates a new table from all or part of the data in one or
more tables. Make-table queries are helpful for:
Creating a table to export to other MS-Access database. For example, you might
want to create a table that contains several fields from your Employees table, and
then export that table to a database used by your personnel department.
Creating data access pages that display data from a specified point in time.
Making a backup copy of a table.
Creating a history table that contains old records. For example, you could create
a table that stores all your old orders before deleting them from your current
Orders table.

JBD
112 Computer Studies-10

Improving performance of forms, reports, and data access pages based on
multiple-table queries or SQL statements.

SQL query
An SQL query is a query, which is created using an SQL statement. Examples of
SQL-specific queries are the union query (for combining fields from one or more
tables or queries), pass-through query (for sending commands directly to ODBC-
Open Database Connectivity-databases), data-definition query (for creating,
deleting, altering tables or for creating indexes etc.), and sub query (for creating
SQL select queries based upon other SQL select query).
After learning about various types of queries, let us learn to create them. But
before we can actually create queries, we need to learn about relationships.
Because, in order to create queries from multiple tables, there must be a proper
relationship established among them.

To apply a simple one-table query:

• Select the Create tab on the Ribbon, and locate the Queries group.

• Select the Query Design command.

• Access will switch to Query Design view. In the Show Table dialog box that
appears, select the table you would like to run a query on. Click Add, then
click Close. We are running a query about our customers, so we will add the
Customers table.

• The selected table will appear as a small window in the Object Relationship
Pane. In the table window, double-click the field names you would like to
include in your query. They will be added to the Design Grid in the bottom
part of the screen.

• Set the search criteria by clicking on the cell in the Criteria: row of each
field you would like to filter. Typing criteria into more than one field in the
Criteria: row will set your query to include only results that meet all the
criteria. If you want to set multiple criteria but don’t need the records shown
in your results to meet them all, type the first criteria in the Criteria: row and
additional criteria in the Or: row and the rows beneath it.

• After you have set your criteria, run the query by clicking the Run command
on the Query Tools Design tab.

• The query results will be displayed in the query’s Datasheet View, which
looks like a table. If desired, save your query by clicking the Save command
in the Quick Access Toolbar. When prompted to name it, type in the desired
name, then click OK.

JBD
Computer Studies-10 113

To create a multi-table query:
• Select the Query Design Command from the Create tab on the Ribbon.

• In the Show Table dialog box that appears, select each table you would like
to include in your query, then click Add. After you’ve added all of the tables
you want, click Close. When we planned our query, we decided we needed
information from the Customers and Orders table, so we’ll add those.

• The tables will appear in the Object Relationship Pane, which is linked by a
join line. Double-click the thin section of the join line between two tables to
edit its join direction.

• The Join Properties dialog box will appear. Select an option to choose the
direction of your join.

Choose option 2: for a Left to Right join. In our query, the left table is the
Customers table, so choosing this would mean all of the customers who met
our location criteria, whether or not they had placed an order, would be
included in our results. We don’t want to choose this option for our query.
Choose option 3: for a Right to Left query. Since our right table is our Orders
table, selecting this option will let us work with records for all of the orders
and only the customers who’ve placed orders. We’ll choose this option for
our query, since this is exactly the data we want to see.

• In the table windows, double-click the field names you would like to include
in your query. They will be added to the Design Grid in the bottom part of
the screen.

• Set field criteria by entering the desired criteria in the criteria row of each
field.

• After you have set your criteria, run the query by clicking the Run command
on the Query Tools Design tab.

• The query results will be displayed in the query’s Datasheet View, which
looks like a table. If desired, save your query by clicking the Save command
on the Quick Access Toolbar. When prompted to name it, type in the desired
name, then click OK.

JBD
114 Computer Studies-10

Specifying the Criteria

The select queries are used for selecting a group of records from the table based
upon a condition. To do this selection criteria is used. Only those records that
meet this criteria, are selected and displayed. The selection criteria is specified in
Criteria: and or rows in the design grid.

Using Wildcard Patterns

Wildcards (?, *) are special characters that can replace one or more characters.
The most common wildcard operators include:

Wildcard Description

? Replaces a single character.

* Replaces a number of characters.

# Replaces a single digit.

To specify a wildcard pattern, enter the pattern in the Criteria row of the field
column in which you want to search.

Using Operators

Operators are the key to more flexible expressions. Access has several classes
of operators: arithmetic, comparison and logical. The table given below lists the
operators you can use in query criteria expressions.

Arithmetic Operators

Operator Description Example

+ Addition = Total + 3

- Subtraction = Total - 3

* Multiplication = Total * 3

/ Division = Total / 3

\ Integer division = Total \ 3

Mod Modulo division = Total mod 3

JBD
Computer Studies-10 115

Comparison Operators

Operator Description Example

= Equals = pencil

or

= “pencils”

> Greater than > 8/12/09

or
>#8/12/09#

< Less than < 2000

>= Greater than

or equal to >=500

<= Less than

or equal to <=200

<> Not equal to <>”pencil”

Between... Between two Between 500

And values, And 200

inclusive

In Included in a In

set of values(“Nepal”, “India”)

Is Null Field is

empty Is Null

Is Not Field is not

Null empty Is Not Null

“ “ Zero-length

string =” “

Like Matches Like d* or

a pattern Like “d*”

Logical Operators

Operator Description Example
>=10 And
And Both conditions are True <=100
“Books” Or
is True “Pencil”
Not like “A*”
Or Either condition



Not Not True

JBD
116 Computer Studies-10

Sorting queries
Access allows you to apply multiple sorts at once while you’re designing your
query. This allows you to view your data exactly the way you want, every single
time you view it.
A sort that includes more than one sorted field is called a multilevel sort. A
multilevel sort allows you to apply an initial sort, then further organize that data
with additional sorts. For instance, if you had a table full of customers and their
addresses, you might choose to first sort the records by city, then further sort
them alphabetically by last name.
When more than one sort is included in a query, Access reads the sorts from left
to right. This means the leftmost sort will be applied first. In the below example,
then, customers will be sorted first by the City they live in and then by the Zip
Code within that city.
To apply a multilevel sort:
• Open the query, and switch to Design View.
• Locate the field you would like to sort first. In the Sort: row, click the drop-

down arrow to select either an ascending or descending sort.

• Repeat the process in the other fields to add additional sorts. Remember, the
sorts are applied from left to right, so any additional sorts must be applied to
fields located to the right of your primary sort. If necessary, you can rearrange
the fields by clicking a field and dragging it to a new location.

• To apply the sort, click the Run command.
• Your query results will appear with the desired sort.
You can also apply multilevel sorts to tables that don’t have queries applied

to them. On the Home tab on the Ribbon, select the Advanced drop-down
command in the Sort & Filter group. Select Advanced Filter/Sort, and create
the multilevel sort as you normally would. When you’re finished, click the
Toggle Filter command to apply your sort.

JBD
Computer Studies-10 117

Totals queries

Sometimes setting simple criteria won’t give you the results you need, especially
when you’re working with numbers. You may want to see your query results
grouped or counted in some way. Access 2010 offers several options that make
these functions possible. Perhaps the easiest of these is the Totals command.

When you use the Totals function in your query, the data in your fields will be
grouped by value, meaning all items of one type are listed together. For instance,
in a totals query about the items sold at our bakery, each type of item sold would
be listed on a single row, no matter how many times that item had been sold.

Once your records are grouped, you can perform calculations with them. These
calculations include:

• Count, which counts the number of the same items in a field

• Sum, which adds the numbers in that field

• Average, which finds the average of the numbers that occur in that field

• Maximum, which returns the highest value that has been entered in that field

• Minimum, which returns the lowest value that has been entered in that field

• First, which returns the first, or earliest, value that has been entered in that
field

• Last, which returns the last, or most recent, value that has been entered in
that field

To create a totals query:

• Create or open a query you would like to use as a totals query.

• In the Query Design tab, locate the Show/Hide group, then select the Totals
command.

• A row will be added to the table in the Design Grid, with all values in that
row set to Group By. Select the cell in the Total: row of the field you would
like to perform a calculation on, and click the drop-down arrow that appears.

• Select the calculation you would like to be performed in that field. In our
example, we want to add the quantities of products we’ve sold, so we’ll select
the Sum option.

• When you are satisfied with your query design, select the Run command on
the Query Tools Design tab to run the query.

• The query results will be displayed in the query’s Datasheet View, which
looks like a table. If desired, save your query by clicking the Save command
in the Quick Access Toolbar. When prompted to name it, type in the desired
name, then click OK.

JBD
118 Computer Studies-10

Using the Update Query
Update queries makes global changes to a group of records in one of or more
tables. For example, you can raise prices by 10 percent for all dairy products, or
you can raise salaries by 5 percent for the people within a certain job category.
With an update query, you can change data in existing tables.
To perform Update Query, follow these steps:
• Create a query with the tables or queries that include the records you want to

update.
• Click Update Query in query Design View.

• Drag from the field list to the query design grid the fields you want to update
or you want to specify criteria for.

• In the Criteria cell, specify the criteria if necessary. In the Update To cell for
the fields you want to update, type the expression or value.

• To see a list of the records that will be updated, click View on the toolbar.
This list won’t show the new values. To return to query Design view, click
View on the toolbar again. Make any changes you want in Design view. Click
Run on the toolbar to update the records.

Using the Append Query
Append query is a type of action query adds a group of records from one or more
tables to the end of one or more tables. Append queries are also helpful for:
• Appending fields based on criteria.
• Appending records when some of the fields in one table don’t exist in the

other table.
To perform Update Query, follow these steps:
• Create a query that contains the table whose records you want to append to

another table.

JBD
Computer Studies-10 119

• Click Append Query in query Design View. The Append dialog box appears.

In the Table Name box, enter the name of the table you want to append
records to.

• Do one of the following:

If the table is in the currently open database, click Current Database.

If the table is not in the currently open database, click Another Database
and type the path of the database where the table is stored or click Browse
to locate the database. You can also specify a path to a Microsoft FoxPro,
Paradox, or dBASE database, or a connection string to an SQL database.

• Click OK.

• Drag from the field list to the query design grid the fields you want to append
and any fields you want to use for setting criteria.

If all the fields in both tables have the same names, you can just drag the
asterisk (*) to the query design grid.

• If you have a field with an AutoNumber data type, do one of the following:

Add AutoNumber values automatically

Keep the AutoNumber values from the original table

• If the fields you’ve selected have the same name in both tables, Microsoft
Access automatically fills the matching name in the Append To row. If the
fields in the two tables don’t have the same name, in the Append To row,
enter the names of the fields in the table you’re appending to.

• In the Criteria cell for the fields that you have dragged to the grid, type the
criteria on which additions will be made.

• To preview the records that the query will append, click View on the toolbar.
To return to query Design view, click View on the toolbar again. Make any
changes you want in Design view.

• Click Run on the toolbar to add the records.

Using the Delete Query

Delete query is a type of action query that deletes a group of records from one
or more tables. For example, you could use a delete query to remove products
that are discontinued or for which there are no orders. With delete queries, you
always delete entire records, not just selected fields within records.

To perform delete Query, follow these steps:

• Create a new query that contains the “one” table from which you want to
delete records.

JBD
120 Computer Studies-10

• Click Delete Query in query Design View. The Append dialog box appears.
• Drag the asterisk (*) from the field list for the table to the query.
• To specify criteria for deleting records, drag to the design grid the fields on

which you want to set criteria.
Where appears in the Delete cell under this field, as shown in the following

illustration.
• In the Criteria cell for the fields that you have dragged to the grid, type the

criteria.
• Click Run on the toolbar to delete the records.

Understanding Forms
Form is a type of a database object that is primarily used to enter or display data
in a database. You can also use a form as a switchboard that opens other forms
and reports in the database, or as a custom dialog box that accepts user input and
carries out an action based on the input. There are many ways to create a form.
You can create a form from scratch using Form Design View, or you can use the
Form Wizard to provide guided steps for developing a form.
To create a form by using wizard, follow these steps:
• Select the table in the Navigation pane.
• Select the create tab on the Ribbon.
• Click on the form wizard button in the Forms group. Access starts the form

wizard shown in figure.

• Select the table or query for which you want to make the form.

JBD
Computer Studies-10 121

• Highlight the required field and click on > button to transfer the fields to the
selected fields section for creating the Forms.

• Click on the Next button to move over to the next step of the form wizard. In
the next step of the Form Wizard, select the layout of the Form. The Columnar
layout has be selected by default. Click Next to move to the next step of the
Form Wizard.

• In the next step of the Form Wizard, select a style for your form and click on
the Next button.

• On the final screen, give a name to the form.
• Click Finish to create the form object.

Understanding Reports
Report is an effective way of presenting the data stored in a table or query in
the printed format. The Report object allows you to control the way the data is
displayed when it is printed on paper. When you click at the Reports object in the
database window, two options to create a Report are displayed. They are: Create
report by using wizard and Create report in design view.
To create a report by using wizard, follow these steps:
The wizard asks you detailed questions about the record sources, fields, layout,
and format you want and creates a report based on your answers.
• On the Create tab, in the Reports group, click Report Wizard.
• Click the table or query that contains the data you want to base your report

on.

• Follow the instructions in the wizard.
• Click Finish.

JBD
122 Computer Studies-10

C Dompu- ictionary

Database : A collection of data in an organized form.

DBMS : Database Management System, a collection of
programs that enables to store, modify, and extract
information from a database.

Relational Database : A collection of data items organized as a set of tables.

Fields : The columns of the table, containing one type of
information.

Table : Collection of records with one record occupying a
single row.

Recap

• Data are the raw materials of information processing.

• Computer data processing is any process that uses a computer program to
enter data and summarise, analyse or otherwise convert data into usable
information.

• A database is a collection of information that is organized so that it can easily
be accessed, managed and updated.

• A database management system (DBMS), sometimes just called a database
manager, is a program that lets one or more computer users create and access
data in a database.

• Microsoft Access is a relational database management system from Microsoft
which is used to store large amounts of data.

• A table is a collection of related data stored in an organized manner.

• A query is used to filter data from the table based on some conditions.

• A form is a user-friendly way of entering, displaying and editing data stored
in a table.

• Reports are used to present the data stored in tables or queries in a printed
form.

• Pages allows you to create a web page which is connected to an access
database.

• Macros allow you to automate common tasks.

• Modules are used to write programs to create applications.

JBD
Computer Studies-10 123

Review Yourself

1. State whether the following statements are true or false.

a. A database is a collection of information that is organized so that it can
easily be accessed, managed and updated.

b. A table is used to filter data from the table based on some conditions.

c. The Format property is used to specify the data display format for a field
in a table.

d. A Field Validation Rule validates a value being entered in a field and a
Record Validation Rule controls when an entire record is saved.

e. A select query is a query that lets the user retrieve records depending
upon the value specified by the user at runtime.

2. Match the following: Column B
Column A

Database A collection of data in an organized form.

DBMS A collection of programs that enables to store, modify,
and extract information from a database.

Relational Database A collection of data items organized as a set of tables.

Fields The columns of the table, containing one type of
information.

Table Collection of records with one record occupying a
single row.

3. Select the best answer from the list of choices.

a. A(n)_________________is an organized collection of related
information. iii. property

i. object ii. database

b. A field name is used to identify the __________ stored in a field.

i. characters ii. keys iii. data

c. A collection of records for a single subject, such as all of the customer
records, is called __________.

i. Field ii. Record iii. Table

JBD
124 Computer Studies-10

d. Which of the following is not MS-Access database object?

i. Table ii. Form iii. Database



e. A(n)______________ is a question asked of the data contained in a
database.

i. form ii. inquiry iii. query

f. The value of primary key field must not be __________.

i. 0 ii. 1 iii. 2

4. Give the appropriate technical term for the following.

a. A collection of programs that enables to store, modify and extract
information from a database.

b. A field that uniquely identifies a record in a table.

c. Database components that retrieve the data that meets conditions that
you specify.

d. Database components used to easily view, enter and change data directly
in a table.

e. A set of one or more actions that performs a particular operation.

5. Answer the following questions.
a. Define the following terms:
i. Database
ii. Record
iii. Relational Database Management System
b. What is DBMS? What are the advantages and disdavantages of DBMS?
c. What different data types (field types) are available in MS-Access? Also
mention their maximum sizes.
d. What do you mean by ‘default value’ of a field in Access and how can it
be set?
e. What is the importance of Primary key in a table? Can you have multiple
primary keys in a table? Why or Why not?
f. What is a query? What is the significance of queries?
g. What is a form and what are the different ways to create forms in Microsoft
Access?
h. What is a report in Microsoft Access?

JBD
Computer Studies-10 125

Practical Assignments

1. Create a database named Purchases. Design a table using the following field information:

Field Data Type Field Size

Item # Text 4

Name Text 50

Contact Text 50

Address Text 50

City Text 50

State Text 2

Zip Code Text 10

Phone Text 15

a. Make the Item # field the primary key field.

b. Save the table as Vendors.

c. Enter the following records into the table in Datasheet view:

Record 1 Record 2

3527 1723

Kona coffee Decaf Colombian

Fred Wilmington Nancy Young

772 First Street 1124 Mariner Rd.

Seattle Half Moon Bay

WA CA

93210-7214 94019

(206) 555-9090 (650) 555-5689

d. Add the following records into the table in Data Entry:

Record 1 Record 2

7926 1100

Darjeeling tea Coffee filters

Mae Yung Manny Smith

12 Main Street 13990 N. Center Ave.

Pacifica Phoenix

CA AZ

94044-3213 84137-7214

(415) 555-1122 (602) 555-0037

JBD
126 Computer Studies-10

e. Return to Datasheet view and display the records in primary key order.

f. Adjust the column widths appropriately.

g. Edit the record for Item # 7926 to change the four-digit zip code extension
from 3213 to 3322.

h. Edit the record for Item # 1100 to replace the current Contact name with your
name.

i. Preview the table. Print, save and close the table.

2. Open the database on your data disk named Purchases and the table named
Vendors.

a. Remove Item 1723 from the table.

b. Use the Replace command to replace Item #3527 with correct item number,
2575.

c. In Design view, make the Item #, Name required fields. Add a Format
property to the State field to force the data in that field to display in all capital
letters.

d. Add a field before the Name to specify the inventory on hand for each
item:

Field name: # On Hand

Data type: Number

Description: Number of individual units (bags, boxes, etc.) in stock

Field size: Integer

e. Add another field before the Name to specify whether the item is a special
order (not regularly stocked):

Field name: Special Order?

Data type : Text

Description : Is this a special order item?

Field size : 1

Default value : N

Validation rule : Y or N

Validation text : The only valid entry is Y (Yes) or N (no)

f. Return to Datasheet View and update the table by filing in the new fields for
each record.

g. Use the Form Wizard to create a columnar form with the SandStone style
and include all the table fields in their current order. Title the forma. T i t l e
the form Cafe Vendors.

JBD
Computer Studies-10 127

h. Use the new form to add the following purchase items to the table:

Record 1 Record 2

1102 2924

Napkins Coffee mugs

50 12

N Y

Restaurant Supply Central Ceramics

Manny Smith [Your name]

Central Ave. Hayden Road

Phoenix Scottsdale

AZ AZ

84137-7214 85254

(602) 555-0037 (602) 555-1924

i. Preview and print the form for the second new record you added.

3. Open the Purchases database and the Inventory table. Filter the table to
display only those records where the Special Order? Field is Y. Hide the
address columns. Print the filtered data sheet to give to Evan. Unhide the
hidden columns and remove the filter.

a. Use the Query Wizard to create a query based on the Inventory table. Include
all fields except Item # in their current order. Name the query To Be Ordered.
In Design view, enter the criteria to display only those records with an On-
Hand # that is less than 25, and run the query. Review the resulting datasheet.

b. Upon reviewing the datasheet, you realize that it is not in a very useful order.
Also, since Evan typically places orders by phone, the address information is
not really necessary. Return to Design view and do the following:

c. Apply an ascending sort to the Vendor Name column.

d. Delete the four address columns.

e. Move the Vendor Name, Contact, and Phone columns to the left of the
Description column.

f. Run the query and review the resulting data sheet. Since the query now looks
satisfactory enough to create a report from it, close the query window, saving
the changes.



JBD
128 Computer Studies-10

4. Open the Purchases database and the Inventory table. Filter the table to
display only those records where the Special Order? Field is Y. Hide the
address columns. Print the filtered data sheet to give to Evan. Unhide the
hidden columns and remove the filter.

a. Use the Query Wizard to create a query based on the Inventory table. Include
all fields except Item # in their current order. Name the query To Be Ordered.
In Design view, enter the criteria to display only those records with an On-
Hand # that is less than 25, and run the query. Review the resulting datasheet.

b. Upon reviewing the datasheet, you realize that it is not in a very useful order.
Also, since Evan typically places orders by phone, the address information is
not really necessary. Return to Design view and do the following:

c. Apply an ascending sort to the Vendor Name column.

d. Delete the four address columns.

e. Move the Vendor Name, Contact, and Phone columns to the left of the
Description column.

f. Run the query and review the resulting data sheet. Since the query now looks
satisfactory enough to create a report from it, close the query window, saving
the changes.

5. Create a database having a table in design view and perform the task given
below:

Field name Data Type Description

Empno Number Employee’s number

Empname Text Employee’s name

Designation Text Designation of employee

Basic_Pay Number Employee’s basic pay

HRA Number House Rent Allowance

PF Number Provident Fund

a. Set Empno as the primary key.

b. Set the validation rule for Basic_Pay as >10000 and the validation text as
“Basic pay should be greater than 10000”.

c. Enter five records.

d. Calculate 5% tax on Basic_Pay.

e. Create a query to display all the records whose Basic_Pay is more than 20000.

f. Create a query to display all the records whose designation is director.

g. Create an update query to increase the Basic_Pay of all the employees by
10%.

JBD
Computer Studies-10 129

Chapter 9

MODULAR
PROGRAMMING

Objectives

After completing this chapter, you will be able to:
y Define modular programming and explain the advantages of modular programming.
y Explain the types of procedures in QBASIC programming.
y Explain the purpose and syntax of SUB...END SUB.
y Explain the purpose and syntax of FUNCTION...END FUNCTION.
y Identify and compare the two methods of passing arguments to the procedure.
y Explain the scope of variables in QBASIC.

C Ooncept verview

Modular programming is a software
design technique that increases the extent
to which software is composed of separate
parts, called modules. A module is a set of
program statements which, when acting
together, complete a specific task, and is
identified by a name. These modules are
complete, and can be integrated through a
main program.
QBASIC program consists of module-level
code and a number of procedures. The
module-level code is the main program
controlling the computer. Procedures are
separate blocks of statements used by
the module-level code; they can be called
by the module-level code any number of
times.

JBD
130 Computer Studies-10

Modular Programming Defined
Modular programming is the process of subdividing a computer program into
separate sub-programs. A module is a separate software component. It can often
be used in a variety of applications and functions with other components of the
system. Similar functions are grouped in the same unit of programming code and
separate functions are developed as separate units of code so that the code can be
reused by other applications.
QBASIC program consists of module-level code and a number of procedures. The
module-level code is the main program controlling the computer. Procedures are
separate blocks of statements used by the module-level code; they can be called
by the module-level code any number of times.
The modular design offers several benefits, such as:
• Improving the readability of a program, because it is easier to interpret small

blocks of code that perform a particular task.
• Reducing redundancy, because you can use the same module at different

places in the program, without having to write the entire code again.
• Saving time during project development, because you can create a library of

modules that can be reused in numerous programs.
• Modules can be tested independently, thereby shortening the time taken to

get the whole program working.
• Program maintenance becomes easier because the affected modules can be

quickly identified and changed.
• Using a modular approach, different programmers can develop different

program modules independently.

SUB Procedure
SUB procedure is essentially a program within a program designed to perform
a specific task. When using SUB procedures, you are basically breaking down a
program into logical steps. This makes your program code easier to understand
and follow.
The major features of SUB procedures are listed below:
• SUB procedure is a procedure that does not return any value.
• SUB procedure starts with the keyword, SUB, and ends with the keyword,

END SUB.
• SUB procedure does not have a data type.
• SUB procedure cannot be a part of an expression.
• The parameters can be passed by reference or by value.
• All variables and arrays are considered local to the SUB procedure unless

specifically defined as shared using the SHARED statement.

JBD
Computer Studies-10 131

The three important steps to build sub procedure are listed below:

Declaring a SUB procedure
The DECLARE statement is used to declare a SUB procedure. QBASIC automati-
cally generates a DECLARE statement when you save the program having no
declaration statement for the first time.
The syntax for the DECLARE statement is as follows:
DECLARE SUB name (parameterlist)
Where,
name is the name of the sub used in assignment statement and procedure calls.
The name is a valid QBASIC identifier and can be maximum of 40 characters.
parameterlist indicates the number and type of arguments that will be used to
call the procedure.
Example:
DECLARE SUB cube (l!)
Declares a sub procedure cube with a parameter l.

Defining a SUB procedure
The SUB...END SUB statement is a procedure statement that marks the begin-
ning and ending of a subprogram. The syntax is:
SUB name [parameterlist]
[statements]
END SUB
Where,
name is the subprogram name which is used to call the subprogram. The variable
name can be up to 40 characters long.
Statements contain valid QBASIC statements.
parameterlist contains the names of the simple variables and arrays passed to the
SUB when it is called. The variable names are separated by commas.
Example:
SUB cube (l)
area = 6 * l ^ 2
PRINT “Area of a cube”; area
END SUB

JBD
132 Computer Studies-10

Solved ExampleCalling a SUB procedure
When you call a procedure, you must supply values for all the arguments speci-
fied in the procedure’s definition and in the same order. The CALL statement is
used to transfer control to another procedure, a BASIC SUB program. The syntax
is:
CALL name (argument list)
Where,
name is the name of the subprogram that is being invoked. The name can be up
to maximum of characters.
argument list is the data passed to the subprogram’s parameter. The parenthesis
around the argument list are required unless the CALL keyword is omitted. The
syntax is:
name argument list
Example:
CALL cube(l)

DECLARE SUB area (r!)
DECLARE SUB cir (r!)
INPUT “Enter the radius”; r
CALL area(r)
CALL cir(r)
END

REM “Module for area of circle”
SUB area (r)
a = 3.141 * r ^ 2
PRINT “The area is =”; a
END SUB

REM “Module for circumference of
circle”

SUB cir (r)
c = 2 * 3.141 * r
PRINT “The circumference is =”; c
END SUB

JBD
Computer Studies-10 133

Solved ExamplePassing Values to SUB Procedures
SUB procedures have the ability to transfer or pass the value of variables from
Solved Exampleone module to the next through the use of arguments and parameters. This is
handy when you need to send data to a procedure to perform a task that depends
on the data. An argument is placed in parentheses in the CALL statement and
allows a value to be passed from the current module to the calling module. A
parameter is placed in parentheses after a SUB procedure’s name. When the pro-
cedure is called, the value of the argument is sent to the corresponding parameter
that it matches up with the SUB procedure parameter list. That parameter will
then hold the value of the argument for use in the procedure.
When passing arguments, the parameter list and argument list of the procedure
must match in number of arguments and also data types. This means that you
can’t pass a numeric variable to a character string variable, or vice versa. The lists
must match data types. However, the argument name doesn’t have to match the
corresponding parameter name.
Using constant values in the arguments

DECLARE SUB cube (l!)
INPUT “Enter a length”; l
CALL cube(5)
END
SUB cube (l)
area = 6 * l ^ 2
PRINT “Area of a cube”; area
END SUB

Without passing argument

DECLARE SUB area (l!, b!)
INPUT “Enter length of a rectangle”; l
INPUT “Enter breadth of a rectangle”; b
CALL area(l*l, b*b)
END
SUB area (l, b)
a=l*b
PRINT “The area of a rectangle:::”; a
END SUB

JBD
134 Computer Studies-10

Solved ExampleUsing expression in the argument

Solved ExampleDECLARE SUB area ()
CALL area
END
SUB area
INPUT “Enter a radius”; r
a = 3.141 * r ^ 2
PRINT “Area of a circle”; a
END SUB

Using expression in the argument

DECLARE SUB rev (n!)
CLS
INPUT “Enter a number”; n
rev n
END
SUB rev (n)
WHILE n <> 0
r = n MOD 10
s = s * 10 + r
n = n \ 10
WEND
PRINT “Reversed number is “; s
END SUB

JBD
Computer Studies-10 135

Solved ExampleUsing array argument

DECLARE SUB set (n!())
FOR i = 1 TO 10
INPUT “Enter a number”; n(i)
NEXT
CALL set(n())
END
SUB set (n())
FOR j = 1 TO 10
IF n(j) > 0 THEN posi = posi + n(j)
IF n(j) < 0 THEN neg = neg + n(j)
NEXT
PRINT “Sum of positive numbers:::”; posi
PRINT “Sum of negative numbers:::”; neg
END SUB

Argument-Passing Mechanisms
When a procedure is invoked, the program may send values to the procedure.
Such values are called arguments. There are two different methods to pass the
arguments to a procedure. They are: call by reference and call by value.

a. Passing Arguments by Reference
When arguments are passed to a procedure by reference, the called proce-

dure has access to the memory location of the argument variable. The called
procedure can use the memory reference to change the value of the argument
variable. The changed value is then also available to the calling procedure.
This technique is useful when the called procedure needs to indicate its suc-
cess or failure, or to return the output of some calculation within the calling
procedure.

JBD
136 Computer Studies-10

DECLARE SUB rev (n!)Solved Example
INPUT “Enter a number”; n
PRINT “Before calling Sub-program”;n
rev n
PRINT “After calling Sub-program”;n
END
SUB rev ((n))
WHILE n <> 0
r = n MOD 10
s = s * 10 + r
n = n \ 10
WEND
PRINT “Reversed number is “; s
END SUB

b. Passing Arguments by Value
A procedure accepts arguments by value, thus making a copy of the document

available to the called procedure. The called procedure uses this variable for
processing. The changes made to the argument variable in the procedure
reflect in the copy of the variable, while the variable in the calling procedure
remains unchanged.

Solved Example DECLARE SUB rev (n!)
INPUT “Enter a number”; n
PRINT “Before calling Sub-program”;n
rev n
PRINT “After calling Sub-program”;n
END
SUB rev (n)
WHILE n <> 0
r = n MOD 10
s = s * 10 + r
n = n \ 10
WEND
PRINT “Reversed number is “; s
END SUB

JBD
Computer Studies-10 137

FUNCTION Procedure
FUNCTION procedure is used by the programmer to define a new function.
The major features of FUNCTION procedures are listed below:
• A function is a procedure that return a single value to the calling program.
• A function starts with the keyword, FUNCTION, and ends with the keyword,

END FUNCTION.
• The data type is the return value of the function.
• Functions can be a part of an expression.
• FUNCTION procedure can be recursive. A recursive function is one that calls

itself.
• The parameters can be passed by reference or by value.
• All variables within a FUNCTION are local and are initialized to zero or null

before the function begins execution.
The three important steps to build function procedure are listed below:

Declaring a FUNCTION procedure
The DECLARE statement is used to declare a FUNCTION procedure. QBASIC
automatically generates a DECLARE statement when you save the program hav-
ing no declaration statement for the first time.
The syntax for the DECLARE statement is as follows:
DECLARE FUNCTION name (parameterlist)
Where,
name is the name of the user-defined function. The function name is assigned the
return value of the function. Hence, the function name should be of the same data
type similar to the return value.
function name should be of the same data type similar to the return value.
parameterlist indicates the number and type of arguments that will be used to
call the procedure.
Example:
DECLARE FUNCTION area! (b!, h!)
Declares the function procedure area with parameters b and h.

Defining a FUNCTION procedure
The FUNCTION...END FUNCTION statement declares the name, the parameters, and
the code that form the body of a FUNCTION procedure.
FUNCTION name [(parameterlist)]
[statements]
function name = expression
[statements]
END FUNCTION

JBD
138 Computer Studies-10

Where,
name is the name of the function. The name can include a type of identifier to
indicate the type of the result that the function will return.
parameter list is the list of parameters
that the function expects and accepts.
The list is delimited by commas. The parameters are passed by reference, so
any change to a parameter’s value inside the function changes its value in the
calling program. expression is the return value of the function.
Example:
FUNCTION area (b, h)
a=1/2*b*h
area = a
END FUNCTION

Calling a Function
The reference of the function name invokes that function. The function call becomes its
return value and you can assign this value either to a variable or use this variable in an
expression. The syntax for assigning a function to a variable is:
Variable = FunctionName (argument list)
Example:
triangle = area(b, h)

Solved Example DECLARE FUNCTION LENGTH (S$)
REM “Find the total number of words”
CLS
INPUT “Enter the string”; S$
G = LENGTH(S$)
PRINT “Total number of words is =”; G
END
FUNCTION LENGTH (S$)
C=1
FOR I = 1 TO LEN(S$)
IF MID$(S$, I, 1) = “ “ THEN C = C + 1
NEXT
LENGTH = C
END FUNCTION

JBD
Computer Studies-10 139

Solved ExamplePassing Arguments to Function
When a function is invoked, the program may send values to the function.
Such values are called arguments. There are two different methods to pass the
arguments to a function. They are:
• Call by value
• Call by reference

Call by Value
A process of passing value of variables is known as call by value. When arguments
are passed by value, the called function creates a new copy of variable of the
same type as the arguments and copies the arguments values into it. The changes
made to the parameters of the called function have no effect on the variables used
to call the function.

DECLARE FUNCTION palind! (n!)
INPUT “Enter a number”; n
m = palind((n))
IF m = n THEN
PRINT “Number is palindromic”
ELSE
PRINT “Number is not palindromic”
END IF
FUNCTION palind (n)
WHILE n <> 0
r = n MOD 10
s = s * 10 + r
n = n \ 10
WEND
palind = s
END FUNCTION

Call by Reference
A process of passing addresses to a function is known as call by reference. When
arguments are passed by reference, the address of each argument is copied to the
argument of the function. The changes made to the parameter of the function will
effect on the variables used at the calling function because called function can ac-
cess the original variables of the calling function.

JBD
140 Computer Studies-10

DECLARE FUNCTION palind! (n!)Solved Example

INPUT “Enter a number”; n

m=n

IF m = palind(n) THEN

PRINT “Number is palindromic”

ELSE

PRINT “Number is not palindromic”

END IF

FUNCTION palind (n)

WHILE n <> 0

r = n MOD 10

s = s * 10 + r

n = n \ 10

WEND

palind = s

END FUNCTION

Scope of a Variable
The scope of a variable refers to that portion of the program where the variable is
visible (i.e., where it can be manipulated). Two kinds of scope are:
• Local scope
• Global scope

Local Variable
A variable declared as local is one that is visible only within the block of code in
which it appears. It has local scope. In a function, a local variable has meaning
only within that function block. When the function is finished and control is re-
turned back to the part of the program that called it, the local variables no longer
exist.

JBD
Computer Studies-10 141

DECLARE SUB area ()Solved Example
CALL area
ENDSolved Example
SUB area
INPUT “Enter a radius”; r
a = 3.141 * r ^ 2
PRINT “Area:”; a ----> Local variable
END SUB

In the above program, there are two variables named r and a. These two variables
are local variables. These variables are not accessible to other procedures.

Gobal Variable
Global variable is a variable which can be accessed (used or changed) throughout
a computer program and is not confined to a single block. A variable declared in
a COMMON or DIM statement with the SHARED attribute is a global variable
to a module.

a. COMMON statement
The COMMON statement is a non-executable statement that declares vari-

ables as global, so that they can be shared between main program, subpro-
grams and functions. They appear only in the main module. The syntax is:
COMMON [SHARED] variablelist

DECLARE SUB area ()
COMMON SHARED r
INPUT “Enter a radius”; r
CALL area
END
SUB area
a = 3.141 * r ^ 2
PRINT “Area of a circle”; a
END SUB

JBD
142 Computer Studies-10

Solved Exampleb. DIM SHARED statement
The DIM SHARED statement makes the variable accessible to all the modules. It

appears in the main program. The syntax is:
DIM SHARED variable (subscript)

DECLARE FUNCTION small! ()
DECLARE FUNCTION great! ()
DIM SHARED n(10)
FOR i = 1 TO 10
INPUT “Enter number”; n(i)
NEXT
diff = great - small
PRINT “The Difference is:::”; diff
END
FUNCTION great
max = n(1)
FOR j = 2 TO 10
IF n(j) > max THEN max = n(j)
NEXT
great = max
END FUNCTION
FUNCTION small
min = n(1)
FOR j = 2 TO 10
IF n(j) < min THEN min = n(j)
NEXT
small = min
END FUNCTION

JBD
Computer Studies-10 143

Hands on
Problem

1. Write a sub-program cost(l,b,h,c) to find the cost of painting the four walls of a room.
Solution:
DECLARE SUB cost(l,b,h,c)
INPUT “Enter the length of the room”;l
INPUT “Enter the breadth of the room”;b
INPUT “Enter the height of the room”;h
INPUT “Enter the cost of painting per unit area”; c
Call cost(l,b,h,c)
END
SUB cost (l,b,h,c)
LET area = 2 * h * (l + b)
LET total = c * area
PRINT “Total cost of painting:”; total
END SUB

2. Write a sub procedure pattern ( ) to generate the following pattern.
1
121
12321
1234321
123454321
Solution:
DECLARE SUB pattern ()
CALL pattern
END
SUB pattern
DEFDBL A
a=1
FOR i = 1 TO 5
PRINT a * a
a = a * 10 + 1
NEXT
END SUB

JBD
144 Computer Studies-10

3. Write a sub-program prime () to find prime numbers from 1 to 100.
Solution:
DECLARE SUB prime ()
CALL prime
END
SUB prime
CLS
FOR j = 2 TO 100
FOR k = 2 TO j - 1
IF j MOD k = 0 THEN GOTO last
NEXT
PRINT j;
last:
NEXT
END SUB

4. Write a sub procedure ARM (n, s) to input a number and check whether it is armstrong or
not.

Solution:
DECLARE SUB arm (n!, s!)
INPUT “Enter a number”; n
m=n
CALL arm(n, s)
IF m = s THEN
PRINT m; “ is an armstrong number”
ELSE
PRINT m; “ is not an armstrong number”
END IF
END
SUB arm (n, s)
WHILE n <> 0
r = n MOD 10
s = s + r ^ 3
n = n \ 10
WEND
END SUB

JBD
Computer Studies-10 145

5. Write a sub procedure hston ( ) to print 7, 22, 11, 34, 17, 52, 26, 13, 40, 20 without passing
parameter..

Solution:
DECLARE SUB hston ()
CALL hston
END
SUB hston
a=7
FOR i = 1 TO 10
PRINT a
IF a MOD 2 = 0 THEN

a=a/2
ELSE

a=a*3+1
END IF
NEXT
END SUB

6. Palindrome words are those which spell the same from both the sides. Write a BASIC
program using SUB procedure PALINDROME (w$, n$) to check whether input word is a
palindrome or not

Solution:
DECLARE SUB palind (w$, n$)
INPUT “Enter a string”; w$
CALL palind(w$, n$)
IF w$ = n$ THEN

PRINT w$; “is a palindromic word”
ELSE

PRINT w$; “ is a not a palindromic word”
END IF
SUB palind (w$, n$)
FOR i = LEN(w$) TO 1 STEP -1
n$ = n$ + MID$(w$, i, 1)
NEXT
END SUB

JBD
146 Computer Studies-10

7. Write a sub procedure caps (s$) to input a string and print the alternate caracters in capital
letters.(Hint: If your input is “kathmandu” then the output should be “KaThMaNdU”).

Solution:
DECLARE SUB caps (s$)
INPUT “Enter a string”; s$
CALL caps(s$)
END
SUB caps (s$)
FOR i = 1 TO LEN(s$)

c$ = MID$(s$, i, 1)
IF i MOD 2 = 1 THEN
w$ = w$ + UCASE$(c$)
ELSE
w$ = w$ + LCASE$(c$)
END IF
NEXT
PRINT “Alternate capital letters=”; w$
END SUB

8. Write a sub procedure pattern ( ) to generate the following pattern:

1

22

333

4 4 4 4

5 5 5 5 5

Solution:

DECLARE SUB pattern ()

CALL pattern

END

SUB pattern

FOR i = 1 TO 5

LOCATE i, 40 - i

FOR j = 1 TO i * 2 - 1

PRINT USING “#”; i;

NEXT

PRINT

NEXT

JBD
Computer Studies-10 147

9. Write a sub procedure even (n!()) to input any ten numbers into an array and find the sum of
even numbers only.

Solution:
DECLARE SUB even (n!())
DIM n(10)
CLS
FOR = 1 TO 10
INPUT n(i)
NEXT
CALL even(n())
END
SUB even (n())
s=0
FOR i = 1 TO 10
r = n(i) MOD 2
IF r = 0 THEN

s = s + n(i)
END IF
NEXT
PRINT “sum=”; s
END SUB

10. Write a program to declare a user defined function using FUNCTION...END FUNCTION to
print the area of a triangle by using expression method. The area of a triangle is given by
the formula:

area = 1/2 x base x height
Solution:
DECLARE FUNCTION area! (b!, h!)
INPUT “Enter a base of a triangle:::”; b
INPUT “Enter a height of a triangle:::”; h
triangle = area(b, h)
PRINT “Area of a triangle=”; triangle
END
FUNCTION area (b, h)
a=1/2*b*h
area = a
END FUNCTION

JBD
148 Computer Studies-10

11. Write a function procedure to read the length, breadth and height of a box. Calculate the
volume and surface area of a box.

(Hint: vol = lbh and sa = 2(lb+bh+hl))
Solution:
DECLARE FUNCTION vol! (l!, b!, h!)
DECLARE FUNCTION tsa! (l!, b!, h!)
INPUT “Enter a length:::”; l
INPUT “Enter a breadth:::”; b
INPUT “Enter a height:::”; h
PRINT “Volume of a box”; vol(l, b, h)
PRINT “surface area of a box”; tsa(l, b, h)
END
FUNCTION tsa (l, b, h)
t = 2 * (l * b + b * h + h * l)
tsa = t
END FUNCTION
FUNCTION vol (l, b, h)
v=l*b*h
vol = v
END FUNCTION

12. Write a program using FUNCTION...END FUNCTION series! (i!) to generate the series
1,8,27,64,125.

Solution:
DECLARE FUNCTION series! (i!)
FOR i = 1 TO 5
PRINT series(i)
NEXT
END
FUNCTION series (i)
s=i^3
series = s
END FUNCTION

JBD
Computer Studies-10 149

13. Write a program to declare a user defined function palind! (n!) using FUNCTION...END
FUNCTION to input a number and check whether it is a palindrome or not.

Solution:
DECLARE FUNCTION palind! (n!)
INPUT “Enter a number”; n
m=n
IF m = palind(n) THEN

PRINT “Number is palindromic”
ELSE

PRINT “Number is not palindromic”
END IF
FUNCTION palind (n)
WHILE n <> 0
r = n MOD 10
s = s * 10 + r
n = n \ 10
WEND
palind = s
END FUNCTION

14. Write a function procedure palind$ (s$) to input a string and check whether a supplied string
is palindrome or not.

Solution:
DECLARE FUNCTION palind$ (s$)
INPUT “Enter a string”; s$
IF s$ = palind$(s$) THEN

PRINT “palindromic string”
ELSE
PRINT “not palindromic string”
END IF
END
FUNCTION palind$ (s$)
FOR i = LEN(s$) TO 1 STEP -1
a$ = a$ + MID$(s$, i, 1)
NEXT
palind$ = a$
END FUNCTION

JBD
150 Computer Studies-10


Click to View FlipBook Version