You are on page 1of 98

LBYEC71

Laboratory
Manual
Students Information Sheet
Subject: ___________________ Section: ___________ Schedule: ___________

Tri-Academic Year: __________ Professor: __________________________

Personal:

Name: _______________________________________________________

Degree Program: ____________________________________________

Scholarship: ________________________________________________

Address: ______________________________________________________

Telephone No: ___________________ Cell phone No: ________________

E-mail Address: ________________________________________________

Birthday: _________________________ Age: ________

Family:

Father: __________________________ Occupation: __________________

Mother: _________________________ Occupation: __________________

Schools:

High School: __________________________________________________

Elementary: ___________________________________________________

Others: _______________________________________________________

1
Lab Rules
1. Late students = 0% in lab performance and final report. (grace period=

10 minutes) No special lab performance whenever a student is tardy or

absent.

2. During lab performance, excellent behaviour is always expected. Behave

in a manner that does not disrupt classroom learning.

3. No eating, drinking and smoking inside the laboratory. Chewing gum is

not allowed.

4. Students must abide by the dress policies as indicated in Student

Handbook.

5. Academic honesty should be observed at all times as indicated in

Student Handbook (e.g. Cheating, Plagiarism, etc)

6. Late submission of project or No Show during presentation of project =

0%

2
TOPICS

Week 1: Orientation

Week 2: Office Productivity Tools: Word Processing and Excel

Week 3: Basic and Advanced HTML

Week 4: Introduction to CSS

Week 5: MS Visio and Flowchart/Algorithm

Week 6: C-Basic I/O

Week 7-8: C-Conditional Statements/ Midterm Project Submission (Website)

Week 9-10:C- Looping Statements

Week 11-12: Arrays

Week 13: Practical Exam /Final Project Submission (Software)

3
Requirements
Preliminary Report /Lab Performance
The student will print the reports from the lab manual and use it torecord all
pertinent data or the Professor will require the students to submit the report online
thru Turnitin. This must be submitted to the Professor forchecking after conducting
the lab exercise.

Final Report
This report must be submitted one week after the exercise wasperformed.

Practical Exam
This is a timed-exam that will be administered to each student when alllaboratory
Final Report have been performed or as scheduled.

Midterm Project
The student will develop a project proposal or the professor mayprovide the project
specifications.

Final Project
The student will develop a project proposal or the professor mayprovide the project
specifications.

Assessment / Evaluation
Average of Preliminary Reports/ Laboratory Activities 20%
Average of Final Reports/ Journal Entry 20%
Project 1 /Midterm Project 15%
Project 2 /Final Project 15%
Practical Exam 30%
_________________
Total 100%

Passing Grade: 70%

4
Laboratory Activity 1

Office Productivity Tools: MS Word and MS Excel

Objectives:
1. To familiarize the students in using MS Word and MS Excel
2. To learn how to compute, use logical IF and graph in MS Excel.

I. MS Word

Personal Portfolio/ Resume


Create a personal portfolio or a resume by making a list of accomplishments, education
and previous positions. Do not be concerned with the order of information. Gather, create,
collect and document your history with important facts, figures and milestones. Use MS
Word.

Highlights:

Name and contact info


Work Experience (if any)
Educational Background
Awards/Accomplishments
Organizations/Affiliations

II. MS Excel

A. Formulas and Functions


The worksheet below contains the performance of 10 students in quizzes, recitations, and long
examinations. Compute the final rating of the students in column Q. Compute the total of quizzes in
column E and the % rating in column F. Compute the total of recitation in column J and the % rating
in column K. Compute the total exams in column O and the % rating of long exams in column P. The
Final Rating is 20% quizzes, 20% recitation, and 60% long exams. You may use/create your own
formula or use the built-in functions of the program.

5
Quizzes Recitation Long Exam
Total % Total % Total % Final Rating
Name of Students 1 2 3 1 2 3 1 2 3
15 15 15 20 20 20 100 100 100
ABC 5 11 9 12 15 14 60 68 89
DEF 7 12 8 11 16 15 80 78 90
GHI 5 12 7 12 17 16 90 78 95
JKL 6 14 8 13 13 16 78 76 67
MNO 9 13 9 10 16 16 89 88 95
PQR 8 14 7 9 15 17 78 88 89
STU 6 10 8 12 17 17 50 65 45
VWX 8 9 8 13 18 18 88 86 87
YZA 9 13 7 14 19 19 55 65 45
CCC 8 11 6 12 18 18 94 67 96

6
B. Use of Logical function (IF)

Create the worksheet below. Copy the names of students and the final rating (values) from the worksheet
in exercise No. 2 to columns A and column B, respectively. In column C, with the used of IF command,
make a statement that will print Passed if final rating of the student is equal to or above 70%,
otherwise it will print Failed.

9
C. Graphs
Graph the enrollment data shown in Table 1. Your graph should look like the figure below and with
complete labels.

Table 1. Enrollment Trend from 2005-2015

10
2. Present the age distribution of the population shown in Table 2 in graphical form (pie chart). The chart
should look like the figure below.

Table 2. Age Distribution of the Population

11
Laboratory Activity 2.1

Creating a Simple Web Page


Objectives:

At the end of this activity, the students are expected to:

1. Start and quit the MS Notepad


2. Start and quit the web browser (Internet Explorer)
3. Draw, label and identify the basic parts of the MS Notepad
4. List down the functions of the parts of the MS Notepad
5. Enter and use HTML, HEAD, TITLE and body tags correctly
6. Create a simple web page
7. Save the HTML file
8. View the HTML file in the web browser
9. Identify and correct simple HTML programming errors

Discussion:

A. Starting Notepad

1. Click the Start Button on the taskbar and then point to Programs on the Start
Menu. Point to Accessories on the Programs submenu and then point to
Notepad on the Accessories submenu or Notepad++.
2. Click Notepad.
3. Click the Maximize button on the Notepad title bar to maximize the window.
4. In Notepad, the text users type will scroll continuously to the right unless the
WordWrap feature is turned on. WordWrap makes all the text visible in the
window, but it doesn't affect the way text appears when it is printed. For all
our activities, we will always activate the Word Wrap feature of Notepad.
5. To turn the WordWrap feature on, click the Edit Menu on the Menu
bar and then point and click Word Wrap.

Elements of the Notepad Window

1. Menu Bar

It is located at the top of the screen just below the title bar
It displays the Notepad Menu names
Each menu name
2. Text Area

This is where the text is display every time the user types

12
3. Scroll Bars

Display different portions of the text file in the window


The Vertical scroll bar is located at the right side of the window while the
horizontal scroll bar is located at the bottom of the window
Both scroll bars contain the scroll box which indicate the current location
in the file

B. Entering HTML Tags and Text

HTML is not case sensitive, uppercase, lowercase letters or


combination of both is treated as the same. To adhere standard practice HTML
development, we will use the uppercase letters when writing HTML tags.
Table 1 list down the basic HTML tags as well as their functions.

Table 1. HTML Tags and Their Functions

HTML Tags Function

<HTML></HTML> Indicates the beginning and end of an HTML development


<HEAD></HEAD>
Indicates the beginning and end on the document used for the title
and other document header information
<TITLE></TITLE>
Indicates the beginning and end of the title. Please take note that
the title does not display in the body of the Web page, but displays
on the title bar of the browser
<BODY></BODY> Indicates the beginning and end of the web page body

Indicates the beginning and the end of the text section called
<HN></HN>
heading; size ranges from <H1> through <H6>

<P></P> Indicate the beginning of a new paragraph; inserts a blank line


above the new paragraph
<UL<</UL> Indicates the beginning and the end of an unordered (bulleted) list

<LI></LI> Indicates that the item that follows the tag is an item within a list

<HR> Inserts a horizontal rule

<BR> Breaks a line of text at the point where the tag appears

13
Entering Headings in an HTML Tags

Headings serve to separate text and introduce new topics on Web pages. The
heading tags used for this purpose vary in size. The size ranges from <H1> through
<H6>, with <H1> being the largest. Figure 2.1.1 displays the various sizes of headings.
For consistency and to maintain a good look to your Web page, use the same sized
heading for the same level of topic.

Your main heading may contain the name of business or school, or the main idea
of the web page. Users usually have only one (1) tag on each Web Page.

Figure 2.1.1 HTML Heading Sizes


