Professional Documents
Culture Documents
Lbyec71 Lab Manual V5 PDF
Lbyec71 Lab Manual V5 PDF
Laboratory
Manual
Students Information Sheet
Subject: ___________________ Section: ___________ Schedule: ___________
Personal:
Name: _______________________________________________________
Scholarship: ________________________________________________
Address: ______________________________________________________
Family:
Schools:
Elementary: ___________________________________________________
Others: _______________________________________________________
1
Lab Rules
1. Late students = 0% in lab performance and final report. (grace period=
absent.
not allowed.
Handbook.
0%
2
TOPICS
Week 1: Orientation
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%
4
Laboratory Activity 1
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
Highlights:
II. MS Excel
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.
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.
11
Laboratory Activity 2.1
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.
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
Indicates the beginning and the end of the text section called
<HN></HN>
heading; size ranges from <H1> through <H6>
<LI></LI> Indicates that the item that follows the tag is an item within a list
<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.
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.
1. Unordered List
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
16
Procedure:
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.
8. Click the blank line below <BODY> type <H1> What is a Computer
Technician ?</H1> and then press the enter key.
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
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.
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.
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:
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:
Attributes Function
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.
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
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 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
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
Procedure:
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.
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
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.
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:
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:
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
Laboratory Activity 3
Introduction to CSS
Objectives:
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 style rule below will be applied to the element with id="para1":
26
Example:
#para1
{
text-align:center;
color:red;
}
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;}
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");}
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).
<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
Objectives:
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.
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.
1. Problem solving phase - produce an ordered sequence of steps that describe solution
ofproblem. This sequence of steps is called an algorithm
Flowcharts
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.
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:
Individual declaration
int sum;
float area;
char letter;
Group declaration
int n1, n2, sum, diff;
A Simple Program
#include <stdio.h>
int main()
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)
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.
printf(format string); or
< Format string > consists of character to be display with following specifiers.
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.
Note: that the ampersand (&) before the variables in the scanf ( ) statement is must
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
Discussion:
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.
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;
}
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;
}
#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
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
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");
48
else if((let=='G') || (let=='g'))
printf("Green\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
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
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
1. For-loop
The for loop is the most powerful and flexible of all the loops used
in C. the general syntax is:
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.
x-- -decrementation
x+=n / x-=n
where n is any number
#include <stdio.h>
#include <stdlib.h>
int main()
{
int 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;
54
Important Reminders for Looping Statement:
55
Laboratory Activity 9
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
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 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.
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
63
Frequently used Variable Types
Type Format
Integer %d
Float %f
Char %c or %s
Double %f
Variable Declaration
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
\a = alert
\b = backspace
\n = new line
\r = enter key
\t = horizontal tap
\v = vertical tab
\\ = backslash
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
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 */
}
}
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;
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
NOTES:
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;
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
Syntax
#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 */
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:
main ()
{
float p,a,l,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
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.
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
switch(n)
{
case 1: printf("Enter number of miles (mi)\n");
scanf("%f",&m);
km=m*1.61;
printf("Kilometers: %.2f\n",km);
break;
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("It's a tie!");
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
printf("Enter Year\n");
scanf("%d",&y); printf("\t%d, \t%d",d,y);
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 Day\n");
scanf("%d",&d);
printf("Enter Year\n");
scanf("%d",&y);
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;
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;
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);
prod=n1*n2*n3;
printf("The product of the numbers is: %d",prod);
break;
84
85
Looping Statements
(Series.C)
Design and implement a program that will find the result of the following:
#include <iostream>
#include <math.h>
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:
#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);
{
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>
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)
{
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);
{
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;
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: %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.
int main()
{
inti,num=0;
floats,ar[4];
for(i=0;i<12;i++)
scanf("%f",&ar[i]);
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>
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>
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");
printf("\t\t\tROW%d= %.2f\n",col,row[col][0]);
}
row[0][0]=row[0][0]/4;
printf("\t\t\tMatrix Ave: %.2f",row[0][0]);
return 0;
}
98
99