14
Entering Text in Paragraph Format

Web pages contain significant amount of text usually in paragraph format. The <P>
tag is one of the few tags that did not originally have corresponding ending tags. Newer
versions of HTML added </P> tag, but it is optional. When the Web browser finds </P>
tag, it starts a new line and adds some additional vertical spaces between the line that it just
displayed and the following lines. This gives enough of a break in the text to indicate that
there is a new paragraph. It is good habit to enter large sections having paragraph breaks.

Creating a List

Lists structure the text in an outline format instead in paragraph format. It helps
itemize the information on the web page.

Two Types of List

1. Unordered List

Also known as the bulleted list


Formats information as bullet points
The <UL> and </UL> must be at the beginning and end of this list
Users can use disc, square or circle as bullets in this list
By default, the disc is used
2. Ordered List

Also known as the numbered list


Information is shown as numbered or lettered points
The <0L> and </0L> must be at the beginning and end of this list
Users can create an ordered list using numbers, letters or roman numerals
The default option is to number the list
Note:

To change the bullet or number type, use the TYPE attribute within the <OL>or
<UL> tags. The tag could be <UL TYPE = disc or <OL TYPE=" 1)where the selected
type is found within the quotes. The <LI> and </LI> tags define a list item within the
ordered and unordered list. Remember that each item within the list has <LI> tag in front of
it and </LI> tag at the end.

Please refer to Figures 2.1.2 and 2.1.3 for various types of ordered and unordered
list.

15
Figure 2.1.2 Various Types of Unordered List

Figure 2.1.3 Various Types of Ordered List

16
Procedure:

Entering Initial HTML Tags

1. In your notepad, type <HTML> and then press the Enter Key.
2. Type <HEAD> and then press the Enter key
3. Type <TITLE> Computer Technician </TITLE> and then press the Enter key
4. Type </HEAD> and then press the Enter key.
5. Type <BODY> and then press the Enter key twice.
6. Type </BODY> and then press the Enter key.
7. Type </HTML> as the tag.

To create the Web page heading:

8. Click the blank line below <BODY> type <H1> What is a Computer
Technician ?</H1> and then press the enter key.

To enter text in paragraph format:

9. With the insertion point on line 7, type <P> A computer technician is a


person who repairs and maintains computers and servers. The
technicians responsibilities may extend to include building or configuring
new hardware, installing and updating software packages, and creating
and maintaining computer networks. Computer repair technicians work
in a variety of settings, encompassing both the public and private sectors.
Because of the relative newness of the profession, institutions offer
certificate and degree programs designed to prepare new technicians, but
computer repairs are frequently performed by experienced and certified
technicians who have little formal training in the field </P> and then press
the Enter key

Creating a Bulleted List

10. With the Insertion Point at line 11, type <H2> What steps do I need to follow to
become a computer technician?</H2>and then press the Enter key
11. Type <UL> and then press the Enter key
12. Type <LI>Learn about computers </LI> and then press the Enter key
13. Type <LI>Gain experience</LI> and then press the Enter key
14. Type <LI>Get formal computer training </LI> and then press the Enter key
15. Type <LI>Obtain certifications </LI> and then press the Enter key
16. Type the </UL> tag

17
Saving the HTML File

17. Save this as (yourname).html on your folder in the hard disk.

Using the Web Browser to View the HTML File

18. Click the Start button on the taskbar and then point to Programs on the Start Menu.
Point to the Internet Explorer or your web browser on the Programs submenu.

19. Now, open your HTML file. Your screen should at least resemble Figure 2.1.4.
You've just created your first web page.

Figure 2.1.4 Your First HTML Page

20. Now, go back to the Notepad and edit your work by simply trying different sizes of
heading. Remember that your heading size ranges from 1 to 6. Use other heading
sizes. Use also other bulleted list format such as the circle and square.

21. View your html file on your browser


18
Laboratory Activity 2.2

Creating a Website with Images


Objectives:

At the end of this activity, the students are expected to

1. Change the font size, colour and format of text of a web page
2. Describe what is homepage
3. Create a home page
4. Explain the difference between the two (2) classes of web images
5. Differentiate the various types of web images
6. Insert a background image
7. Insert a horizontal rule image
Discussion:

Homepage

A homepage is the main page of the Web site. This is the first page, which the
visitors view. On your home page, these are the important things to consider:

The purpose of the web site


What is the web site all about?
How visitors can move from one page to another?
E-mail link so visitors can email you directly from the initial page.
Font Attributes

To enhance the appearance of our web page and make it more interesting to the
visitors, different font size, font style and font face are available in HTML. Table 2 shows
the different FONT attributes and their functions:

Table 2. Font Attributes and Their Functions

Attributes Function

COLOR Changes the font color


Uses Color Codes
FACE Changes the font type
If the user doesnt specify a font the
default font is displayed
SIZE Changes the font size
Choices range from 1 to 7, or relative
values such as +2

19
The format use to change the color of the text is <FONT COLOR = " "> with the
color number code between the quotation marks. Figure 3.1 shows some of the font
attributes.

Figure 2.2.1. Web Page with Different Attributes

Web Page Images

Images can be used as backgrounds, horizontal rules or as pictures or graphics in any


web page. These images make the web page more interesting and colorful. They also help to
clarify or make a point being made in the text or as links to other Web pages. They also
serve as directional symbols that allow the visitors to navigate through the Web site.

Please take into consideration that the purpose of Web page determines which class
of image to use. HTML image tags are <IMG> and </IMG>.

Classes of Images

1. Inline Images

Images that display on the Web page directly, together with the text
20
2. External Images

Images that are stored separately from the Web page and are displayed only when
the visitor clicks a link to display them
Image Types

1.Joint Photographic Experts Groups (.JPEGS)

Pronounced as JAY-peg
It has an extension of .jpg, .jpeor .jpeg
It is a graphic image that is saved using compression techniques to make it
smaller for a download on the Web
When creating a JPEG image, users can specify the image quality to
reach a balance between image quality and file size
JPEG files are often used for photographs because they support millions of
colors. Photographs are more complex images than any other images
2. Graphics Interchange Format (.GIF)

Pronounced as Jiff or giff


It has an extension of .GIF
A graphic file with this type is also saved using compression technique to make it
smaller for download on the Web
GIF however supports more colors and resolutions than JPEG making it more
effective for scanned photographs
LSW compression, the technique that is used to compress GIF files is patented,
thus saving in GIF files needs license
GIF images play one line at a time when loading
Interlaced GIF images load all at once, starting with a blurry look and becoming
sharper as they load
3. Portable Network Graphics (.PNG)

Pronounced as ping
Designated with a png or ping extensions
A patent-free alterative to the GIF which has been developed and approved by the
World Wide Web Consortium as an Internet graphics standard
PNG file is also a compressed file that supports multiple colors and resolutions
Table 3. Image Attributes and Their Functions

Attributes Function

ALIGN Controls alignment


Alignment can be from top, middle, bottom, left, or right
ALT Alternative text to display when an image is being
loaded
BORDER Defines the border width

21
HEIGHT Defines the height of the image
Improves the loading time
HSPACE Defines the horizontal space that separate the image
from the text
SRC Defines the URL of the image to be loaded

YSPACE Defines the vertical space that separate the image from
text
WIDTH Defines the width of the image
Improves loading time

Inserting Background Image

To insert a background image, we will use the BACKGROUND attribute. The


BACKGROUND attribute defines the source of the image. This statement tells the browser
where to locate the image users want displayed.

Procedure:

Creating an Image File

1. Open MS Paint.

2. Create an image that will serve as your background for your homepage.

3. If you like, you can copy any image file available in Windows and then paste it in
Paint.

4. Save this file as background.jpg in your folder

Creating a Home Page

5. Open Notepad or Notepad++. Be sure that your Word Wrap is ON.

6. Enter initial HTML tags. Type <HTML> and then press the Enter key. Type
<HEAD> and then press the Enter key

7. Type <TITLE> CCT Home Page </TITLE> and then press the Enter key

8. Type </HEAD> and then press the Enter key

9. Type <BODY> and then press the Enter key

10. Type </BODY> and then press the Enter key


22
11. Type </HTML> and then press the Enter key

12. Position the insertion point on the blank line between the <BODY> and </BODY>

13. We know that <H1> tag assigns the largest possible size to a heading and the
attribute ALIGN = "CENTER" will center the heading. We will enhance our home
page with the <FONT> and </FONT> tags. Click line 6 between the <BODY> and
the </BODY> tags, type <H1 ALIGN = "CENTER"><FONT COLOR =
"#000066"> Computer Technician </FONT></H1> and then press the Enter key.

14. With the insertion point in line 7, type <P>In a nutshell, computer technicians
perform installation & maintenance or solve problems that people have with
their computers. Just as there are different types of computers and different
levels of computer systems and networks, there are also several different types
of computer specialist. A partial list of some of the job designations in this
growing field includes the following: </P> as the first paragraph of the body.

15. Press the ENTER key.

16. After the first paragraph, type <H2> What does a computer technician do? </H2>
and then press the Enter key.

17. Now, we are to add a bulleted list of information. Recall that in Lab Activity 2.1, we
performed this operation without changing the bullet type available, which is the
disc. We will now use the bullet type square for this activity. Create a bulleted list
for the following elements:

Desktop Support Specialist


Network Administrator
Systems Administrator
Computer Forensics Specialist
Help Desk Technician
Customer Support Analyst
Internet Professional

18. Now, type <H2>Our Services </H2> next and then press the enter key. This would
be our next subheading.

19. Create another list, using the bullet square, with the following elements:

Computer Troubleshooting and Repair


Software Package Installation
Network Maintenance and Troubleshooting
Web Page Development and Maintenance
Printing

23
We've just created the first part of our web page.

20. Now, we are to insert background and horizontal rule image for our web page. To
add a background image. First, position the insertion point insertion point
immediately to the Y in the <BODY> tag and then press the space bar. Type
BACKGROUND = "directory and the filename of the image". In this case, use
the image file, background.jpg you've created earlier.

21. We have just added an image background to our web page. We are now ready to
create a horizontal rule image. But we first have to create the horizontal bar. Open
your MS Paint and then using the box object, create a rectangular image filled with
color blue. Save this at c:\desktop\lbyec71 with filename bluebar.jpg. We will use
this as our horizontal rule image.

22. Going back to Notepad, point the insertion point to the right of the </H1> and then
press the Enter key. Type <CENTER><IMG SRC =
"c:\desktop\lbyec71\bluebar.jpg" HEIGHT = 5 WIDTH = 500></CENTER> as
the tag. This line defines our horizontal rule. It tells that the horizontal rule should be
place at center and with height and weight dimensions specified.

23. We are to copy this horizontal rule image in the middle of two bulleted lists.
Highlight the text <CENTER><IMG SRC = "c:\desktop\lbyec71\bluebar.jpg"
HEIGHT = 5 WIDTH = 500></CENTER> and then click the EDIT menu then
Copy. Now, position the insertion point at the end of our 2 nd unordered list and then
click the EDIT menu again and then click PASTE. We have now two (2)
horizontal rule images.

24. Save this exercise as (yourname).html. View this file on the web browser. Your
screen should at least resemble Figure 2.2.2.

24
Figure 2.2.2. The Finished Work

25. Close and exit your Web Browser and Notepad.

25
Laboratory Activity 3

Introduction to CSS

Objectives:

1. Learn the basic of cascading style sheets or CSS.


2. Design a website using HTML and CSS
3. Differentiate different styles of CSS

Discussion:
What is CSS?
CSS stands for Cascading Style Sheets
Styles define how to display HTML elements
Styles were added to HTML 4.0 to solve a problem
External Style Sheets can save a lot of work
External Style Sheets are stored in CSS files

CSS Syntax

A CSS rule has two main parts: a selector, and one or more declarations:

To make the CSS more readable, you canput one declaration on each line:
p
{
color:red;
text-align:center;
}

The id Selector

The id selector is used to specify a style for a single, unique element.


The id selector uses the id attribute of the HTML element, and is defined with a "#".

The style rule below will be applied to the element with id="para1":

26
Example:

#para1
{
text-align:center;
color:red;
}

The class Selector

The class selector is used to specify a style for a group of elements. Unlike the id selector, the
class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.

The class selector uses the HTML class attribute, and is defined with a .

In the example below, all HTML elements with class="center" will be center-aligned:

Example:
.center {text-align:center;}

You can also specify that only specific HTML elements should be affected by a class.
All p elements with class="center" will be center-aligned: p.center {text-align:center;}

Three Ways to Insert CSS

There are three ways of inserting a style sheet:


External style sheet
Internal style sheet
Inline style

External Style Sheet

An external style sheet is ideal when the style is applied to many pages. With an external style
sheet, you can change the look of an entire Web site by changing just one file.
Each page must link to the style sheet with the <link> tag. The <link> tag goes inside the head
section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

An external style sheet can be written in any text editor. The file should not contain any html
tags. The style sheet file must be saved with a .css extension. An example of a style sheet file is
shown below:

27
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/background.gif");}

Internal Style Sheet


An internal style sheet should be used when a single document has a unique style. You define
internal styles in the head section of an HTML page, inside the <style> tag, like this:
<head>
<style>
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/background.gif");}
</style>
</head>

Inline Styles
An inline style loses many of the advantages of a style sheet (by mixing content with
presentation). Use this method sparingly!
To use inline styles, add the style attribute to the relevant tag. The style attribute can contain any
CSS property. The example shows how to change the color and the left margin of a paragraph:
<p style="color:sienna;margin-left:20px;">This is a paragraph.</p>

Source: http://www.w3schools.com/css/css_howto.asp
(you may also click the source to view different CSS commands)

Exercises:

Before you begin, create a folder on your desktop and name the folder as: lbyec71. Save all
your files to lbyec71 folder.

1. Type and save the following as a CSS (.css) file. Make sure that you are NOT saving it
as a text file. Name the file "sample.css" (without the quotes).

body{ background-color: gray;}


p {color: blue;}
h3{color: white;}

2. Type and save it as CSS1.html

<HTML>
<HEAD>
<link rel="stylesheet" type="text/css" href="sample.css"/>
</HEAD>
<body>
<h3> A White header</h3>
28
<p> This paragraph has a blue font.
The background color of this page is gray because
we changed it with CSS! </p>
</body>
</HTML>

3. Run the html file using notepad++. The output should be similar to this:

29
Laboratory Activity 4

Block Diagram and Flowchart Using MS Visio

Objectives:

1. Learn and manage basic diagrams, workflows and flowcharts.

2. Get acquainted with Microsoft Visio, which is the fastest, easiest tool for creatingflowcharts,
organization charts, timelines, marketing diagrams and much more.

Discussion:

Block Diagram
It is a simplified illustration of a system, program, or process. The electronic andcomputer industries
use block diagrams to convey a variety of technical information.

Block Representations
Each individual block represents a stage, substage or unit of the total system as
an independent function.

Individual blocks may represent aspect of process, as inflow diagrams

Blocks may represent individual modules, units or removable portions of the total
systemmade up of multiple sections.

Components of a Block Diagram


1. Blocks a variety of simple geometric shapes is used for block diagrams,
althoughrectangular forms are the most common. Blocks can be placed vertically or
horizontally,depending on the needs of the diagram. In general, a block diagram should
contain as fewdifferent sizes of blocks as possible.

30
2. Symbols These are usually units and are normally depicted with aspects of theirreal-life
configuration.

3. Flow Lines- connects blocks and symbols according to the functional sequence of thesystem.
Flow lines are drawn as solid, medium-weight lines. The thickness of the linesshould be the
same as that used for the blocks. All flow lines are drawn withhorizontal and vertical lines. Do
not use diagonal lines or rounded corners.

Algorithms and Flowcharts


A typical programming task can be divided into two phases:

1. Problem solving phase - produce an ordered sequence of steps that describe solution
ofproblem. This sequence of steps is called an algorithm

2. Implementation phase - implement the program in some programming language

Flowcharts

(Dictionary) A schematic representation of a sequence of operations, as in a manufacturing


process or computer program.

(Technical) A graphical representation of the sequence of operations in an information system


or
program. Information system flowcharts show how data flows from source documents through
the computer to final distribution to users. Program flowcharts show the sequence of
instructions
in a single program or subroutine. Different symbols are used to draw each type of flowchart.

31
Example 1: Write an algorithm and flowchart to determine a students final grade and indicate
whether it is passing or failing. The final grade is calculated as the average of four marks

Algorithm
Step 1:
Input M1,M2,M3,M4

Step 2:
GRADE (M1+M2+M3+M4)/4

Step 3:
if (GRADE < 70) then
Print FAIL
else
Print PASS
endif

Flowchart

32
Example 2: Write an algorithm and draw a flowchart to convert the length in feet to centimeter.

33
Example 3: Write an algorithm that reads two values, determines the largest value and prints
the
largest value with an identifying message.

Exploring MS Visio

34
1. Open Visio and open the shapes template.

2. Drag and drop the following shapes to the workspace: square, rectangle, triangle.
*drag is done by pointing on the object, then hold down the left button of the mouse and
move it to the point where the object will be placed. Release to drop.

3. Flip the triangle both horizontally and vertically and observe what happens.

4. Misalign them and group them by dragging the left mouse button until all of the blocks are
highlighted. Connect them using the connect button.

5. Undo what you just did, and connect the shapes by using the pencil tool. You may also
choose the line tool.

6. You can change the thickness of the line and the block by clicking on the shape first, then
click on the line tool. Make sure that the object is highlighted when you do this.

7. Name the block by double clicking on the shape or by using the text tool.

8. Save your file as visio_exercise.

Exercises:

1. Draw the flow diagram using proper line weights and proper standards.

35
2. Redraw the following using MS Visio:

A. SSB Receiver

B. Power Supply

36
Laboratory Activity 5

Introduction to C- Programming
Objectives:
1. Learn the basic of C-Language: printf() and scanf().
2. Develop algorithms and flowcharts for use in programming applications.
3. Design, compile, test, run, and implement C language program

Discussion:

In the Beginning

C is a general purpose programming language and it started to run under UNIX
environment.

Dennis Ritchie invented the C-Programming language at AT&T Bell Laboratories

C is similar to Pascal, a functional programming language

Aimed in designing and developing operating systems, compilers, interpreters,
database software and embedded intelligence programs.

C Data Types

Before a variable name can be used in a C program, it must be declared explicitly, together with
its corresponding data type.

37
Variable Declaration

Before you can use a variable, you must tell the compiler about it by declaring it and telling the
compiler about what its "type" . To declare a variable you use the syntax:

<variable type><name of variable>;


Individual declaration
int sum;

float area;

char letter;


Group declaration
int n1, n2, sum, diff;

float area, fahr, celsius, div;

A Simple Program
#include <stdio.h>

int main()

printf( "ANIMO La Salle!\n" );

getchar();

return 0;

The #include is a "preprocessor" directive that tells the compiler to put code from the header called
stdio.h into the program before actually creating the executable. By including header files, you can gain
access to many different functions--both the printf and getchar functions are included in stdio.h.

The next important line is int main(). This line tells the compiler that there is a function named main, and
that the function returns an integer, hence int. The "curly braces" ({ and }) signal the beginning and end
of functions and other code blocks.

38
The printf function is the standard C way of displaying output on the screen. The quotes tell the compiler
that you want to output the literal string as-is (almost). The '\n' sequence is actually treated as a single
character that stands for a newline; for the time being, just remember that there are a few sequences that,
when they appear in a string literal, are actually not displayed literally by printf and that '\n' is one of
them. The actual effect of '\n' is to move the cursor on your screen to the next line. Notice the semicolon:
it tells the compiler that you're at the end of a command, such as a function call. You will see that the
semicolon is used to end many lines in C.

The next command is getchar(). This is another function call: it reads in a single character and waits for
the user to hit enter before reading the character. This line is included because many compiler
environments will open a new console window, run the program, and then close the window before you
can see the output. This command keeps that window from closing because the program is not done yet
because it waits for you to hit enter. Including that line gives you time to see the program run.

Finally, at the end of the program, we return a value from main to the operating system by using the
return statement. This return value is important as it can be used to tell the operating system whether our
program succeeded or not. A return value of 0 means success. The final brace closes off the function.
(Source: http://www.cprogramming.com)

printf() and scan()


printf()

This function is used in order to display the contents of a variable on the screen or to simply print the
contents as it is on the screen. This function can be accessed from anywhere within a program simply by
writing the function name, followed by a list of arguments enclosed in parentheses.

The arguments represent data items that are sent to the function. The necessary information required
for printf ( ) and scanf ( ) function is supplied by < stdio.h > file. This < stdio.h> file is called header file.
Different header files are like < conio.h >,< stdio.h > etc.

The general form of printf ( ) is

printf(format string); or

printf( < format string > , < list of variables>);

< Format string > consists of character to be display with following specifiers.

%f: For printing real values. %d:


For printing integer values.
%c: For printing character values.
%s: For printing string values.

39
scanf ( )

Input is entered into the computer from a standard input device by using scanf ( ) function. This function
can be used to enter any combination of numerical values, single characters & strings.

The general form of scanf ( ) is

scanf(data type format, &variable name );

Note: that the ampersand (&) before the variables in the scanf ( ) statement is must

Basic Data Type Format


Type Format Meaning

int %d whole number (3, 7, -9, 10000)

float %f A number with decimal point (5.8, -5.67,0.32)

char %c A single letter, symbol or number enclosed


with single quotes
(B, r, *)

%s a string of characters enclosed with double quotes


(Bok, JAY)

Example 1: Write a C program that calculates the sum of two input numbers and display
theresult

Algorithm:
Input: Enter two numbers (n1, n2)
Process: Compute the sum (sum=n1 +n2)
Output: Display the sum (sum)

#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum, n1, n2;
printf(\n Enter two numbers: );
scanf("%d %d", &n1, &n2);
sum = n1+n2;
printf("\n The sum is: %d\n", sum);
system("PAUSE");
return 0;
}

40
Example 2: Write a program to calculate the area of a circle and display the result. Use the
formula:
2
A= r

Algorithm:
Input: enter the radius
Process: Compute the Area
Output: Display the area

// 2. Area of a Circle
#include <stdio.h>
#include <stdlib.h>
#define Pi 3.1416
int main()
{
int r;
float A;
printf(\nEnter the radius: );
scanf("%d", &r);

A=Pi*r*r;
printf("The area: %5.2f \n", A);

system("PAUSE");
return 0;
}
Example 3: Write a program that computes the average of three input quizzes, then display the result.

Algorithm
Input: Enter three quizzes(q1, q2, q3)
Process: Compute the average (ave=(q1+q2+q3)/3)
Output: Display the Average
#include <stdio.h>
#include <stdlib.h>
int main()
{
int q1, q2,q3;
float ave;
printf("\nEnter Three Quizzes: ");
scanf("%d %d %d", &q1, &q2, &q3);
ave=(q1+q2+q3)/3;
printf("the average: %.3f\n", ave);
system("PAUSE");
return 0;
}

41
Laboratory Activity 6

C- Conditional Statements: If and If-Else


Objectives:
1. Learn the conditional statements of C-language using if and if-else.
2. Develop algorithms and flowcharts for use in programming applications.
3. Design, compile, test, run, and implement C language program

Discussion:

If and if-else statement


A statement in C used to select one or two alternative course of actions.

If statement is used in single alternative structure where it executes only when the condition is TRUE.

is used in two alternative structures, where it executes when the condition is either TRUE
If-else statement
or FALSE.

Syntax of if and if-else

42
If-else statement
if (condition) statement 1;
else
statement 2;

When the condition is proven true, statement 1 is executed. Otherwise, Statement 2 will run.
Else part is optional which means that it can be included or not.

C- Logical Operators

&& - The logical-AND operator produces the value 1 if both operands have nonzero values. If
eitheroperand is equal to 0, the result is 0. If the first operand of a logical-AND operation is equal to 0,
the second operand is not evaluated.

|| - The logical-OR operator performs an inclusive-OR operation on its operands. The result is 0 if
bothoperands have 0 values. If either operand has a nonzero value, the result is 1. If the first operand of
a logical-OR operation has a nonzero value, the second operand is not evaluated.

Relationship and Equality Operators


Operator Relationship Tested
< First operand less than second operand
> First operand greater than second operand
<= First operand less than or equal to second operand
>= First operand greater than or equal to second operand
== First operand equal to second operand
!= First operand not equal to second operand

Example 1: Write a program that determines if the input age is qualified to vote or not. The
qualifyingage is 18 years old and above.

Algorithm:
Enter age
If age > 18 : Qualified
Else: Too young!

#include <stdio.h>
#include <stdlib.h>
int main()
{
int age;
printf("\nEnter age: ");
43
scanf("%d", &age);
if (age>=18)
printf("Qualified to vote\n");

else
printf("Too Young!\n");

system("PAUSE");
return 0;
}

//using logical operators


#include <stdio.h>
#include <stdlib.h>
int main()
{
int age;
printf("\nEnter age: ");
scanf("%d", &age);

if ((age>=1)&&(age<=100))
{
if (age>=18)
printf("qualified to vote\n");
else
printf("too young!");
}
else
printf("out of range!\n");

system("PAUSE");
return 0;
}

Example 2: Write a program that accepts the input magic number. If the input is right, the magicwords
will be displayed. The magic number is 143 and its corresponding magic words are: I loveyou! if
the input number is wrong, displays: Sorry, better luck next time.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int mn;
printf("Enter a magic number: ");
scanf("%d", &mn);
if (mn==143)
printf("I love you!\n");
44
else
printf("Sorry, better luck next time!\n");

system("PAUSE");
return 0;
}

Example 3: Write a program that determines if the input number is POSITIVE or


NEGATIVE.Consider 0 as positive, considering that it contains no negative sign.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
printf("\nEnter a number:");
scanf("%d", &n);

if(n>=0)
printf("Positive\n");
else
printf("Negative\n");

system("PAUSE");
return 0;
}

Example 4: Write a program that determines if the input number is ODD or EVEN
number.Use %= modulo
The modulo operation finds the remainder of division of one number by another.
For instance, the expression "5 mod 4" would evaluate to 1 because 5 divided by 4 leaves a
remainder of 1, while "9 mod 3" would evaluate to 0
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r,n;
printf("\nEnter a number:");
scanf("%d", &n);
r=n % 2;
if(r==0)
printf("EVEN\n");
else
printf("ODD\n");
system("PAUSE");
return 0;
}
45
The sequence of if-else statements is the most
general way of writing a multi-way decision.
The expressions are evaluated in order, if any
expression is true, the statement associated with
it is executed, and this terminates the whole
chain.
-Dennis Ritchie

46
Laboratory Activity 7

C- Conditional Statements: Ladderized If-Else and Switch/Case


Objectives:

1. Learn the conditional statements of C-language using ladderized if-else and


case/switch statements.
2. Develop algorithms and flowcharts for use in programming applications.
3. Design, compile, test, run, and implement C language program

Discussion:

Ladderized if-else

Only those conditional statements and expressions that were first proven true are the ones to be
chosen and its associated statements will be executed. When all conditions were proven false,
else statement x will run.

Syntax:

if (condition 1)
statement 1;
else if (condition )
statement 2;
else if (condition )
statement n;
else
statement x;

Example 1: Write a program to assist a teacher in calculating student grades at the end of
thesemester. It accepts a numerical grade as input, then it will display the character as output,
based on the given scale:

90 and above: A
80-89 B
70-79 C
60-69 D
Below 60 F

47
#include <stdio.h>
#include <stdlib.h>
int main()
{
int g;
printf("\nEnter grade: ");
scanf("%d", &g);
if ((g>=90) && (g<=100))
printf("A\n");

else if ((g>=80) && (g<=89))


printf("B\n");
else if ((g>=70) && (g<=79))
printf("C\n");
else if ((g>=60) && (g<=69))
printf("D\n");
else if ((g>=50) && (g<=59))
printf("F\n");

else
printf("Out of Range\n");

system("PAUSE");
return 0;
}

Example 2: Write a program that displays an equivalent color once an input letter match its
firstcharacter, for example b for Blue, r for Red, and so on. Here are the given criteria:
B or b Blue
R or r Red
G or g Green
Y or y Yellow

#include <stdio.h>
#include <stdlib.h>
int main()
{
char let;
printf("Enter a letter: \n");
scanf("%c", &let);

if((let=='B') || (let=='b'))
printf("Blue\n");

else if((let=='R') || (let=='r'))


printf("Red\n");

48
else if((let=='G') || (let=='g'))
printf("Green\n");

else if((let=='Y') || (let=='y'))


printf("Yellow\n");

else
printf("Unknown Color\n");
system("PAUSE");
return 0;
}

Switch/Case Statement

Used to simplify some of the tasks of ladderized if-else statements. Variables declared as
integers and characters are the best candidates that can be tested or evaluated by the switch.

The switch/case statement is a multi-way decision that tests whether an expression matches
one of a number of constant integer values, and branches accordingly. If a case matches the
expression value, execution starts at the case. -Dennis Ritchie

switch(var_expression) {
case const_value: statement 1; break;
case const_value: statement 2; break;
case const_value: statement 3; break;
case const_value: statement 4; break;
default: statement x; break;
}

The break statement causes an immediate exit from the switch. Because cases serve just as
labels, after the code for one case is done, execution falls through to the next unless you take
explicit action to escape. -Dennis Ritchie

49
Example 3: Write a program to display the high school level of a student, based on its year-
entrynumber.

1 Freshman
2 Sophomore
3 Junior
4 Senior

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n;
printf("enter your year-entry number: \n");
scanf("%d",&n);

switch(n)
{
case 1: printf("Freshman\n"); break;
case 2: printf("Sophomore\n"); break;
case 3: printf("Junior\n"); break;
case 4: printf("Senior\n"); break;
default: printf("Out-of-School\n"); break;
}
system("PAUSE");
return 0;

50
Case/Switch Structure

51
Laboratory Activity 8

C- Looping Statements (Part 1)

Objectives:
1. Learn the looping statements of C-language such as for, while and
do-while loop.
2. Develop algorithms and flowcharts for use in programming
applications.
3. Design, compile, test, run, and implement C language program

Discussion:

Looping Statement

A program instruction that repeats some statement or sequence of


statements in a specified number of times.

A set of instructions to be performed all over again until a certain


condition is reached, met, or proven and tested as false.

Loops are used to repeat a block of code. Being able to have your
program repeatedly execute a block of code is one of the most basic but
useful tasks in programming -- many programs or websites that produce
extremely complex output (such as a message board) are really only
executing a single task many times. Alex Alain, cprogramming.com

Three Looping Statements of C-Language

1. For-loop

The for loop is the most powerful and flexible of all the loops used
in C. the general syntax is:

for(initialization ; condition ; loop control)


{
action;
action; //loop
body action;
}

The initialization is evaluated before the loop begins. You have to


declare and assign an initial value for the loop. This initialization is
evaluated only once at the beginning of the loop.

52
The condition tells the program that while the conditional
expression is true the loop should continue to repeat itself.

The loop control executes after each cycle in the loop. The count may
increase, decrease by 1 or of some other value.

Loop control using variable x


x++ -incrementation

x-- -decrementation

x+=n / x-=n
where n is any number

Example 1: Write a program that generates the given sequence:1 2 3 4 5

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n;

printf("\nFor loop example- Incrementation");


for(n=1; n<=5;n++)
{
printf("\n %d",n);
}
printf("\n");

system("PAUSE");
return 0;
}

53
Example 2: Write a program that generates the given
sequence:5 4 3 2 1

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n;
printf("\nFor loop example- decrementation");
for(n=5; n>=1;n--)
{
printf("\n %d",n);
}
system("PAUSE");
return 0;
}

Example 3: Write a program that calculates the sum of a given sequence numbers:

1+2+3+4+5

#include <stdio.h>
#include <stdlib.h>

int main()
{
int sum, i;

printf("\n the use of accumulator");


sum = 0;
for(i=1; i<=5; i++)
{
printf("\n %d", i); sum = sum+i;
}

printf("the sum is %d", sum);


getch();
return 0;
}

54
Important Reminders for Looping Statement:

For incremental loop: initialization <= conditional value

For decremental loop: initialization >= conditional value

55
Laboratory Activity 9

C- Looping Statements (Part 2)


Objectives:
1. Learn the different looping statements: while loop and do-while loop
2. Develop algorithms and flowcharts for use in programming applications.
3. Design, compile, test, run, and implement C language program

While loop

Syntax:

initialization;
while(condition)
{
statements; inc/dec/loop control;
}

Example 4. Using while loop,Write a program that generates the given sequence:
1
2
3
4
5

#include <stdio.h> #include


<stdlib.h> int main()
{
int n;

printf("\n While loop-Incrementation");


n=1;
while(n<=5)
{
printf("\n %d", n);
n++;
}
getch(); return 0;
}
56
Do-While Loop
Syntax:
initialization; do { statements; inc/dec;
} while (condition);

Example 5. Using do- while loop, Write a program that generates the given sequence:
1
2
3
4
5
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
printf("\nDo- While loop-Incrementation");
n=1;
do {
printf("\n %d",n);
n++;
}
while (n<=5);
getch();
return 0;
}

Example 6. Write a program that calculates the sum of a given sequence numbers: 1 + 2 + 3 + 4
+5

//USING FOR LOOP


#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum, i;
printf("\n the use of accumulator");
sum = 0;
for(i=1; i<=5; i++)
{
printf("\n %d", i);
sum = sum+i;
57
}
printf("the sum is %d", sum);
getch();
return 0;
}

//USING WHILE LOOP


#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum, i;
printf("\nWhile loop Accumulator");
i=1;
sum=0;
while(i<=5) {
printf("\n %d",i);
sum = sum+i;
i++;
}
printf("\nThe sum is %d", sum);
getch();
return 0;
}

//USING DO-WHILE
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum, i;
printf("\nWhile loop Accumulator");
i=1;
sum=0;
do
{
printf("\n %d",i); sum = sum +i;
i++;
} while (i<=5);
printf("\nthe sum is %d\n", sum);
getch();
return 0;
}

58
Laboratory Activity 10

Arrays
Objectives:
1. Learn the different Arrays in C.
2. Develop algorithms and flowcharts for use in programming applications.
3. Design, compile, test, run, and implement C language program

Discussion:

can contain or hold one or more values of the same data type
An array is a special type of variable which
with reference to only one variable name.


name identifier and can hold many values at the same time, provided
The array variable has a common
they have the same data type.


An array variable can be distinguished through a pair of square brackets [ ]. The number inside the
brackets is called an index or element.

One Dimensional Array

Syntax:
data_type array_name[index];
Example:
int ar[5]; or float arrayvar[10];

This example illustrates variable: ar[5] which is an integer type and can store a maximum of 5
values.
ar[0] = 10;
ar[1] = 20;
ar[2] = 50;
ar[3] = 80;
ar[4] = 30;

59
Two-Dimensional Array
Syntax:

data_type array_name[arow][acol]

Example:

int Score[2][3];
Score[0][0]= 10
Score[0][1]= 80
Score[0][2]= 30
Score[1][0]= 40
Score[1][1]= 50
Score[1][2]= 90

Example 1. Write a program using one-dimensional array that loads or stores the 5 values into an
arrayvariable. The values are the resulting computation from a simple equation. Then display the stored
values

60
Example 2. Write a program that determines the highest value among the five input values

Example 3. A program that stores roll numbers and marks obtained by a student side by side in
matrix

#include <stdio.h>
main()
{
int stud[4][2];
int i, j;
for (i=0; i<=3; i++)
{
printf ("\n Enter roll no. and marks"); scanf
("%d%d", &stud[i][0], &stud[i][1] );
}
for (i=0; i<=3; i++)
printf ("\n %d %d", stud[i][0], stud[i][1]);

system("pause");
return 0;
}

61
LBYEC71

Reviewer

62
Basic C program

Declarations

#include<stdio.h> - standard input and output functions


#include<stdlib.h>- standard library
#include<math.h>- advanced mathematics.

Integer Data Types

Floating Point Types

63
Frequently used Variable Types

Type Format

Integer %d

Float %f

Char %c or %s

Double %f

Variable Declaration

<variable type><name of variable>;

Individual Declaration:
int x;
float y;
char z;
Group Declaration:
int x, y, z;
float a, b, c;

Arithmethic Operators

64
Relational Operators

Logical Operators

Control Characters for printf

\a = alert
\b = backspace
\n = new line
\r = enter key
\t = horizontal tap
\v = vertical tab
\\ = backslash

Basic Programming Commands

printf(message); This command displays the message inside the application.

scanf(%d, &x); Scanf stores the input value into the variable x. The &symbol represents the
allocation of an address to the given input data. The %d means that the data that
will be scanned/input can be a decimal. Different data types need other
indications like %i.

Conditional Statements

If Statement

An if statement consists of a boolean expression followed by one or more statement

65
Syntax:

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}

If Else Statement

An if statement can be followed by an optional else statement, which executes when the boolean
expression is false.

66
Syntax:

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}

67
Nested if statements

It is always legal in C programming to nest if-else statements, which means you can use one if or else
if statement inside another if or else if statement(s).
Syntax:

if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}

Ladderized If-Else Statement


Only those conditional statements and expressions that were first proven true are the ones to be chosen
and its associated statements will be executed. When all conditions were proven false, else statement x will run.
Syntax:

if (condition 1)
{
statement 1;
}

else if (condition 2)
{
statement 2;
}

else if (condition n)
{

68
statement n;
}
else
{
statement x;
}

Example:

Write a program to assist a teacher in calculating student grades at the end of the semester. It accepts a numerical
grade as input, then it will display the character as output, based on the given scale:
90 and above: A
80-89 B
70-79 C
60-69 D
Below 60 F

#include <stdio.h>
#include <stdlib.h>
main()
{
int g;
printf("\nEnter grade: ");
scanf("%d", &g);
if ((g>=90) && (g<=100))
printf("A\n");
else if ((g>=80) && (g<=89))
printf("B\n");
else if ((g>=70) && (g<=79))
printf("C\n");
else if ((g>=60) && (g<=69))
printf("D\n");
else if ((g>=50) && (g<=59))
printf("F\n");
else
printf("Out of Range\n");
getch();
return 0;
}

Switch Case
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.

Syntax:
switch(expression)
{
case constant-expression :
statement(s);
break;

case constant-expression :

69
statement(s);
break;

/* you can have any number of case statements */


default :
statement(s);
break;
}

70
Loops

For Loops

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax

for ( initialization; condition; loopcontrol )


{
statement(s);

NOTES:

For incremental loop control (++) : initialization < condition

For decremental loop control (- -): initialization > condition

71
#include<stdio.h>

int main ()
{
/* for loop execution */
for(int a =10; a <20; a = a +1)
{
printf("value of a: %d\n", a);
}
return0;
}

72
While Loop

A while loop statement in C programming language repeatedly executes a target statement as long as a
given condition is true.
Syntax:

initialization;
while ( condition )
{
statement(s);
loop control;
}
#include<stdio.h>
int main ()
{
/* local variable definition */
int a =10;

/* while loop execution */


while( a <20)
{
printf("value of a: %d\n", a);
a++;
}
return0;
}

73
Do While Loop

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax:
initialization;
do
{
statement(s);
loop control;
}while(conditions);

#include<stdio.h>

int main ()
{
/* local variable definition */
int a =10;

/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a +1;
}while( a <20);
return0;
}

74
Arrays

used to store a collection of data (numerical)


One-Dimensional Array

Syntax

datatype arrayName [ arraySize ];

#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */

for ( i = 0; i < 10; i++ )


{
n[ i ] = i + 100; /* set element at location i to i + 100 */
} /* output each array element's value */

for (j = 0; j < 10; j++ )


{
printf("Element[%d] = %d\n", j, n[j] );
}
getch();
return 0;
}

Two-Dimensional Array
Format:
datatype arrayName [row][column];

#include<stdio.h>
int main ()
{/* an array with 5 rows and 2 columns*/
int a[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};
int i, j;/* output each array element's value */
for( i =0; i <5; i++)
{
for( j =0; j <2; j++)
{
printf("a[%d][%d] = %d\n", i,j, a[i][j]);
}
}

getch();
return0;
}

75
SAMPLE

PROBLEMS

76
INTRODUCTION TO C PROGRAMMING
Design and implement a C program to calculate the perimeter and the area of a rectangle based on the
users input (the user may input floating values). Then output the results to the screen. The program
should act like this:

- Enter the rectangle length: 10


- Enter the rectangle width: 5
- Rectangle perimeter = 30.0
- Rectangle area = 50.0
Note: When the user input a negative value, print the perimeter and area as zeros.
#include <stdio.h>
#include <stdlib.h>

main ()
{
float p,a,l,w;

printf("Enter Length of Rectangle\n");


scanf("%f",&l);
printf("Enter Width of Rectangle\n");
scanf("%f",&w);

if ((l>=0) || (w>=0))
{
p=(2*l)+(2*w);
printf("Perimeter of Rectangle %.2f\n",p);
a=l*w;
printf("Area of the Rectangle %.2f\n",a);
}
else
{
printf("Perimeter of Rectangle 0");
printf("Area of the Rectangle 0");
}

getch();
return 0;
}

77
CONDITIONAL STATEMENTS
1. The National Earthquake Information Centre has the following criteria to determine the
earthquakes damage. Here are the given Richter scale criteria and their corresponding characterization.
The Richter scale serves as the input data and the characterization as output information. Use any
conditional statements.
Richter scale characterization
n<5.0 Little or no damage
5.0>=n<5.5 some damage
5.5>=n<6.5 serious damage
6.5>=n<7.5 disaster
Higher catastrophe

#include <stdio.h>
#include <stdlib.h>
main()
{
float g;
printf("\nEnter Status of Damage: ");
scanf("%f", &g);
if ((g>=0) && (g<=5))
printf("Little or no damage\n");

else if ((g>=5.0) && (g<=5.5))


printf("Some Damage\n");
else if ((g>=5.6) && (g<=6.5))
printf("Serious Damage\n");
else if ((g>=6.6) && (g<=7.5))
printf("Disaster\n");

else
printf("Higher Catastrophe\n");

getch();
return main();
}

78
2. Conversions: This set of problems involves conversions of a value in one unit to another unit.
Each conversion option should prompt the user for a value in the specified units and then print the
converted value, along with the units.

Option1: convert miles to kilometers. (Recall that 1 mi= 1.6093440 km)

Option 2: convert pounds to kilograms. (Recall that 1kg = 2.205 lb)

Option 3: converts degrees Fahrenheit (Tf) to degrees Rankin(Tr). ( RecallTf = Tr - 459.67 deg R)

Use switch case statement program so that it will simply select from those given conversions:
(1) Conversions from miles to km
(2) Conversions from pounds to kg
(3) Conversions from deg. F to deg. R

#include <stdio.h> break;


#include <stdlib.h>
main()
{ default: printf("Invalid Number\n"); break;
int n; }
float m, p, km, kg,f,r; getch();
return main();
printf("Option 1:Miles to Kilometers: \n"); }
printf("Option 2:Pounds to Kilograms: \n");
printf("Option 3:Farenheit to Rankin: \n");
printf("Enter desired conversion option:\n");
scanf("%d",&n);

switch(n)
{
case 1: printf("Enter number of miles (mi)\n");
scanf("%f",&m);
km=m*1.61;
printf("Kilometers: %.2f\n",km);
break;

case 2: printf("(Enter number of pounds


(lbs)\n");
scanf("%f",&p);
kg=p/2.21 ;
printf("Kilograms: %.2f\n",kg);
break;

case 3: printf("(Enter Degrees Farenheit Value


(F)\n");
scanf("%f",&f);
r=f+459.67 ;
printf("Rankin(Tr): %.2f\n",r);

79
3. Write a scissors-rock-paper game, commonly known as jack n poy
Two players will input the equivalent letter. For example, s for scissors, r for rock, and p for paper.
Thendisplay the winner and the basis of winning such as: paper covers rock, rock breaks scissors
andscissors cut paper, or nobody wins. Capital or small letters should be accepted by your program.
Useany conditional statements.

#include <iostream>

int main()
{
char p1,p2;

printf("ROCK, PAPER, SCISSORS GAME\n");


printf("Enter R for Rock\nEnter S for Scissors\nEnter P for Paper\n");
printf("Enter Pick for Player 1 and 2:\n");
scanf( "%c %c", &p1, &p2);

if( (((p1 == 's')||(p1=='S')) && ((p2 == 's')||(p2=='S')))


|| (((p1 == 'r')||(p1=='R')) && ((p2 == 'r')||(p2=='R')))
|| (((p1 == 'p')||(p1=='P')) && ((p2 == 'p')||(p2=='P'))))

printf("It's a tie!");

elseif (((p1 == 's')||(p1=='S')) && ((p2 == 'p')||(p2=='P')))


printf("Player 1 Wins\n Scissors Beats Paper");

elseif (((p1 == 'r')||(p1=='R')) && ((p2 == 's')||(p2=='S')))


printf("Player 1 Wins\n Rock Beats Scissors");

elseif (((p1 == 'p')||(p1=='P')) && ((p2 == 'r')||(p2=='R')))


printf("Player 1 Wins\n Paper Beats Rock");

elseif (((p1 == 'p')||(p1=='P')) && ((p2 == 's')||(p2=='S')))


printf("Player 2 Wins\n Scissors Beats Paper");

elseif (((p1 == 's')||(p1=='S')) && ((p2 == 'r')||(p2=='R')))


printf("Player 2 Wins\n Rock Beats Scissors");

elseif (((p1 == 'r')||(p1=='R')) && ((p2 == 'p')||(p2=='P')))


printf("Player 2 Wins\n Paper Beats Rock");

else
printf("Nobody Wins");

return0;
}

80
4. Write a program that accepts dates written in numerical form and then output them as acomplete
form. For example, the input: 2 26 1986 should produce the output: February 26, 1986

1st solution: use ladderized if/ else if/ else


#include <iostream> printf("September");

usingnamespacestd; elseif (m==10)


printf("October");
int main ()
{ elseif (m==11)
intm,d,y; printf("November");

printf("Enter Month in Numerical Form\n"); elseif (m==12)


scanf("%d",&m); printf("December");

printf("Enter Day\n"); else


scanf("%d",&d); printf("Invalid Input");

printf("Enter Year\n");
scanf("%d",&y); printf("\t%d, \t%d",d,y);

printf("The Complete Date is:\n");


return0;
if (m==1) }
printf("January");

elseif (m==2)
printf("February");

elseif (m==3)
printf("March");

elseif (m==4)
printf("April");

elseif (m==5)
printf("May");

elseif (m==6)
printf("June");

elseif (m==7)
printf("July");

elseif (m==8)
printf("August");

elseif (m==9)

81
2nd solution: use the switch/case conditional statement
#include <iostream>

usingnamespacestd;

int main ()
{
intm,d,y;

printf("Enter Month in Numerical Form\n");


scanf("%d",&m);

printf("Enter Day\n");
scanf("%d",&d);

printf("Enter Year\n");
scanf("%d",&y);

printf("The Complete Date is:\n");

switch (m)
{
case1: printf("January"); break;
case2: printf("February"); break;
case3: printf("March"); break;
case4: printf("April"); break;
case5: printf("May"); break;
case6: printf("June"); break;
case7: printf("July"); break;
case8: printf("August"); break;
case9: printf("September"); break;
case10: printf("October"); break;
case11: printf("November"); break;
case12: printf("December"); break;
default: printf("Not in range"); break;

printf("\t%d, \t%d",d,y);

return0;
}

82
5. Write a program that accepts an input grade in percentile form and output its grade equivalent;
based on the given range of percentile and grade equivalent table below: use any conditional statement.
Range Grade
96-100 4.0
92-95 3.5
88-91 3.0
83-87 2.5
78-82 2.0
74-77 1.5
70-73 1.0
Below 70 0.0
Other grades out of range
#include <iostream>
usingnamespacestd;
int main ()
{
int g;

printf("Input Grade in Percentile Form\n");


scanf("%d",&g);
if ((g>=96) && (g<=100))
printf("4.0");
elseif ((g>=92) && (g<=95))
printf("3.5");
elseif ((g>=88) && (g<=91))
printf("3.0");
elseif ((g>=83) && (g<=87))
printf("2.5");
elseif ((g>=78) && (g<=82))
printf("2.0");
elseif ((g>=74) && (g<=77))
printf("1.5");
elseif ((g>=70) && (g<=73))
printf("1.0");
elseif (g<70)
printf("0.0");
else
printf("Out of Range");

return0;
}

83
6. Write a menu driven program for the following options using ladderized if-else statement:
a. to display the square root of the input integer
b. to display the product of three input numbers
c. Exit.
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
int n,result,prod,n1,n2,n3,square;

printf("Choose Between The Two Options\n");


printf("1: Display the square root of the input integer\n");
printf("2: Display the product of three input numbers\n");
printf("3: Exit\n");
scanf("%d",&n);
switch (n)
{
case 1: printf("Display the square root of the input integer\n");
printf("Enter Number\n");
scanf("%d",&n);

square=sqrt(n);
printf("The Square root of the number is: %d",square); break;
case 2: printf("Display the product of three input numbers\n");
printf("Enter 1st Number\n");
scanf("%d",&n1);

printf("Enter 2nd Number\n");


scanf("%d",&n2);

printf("Enter 3rd Number\n");


scanf("%d",&n3);

prod=n1*n2*n3;
printf("The product of the numbers is: %d",prod);
break;

case 3: return 0;break;


default: printf("Invalid Input"); break;
}
return 0;
}

84
85
Looping Statements

(Series.C)

Design and implement a program that will find the result of the following:

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
printf("Summation Program:\n\n");
printf("Result:\n\n");
inti,f,sm;
for (sm=0,i=53;i<=15674;i++)
{
f=(2*i)+5;
sm=sm+f;

}
printf("\t\t%d\n",sm);

return (0);
}

86
(Dividors.C)

Design and implement a program that will prompt the user to enter a number. The program shall give all
possible numbers (1-10) that divides that number.

Example:

Please, Enter a number: 36

Numbers dividing 36 are: 1, 2, 3, 4, 6, 9

#include <iostream>
#include <math.h>

int main()
{
inta,d,n;
printf("DIVIDORS\n\n");
printf("Find all possible numbers that divide a given number\n\n");
printf("Enter a Number: \n");
scanf("%d",&n);

printf("The divisors are:");


for(a=10;a>=1;a--)

{
d=n%a;
if (d==0)
printf("\n%d",a);
else
printf("");
}
return 0;
}

87
(Swap.C)

Design and implement a program that will enclose exercises 1, 2 and 3 inside a do-while loop, to make a
user choose among the three which ones he wants to execute. The program should show the following
menu:

Exercise 01 - Print
Exit
Exercise 02 - Summation
Enter your choice [1, 2, 3, or 4]:
Exercise 03 Division

When the user inputs 1, he will get the statement DLSU IS THE BEST twice and Manila once. Then the
program will print the menu again to ask the user for another input. When the user inputs 2, he will get
the value of the summation shown in exercise 2 and so on.
#include <iostream>
#include <math.h>
#include <cstdlib>

using namespace std;

int main ()
{

int n;

printf("Menu:\n\n");
printf("1 - DLSU IS THE BEST LOOP\n");
printf("2 - Summation\n");
printf("3 - Division \n");
printf("4 - Exit\n\n");
printf("Enter Desired Option\n");
scanf("%d",&n);

switch (n)
{

case 1: printf("DLSU IS THE BEST LOOP\n\n");


intx,y,s;
for(s=0;s<10;++s)
{
for(x=0; x<2; ++x)
{
puts("DLSU IS THE BEST");
}

88
for(y=0; y<1; ++y)
{
puts("Manila");
}}

break;
case 2: printf("Summation\n\n");

inti,f,sm;
for (sm=0,i=53;i<=15674;i++)
{
f=(2*i)+5;
sm=sm+f;

}
printf("%d\n",sm);

break;

case 3:

inta,d,n;
printf("DIVIDORS\n\n");
printf("Find all possible numbers that divide a given number\n\n");
printf("Enter a Number: \n");
scanf("%d",&n);

printf("The divisors are:");


for(a=10;a>=1;a--)

{
d=n%a;
if (d==0)
printf("\n%d",a);
else
printf("");
}

break;

case 4:
break;

}
return 0;

89
}

90
Create a Multiplication Table from 0 -10 using for loop.
#include <iostream>

int main()

{
int c, r;

for (c = 1; c <= 10 ; c++) {


for (r = 1; r <= 10; r++){
printf(" %2d ", c*r );
}

printf("\n");
}

return0;
}

91
Build a C-program that will imitate the following output. Use for loop.

#include <iostream>

int main()
{
intidx;
idx = 0;
int week;
floatacc_bal,amt_dep;
intbal;
week = 0;
amt_dep = 0;
acc_bal = 0;
bal = 0;
printf("52 WEEK MONEY CHALLENGE\n\n");
printf("Week\t");
printf("Amount Deposited\t");
printf("Account Balance\t\n");
do{
bal++;

printf ("%d\t\t\t",++week);
printf ("$\t%.2f\t\t\t",++amt_dep);
printf ("$\t%.2f\t\t\n",++acc_bal);

92
acc_bal = acc_bal + bal;

idx++;
} while(idx<= 51);

return0;
}

93
ARRAYS
Write a program using one-dimensional array that calculates the sum and average of the five input
values from the keyboard and prints the calculated sum and average.
#include<iostream>

int main()
{
inti,sum=0,a[4];
floatave;

printf("SUM AND AVERAGE\n");


printf("Enter Five numbers:");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
ave=sum/5;

printf("Sum: %d\n",sum);
printf("Average: %.2f\n",ave);

return0;
}

94
Write a program using two dimensional arrays that searches a number and display the number of times
it occurs on the list of 12 input values.

Sample input/output dialogue:


15 16
20 18
13 20
30 18
35 20
40 22
Enter a number to search: 20
Occurrence/s: 3
#include<iostream>
#include<math.h>

int main()

{
inti,num=0;
floats,ar[4];

printf("Enter Twelve Numbers:\n");

for(i=0;i<12;i++)
scanf("%f",&ar[i]);

printf("Enter number to search:");


scanf("%f",&s);

for(i=0;i<12;i++)
if(ar[i]==s)
num++;

printf("Occurances:%d\n",num);

return0;
}

95
Write a C program for the Fibonacci series of n numbers using array.
Fi = F(i-1) + F(i-2)
Example: if n =5
F1 = 1
F2 = 1
F3 = F2+ F1 = 1 + 1 = 2
F4 = F3 + F2 = 2 + 1 = 3
F5 = F4 + F3 = 3 + 2 = 5
#include <iostream>

using namespace std;

int main ()
{

int a[10],i,n;
a[0]=1;
a[1]=1;
printf("Fibonacci Series\n\n");

printf("Enter Number:");
scanf("%d",&n);

printf("F1= %d\n",a[0]);
printf("F2= %d\n",a[1]);

for (i=1;i<n-1;i++)
{
a[i+1]=a[i-1]+a[i];
printf("F%d = F%d + F%d = %d + %d = %d\n",i+2,i+1,i,a[i-
1],a[i],a[i+1]);

}
return 0;
}

96
Write a C program that will compute for the average value of each row or column and the average value
of the entire matrix. Refer to the given example.
0 1 2 3

0 5 4 3 2 OUTPUT:

AVERAGE:
1 4 5 4 3
ROW 0 = 3.5
2 3 4 5 4 ROW 1 = 4

ROW 2 = 4
3 2 3 4 5
ROW 3 = 3.5

MATRIX = 3.75
#include <iostream>

using namespace std;

int main ()
{
float ar[4][4];
float row[4][1];
float tmp;
int ctr1,ctr2,col;

ar[0][0] = 5;
ar[0][1] = 4;
ar[0][2] = 3;
ar[0][3] = 2;

ar[1][0] = 4;
ar[1][1] = 5;
ar[1][2] = 4;
ar[1][3] = 3;

ar[2][0] = 3;
ar[2][1] = 4;
ar[2][2] = 5;
ar[2][3] = 4;

ar[3][0] = 2;
ar[3][1] = 3;
ar[3][2] = 4;
ar[3][3] = 5;

97
for(ctr1 = 0; ctr1<4; ctr1++){
tmp = 0;
for(ctr2 = 0; ctr2<4; ctr2++){
tmp = tmp + ar[ctr1][ctr2];
}
row[ctr1][0] = tmp;
row[ctr1][0] = tmp / 4;
}
printf("Output:\n\n");
printf("Average:\n\n");

for(col = 0; col<4; col++){

printf("\t\t\tROW%d= %.2f\n",col,row[col][0]);
}

for (ctr1=1; ctr1<4; ctr1++)


{ row[0][0]=row[0][0]+row[ctr1][0];
}

row[0][0]=row[0][0]/4;
printf("\t\t\tMatrix Ave: %.2f",row[0][0]);

return 0;
}

98
99

You might also like