0% found this document useful (0 votes)
43 views63 pages

Laboratory Act1 - Basic Structure of C++

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views63 pages

Laboratory Act1 - Basic Structure of C++

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Laboratory Activity No.

1
BASIC STRUCTURE OF C++
Course Code: CS100A Program:
Course Title: Fundamentals of Progra Date Performed:
mming and Algorithm
Section: Date Submitted:
Name: Instructor:
1. Objective(s):
This activity aims to illustrate the basic structure of C++ programming and demonstrate how to construct C+
+ program.
2. Intended Learning Outcomes (ILOs):
The students should be able to:
2.1 Solve common errors in C++ programming.
2.2 Illustrate different arithmetic expression, the use of comments and the effect of escape sequence in C++
programming.
2.3 Demonstrate valid declaration of variables in constructing C++ program.
3. Discussion :
General Structure of a C++ Program
pre-processor directives
main( ) header line
{
local variable declarations;
statement1;
statement2;
statement3;

statementN;
}

Parts of a C++ Program


1. Pre-processor directives
- Begins with the pound (#) symbol and this is non-executable lines that give special instructions to
the compiler.
#include<header file>

a. #include
- Instructs the compiler to take account of the file, usually a header file, inside the angle
brackets (< >)
b. header file
- Is denoted by the h extension name, a built-in file where particular objects are defined and
must be included first before any of its internal functions can be used. This can also be user-created
which may also be included in other programs.

2. Function

Function header line


- Name of every function which ends with ( ), enclosed in the ( ) are optional parameters

returned_data_type function_name()

a. main( )
Only one of this must exist throughout a program. It is also called a driver function since it is the first
function that will be executed once the program is compiled.
b. {
- Determines the beginning of the function body and may also denote the start of a certain block
c. statements
- Basic component of a function and usually terminated by the terminator operator, the semi-colon
d. }
- Determines the end of the function body and may also signify the end of a certain block

Variable Declaration and Initialization


The table below shows the list of data type used in declaring variables and its syntax.

Table 1.1 List of Data types

Data Type Description Declaration Syntax Example


Integer a whole number int variable_name int sum
Float Number with a float variable_name float sum
fractional part, takes 4
bytes to store.
Double a double-precision double double total
floating point value, variable_name
takes 8 bytes to strore
Character a single character char variable_name char letter
String a series of character char char name[20]
variable_name[no. of
char]
Void valueless special
purpose type
Constant #define #define Pi
constant_name

RULES IN DECLARING VALID IDENTIFIER

1. The variable name must begin with a letter or underscore (_) and can contain only letters, underscores or
digits. It cannot contain blank spaces, commas, or special symbols such as (), &, $, #, \? etc.
2. A variable name cannot be a keyword or a reserved word that is already defined in the system.
3. A variable name cannot consist of more than 1024 characters.
ESCAPE SEQUENCE
The backslash instructs the compiler to divert from the way the next character would be normally
interpreted. An escape sequence is the combination of a backslash and a character, which must be
included in the message symbols as shown in table 1.2.
Table 1.2 List of Escape Sequence
\b Backspace \0 Null

\f Form feed \\ Backslash

\n New line \v Vertical tab

\r Carriage return \a Alert

\t Horizontal tab \o Octal constant

\" Double quote \x Hexadecimal constant

\' Single quote

COMMENT
A comment is a statement the compiler would not interpret. It is denoted by two backslash characters
(//) and the comment statement. It is primarily used for debugging and program maintenance.
Another way of indicating comments is through the use of block comments, indicated by a backslash
and an asterisk following it (/*) and ended by an asterisk and a backslash (*/). It is useful for converting a
large block of code or remarks.
EXPRESSIONS
A simple arithmetic expression consists of an operator connecting two operands.

Table1.2 Arithmetic Operator

Operator Operation Sample expression Resulting value

+ Addition 1+1 2

- Subtraction 13 – 8 5

* Multiplication 2*2 4

/ Division 27 / 3 9

% Modulus division 11 % 6 5
4. Resources:

Computer with DevC/C++ Application

5. PROCEDURE

Program 1. Working with Scape


Sequence.
1. Open the DevC/C++ application
and create new source file or
press CTRL+N.
2. Type the code as shown in
Sample Program1.1 into the Sample Program1.1 Working with scape sequence.
editor.
3. Save the code as
CProgram1.Cpp.
4. Compile or press CTRL+F9.
5. Run the program or press
CTRL+F10.
6. Compare the output with the expected output as shown below.

EXPECTED OUTPUT

7. Is the output similar? (yes or no) If no, why?


Yes, the output was similar.
Program 2. Combinational Operators
Sample Program1.2: Combinational Operators
1.

Open the DevC/C++ application and create a new source file or press CTRL+N.
2. Type the code as shown in Sample Program1.2 into the editor.
3. Save the code as CProgram2.cpp.
4. Compile or press CTRL+F9.
5. Run the program or press CTRL+F10.
6. Write the output below.

7. Explain briefly the flow of the output.

fNum and sNum are variables that are to be inputted in the following operations “Addition”, “Multiplication”,
“Division” and “Modulus”. When we perform the operation (fNum+=sNum) we get 5 as a result. The number
5 becomes the new value of fNum. This new value will be inputted in the following operation,
(fNum*=sNum). The result of that operation will then become the new value of fNum, and so on and so forth.

6. DATA / PROGRAM ANALYSIS

1.From Sample Program 1.2, what will be the output value of line 9. Explain.
The output of line 9 is 5. This is because fNum (10) from line 8, was divided by sNum (2)

2. In Sample Program 1.1 line 7, omit the character “<<”. Is the program run? Why?
When we omit “<<” the program will not run. [Error] no match for call to.

3. From Sample Program 1.1 line 5, what is the significance of “5” in the program?
The number 5 indicates the number of characters in the output.

4. If semicolon ( ; ) is omitted in the Sample program 1.2 line 6, does the program have an error?(yes/no). If
yes, what will be the error of the program? Write the comment that appears in the compiler.

Once the semi colon (;) was omitted the program ran into an error. The comment that appears in the
compiler states: [Error] expected ‘,’ or ‘;’ before ‘cout’

5. From the Sample Program 1.2 line 5, change the data type “int” to “float”. What will be the output of the
program and explain.

When replacing the data type “int” with “float” the program runs into an error because the modulus operator
% cannot apply to float. This is because a modulus is made to output whole integers and not floating
numbers.
6. From Sample Program 1.1, replace the code of line 1 and line 2 by
“/*#include<stdio.h>
#include<conio.h>*/”
Observe the output and explain.
Compared to iostream, stdio.h was not able to run the program. In this case, when using studio.h, we should
use the function “printf” in order to reveal the output.

7. SUPPLEMENTARY PROBLEMS

Direction: Save the program as ACT1a.Cpp and ACT1b.Cpp in the local disk. Put a comment and type the
programmer’s name, course and section and date performed on the first five lines of C++ editor.

1. Write and run a program that will convert the various temperatures from the given constant value as
shown in table below.

CONSTANT VALUE FORMULA OUTPUT


ºC = -5.4 ºF = 9/5ºC + 32 ºF =
ºF = 124.67 ºK = ºC + 273.15 ºK=
ºK = 305.15 ºR = ºF + 459.67 ºR=

2. Write and run a program that will display an equivalent power of 2 from a given constant value of n as
shown in table below. Use pow () function in the program.

N n
2
0 1
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256

3. The initial acceleration, a, of a rocket fired from earth, with an initial thrust, T, is given by this formula:

Write and run a program that will determine the initial acceleration of a rocket having a mass of 5X10 4kg and
an initial thrust of 6X105 Newtons. The Value of g is 9.81m/s2.

8. Assessment (Rubric for Laboratory Performance):


Laboratory Activity No. 2
INPUT / OUTPUT STATEMENTS
Course Code: CS100A Program:
Course Title: Fundamentals of Programming and Algorithm Date Performed:
Section: Date Submitted:
Name: Instructor:
1. Objective(s):
This activity aims to analyze the function of input/ output statements in C programming.

2. Intended Learning Outcomes (ILOs):


The students should be able to:
2.1 Illustrate different arithmetic expression, the use of comments and the effect of escape sequence in C++
programming.
2.2 Apply the different functions of input/output statements in constructing C++ program.
3. Discussion :

INPUT AND OUTPUT STATEMENT

The cout (see-out) derived from console output. It is an output object that sends data it receives to
the standard display device such as a computer monitor. As shown in the statement below, the word
“statement will be displayed on your computer screen.

Syntax:
cout<<” statement”;

The cin (see-in) derived from console input. It is used to enter data in a program while its running. It
allows users to enter a value at the keyboard and then the value is stored in a variable which is num1 as
shown below.

Syntax:
cin>>num1;

4. Resources:

Computer with DevC/C++ Application


5. PROCEDURE

Program 1. Sum of two integers.

1. Open DevC/C++ on your desktop and create a new source file.


2. Type the program as shown in Sample Program 2.1 and save as CProgram3.cpp.
3. Compile the program or press CTRL+F9.
4. Run the Program or press CLICK CTRL+F10.
Sample Program2.1 Sum of two integers.

Expected Output:

Enter 1st number: 25


Enter 2nd number: 37
The sum of two numbers is 62

5. Input value 25 and 37 for 1st and 2nd number respectively and observe the output and compare it on
expected output above.
6. Are the outputs the same?(Yes/No)__________________
7. If No, what is/are the problem that you encountered?__________________________________________

8. Create a pseudo code and flowchart of the given program in Sample Program 2.1
PSEUDOCODE FLOWCHART

Program 2. Working with operators.


A. Create a program that will give an output as seen in the Sample Output box below.
1. Open the DevC/C++ and create a new source file and save as a filename: CProgram4.cpp
2. Ask the user to input two integer numbers.
3. Perform the operation: multiplication, addition, subtraction, division and modulus
4. Display the result of the given operation on step number 3.
5. Compile and run the program.

Sample Output:
6. Write the program code in the box provided below.

B. Create a pseudo code and flowchart from the given procedure


PSEUDOCODE FLOWCHART
Program 3. Compute for speed.

1. Open DevC/C++ and create new source file or press CTRL+N.


2. Type the program as shown in Sample Program 2.2 and save as filename: CProgram5.cpp.
3. Compile and run the program.
4. Write the output in the box provided below.

Program Output

Part 4. I PUT it and I GET it!

1. Open the DevC/C++ and create new source file and type the program as shown in Sample Program 2.3
and save as filename: CProgram6.cpp.
2. Compile and run the program.
3. Enter two words as required by the given program and record the output in the box provided.
Sample Output:

3. Compare cout to puts( ) and cin to gets( ) function.


6. DATA / PROGRAM ANALYSIS

1. From Sample Program 2.2, assume input value for variable dist=405.65 and time=87.45. What will be the
complete output of the program?

2. From line 6 of Sample Program 2.2, omit the “;” and explain the output.

3. Convert the Sample Program 2.3 to cin>> and cout<< and observe the difference.

4. Replace line 7 of Sample Program 2.2 by //cout<<“Enter time in second:” ; and assume value for
dist=405.65 and time =87.45. Record the output and explain.

5. If the entire instruction from line 1 is omitted, is the Sample Program 2.2 will still run? Why?

6. From line 10 Sample Program 2.2, replace the operator “/” by “%”. Observe the output and explain.

7. SUPPLEMENTARY PROBLEMS
Direction: Save the program as ACT2a.Cpp, ACT2b.Cpp, and ACT2c.Cpp in the local disk. Put a comment
and type the programmer’s name, course and section and date performed on the first five line of C editor.
1. Make and run a program that will accept an inch dimension and convert it to meters.
(Note: 1 inch = 2.54 cm ; 1 m = 100 cm, use this conversion of inch to meters)
Sample Output:

2. Make and run a program that will convert an input year into minutes.
(Note: 1 year = 365 days ; 1 day = 24 hours ; 1 hr = 60 mins, use this conversion of year to
mins)

Sample Output:

3. Make and run a program that will take three numbers and display their sum and average.
Sample Output:

8. Assessment (Rubric for Laboratory Performance):


Laboratory Activity No. 3
CONDITIONAL STATEMENTS
Course Code: CS100A Program:
Course Title: Fundamentals of Programming and Algorithm Date Performed:
Section: Date Submitted:
Instructor:
1. Objective:

This activity aims to apply the different conditional statements in controlling the flow of instructions in C++
programming.
2. Intended Learning Outcomes (ILOs):
The students should be able to:

2.1 Demonstrate the use of different types of conditional statements in constructing C program.
2.2 Analyze the function of different conditional statement.
2.3 Apply relational and logical operators in different types of conditional statements.

3. Discussion

To check whether a certain expression is true or not, conditional statements are used. The conditions must
be met before the statements following those conditions are to be executed. Relational and logical
operations are needed to check the results of the statements as shown in table 3.1.

Table 3.1 Relational and Logical Operators

Relational Operators
== Equal to x == 0

< Less than x<0

> Greater than x>0

<= Less than or equal x <= 0

>= Greater than or equal x >= 0

!= Not equal to x != 0

Logical Operators
&& Logical AND ( x > 0 ) && ( x < 10 )

|| Logical OR ( x > 0 ) || ( x != 0 )

! Logical NOT ! ( 10 < 9 )


Conditional Statements

It controls the sequence statements depending condition. The following are the conditional statements.

1. If Statements. If the condition is true the statement inside the parenthesis { }, will be executive, else the
control will be transferred to the next statement after if.

if (expression/condition )
{
statement1;
}

2. If else Statement. If the condition is true the statements between if else is executed. If it false the
statement after else is executed.
if (expression/condition )
{
statement1;
}
else
{
statement2;
}

3. Else if else Statement. In else if, if the condition is true the statements between if and else if is executed.
If it is false the condition in else if is checked and if it is true it will be executed. If none of the condition is
true the statement under else is executed.

if (expression1/condition)
{
statement1;
}
else if (expression2/condition)
{
statement2;
}
else
{
statement3;
}

4. Nested If Statement. if one or more if-else statements are located inside an outer if-else statement.
if(expression/condition)
{if(expression/condition)
{ Statement;
}
else
{ Statement;
}
else
{statement;
}
}

5. Switch Statement. Switch statements can also be called matching case statements. If matches the value
in variable switch(variable) with any of the case inside, the statements under the case that matches will be
executed. If none of the case is matched the statement under default will be executed.

switch ( expression )
{
case value1: statement1;
statement2;

break;

case value_2: statementM;


statementN;

break;

default: statementX;
statementY;

break;
}

4. Resources:

Computer with DevC/C++ Application

5. PROCEDURE

Program 1. Odd or Even.

1. Open the DevC/C++ and create new source file.


4. Create an equivalent C program for figure 3.1 and save as a filename: CProgram7.cpp.
5. Write a comment on the first three lines of the editor: A C++ program that determines a number if it is
ODD or EVEN number.
6. Initialize variable num as integer data type.
7. Allow user to input an integer value.
8. Evaluate the condition:num%2==0
If the condition is TRUE then display the number is EVEN.
If the condition is FALSE then display the number is ODD.
9. Compile and run the program.
10. Write the program code and the sample output in the box provided on Page 6.
SOURCE CODE PROGRAM OUT PUT

Program 2. WHAT’S YOUR STATUS? Write a C program that will allow the user to input a specified
character and determine its status. Refer to the table below.

Table 3.2 What’s your Status?


CHARACTER INPUT STATUS OUTPUT
S/s Single
M/m Married
W/w Widow
A/a Annulled
D/d Divorced
C/c Complicated
Note: Outside of the condition write “STATUS NOT ON THE LISTS.”
1.Open the DevC/C++ and create a new source file and save as a filename: CProgram8.cpp
2. Write a comment on the first three lines of the editor: A C++ program that displays the status of a user
using a code character.
3. Ask the user to input a single character or a code as shown in the table above.
4. Display the equivalent status output as indicated in the table above.
5. Compile and run the program and write the program code and the sample output in the box provided.
6. Create a pseudo code and flowchart for a given scenario above. Please provide extra sheet for your
answer.

SOURCE CODE PROGRAM OUTPUT

Program 3. Rage from 1 to 20.

1. Open DevC/C++ and create a


new source file and save as a
filename: CProgram9.cpp.
2. Type the program as shown in
Sample Program 3.1
3. Compile and run the program.
4. Write the program output in
the provided box below.

Program Output
6. PROGRAM ANALYSIS

1. From Sample Program 3.1, assume input value for num=18. What will be the complete output of the
program?

2. If line 8 of Sample Program 3.1 will be replaced by if(num>=1 || num <=20) and assume input num=98,
what will be the output of the program? Explain your answer.

3. Add a condition in line 10 of Smaple Program 3.1 by else (num!=20). What will be the output and why?

4. In what state of the condition which the line 11 of Sample program 3.1 will be displayed? Explain your
answer.

5. Create a flow chart and pseudo code equivalent to Sample Program 3.1 Provide an extra sheet for your
answer.

6. From Program 2 with filename of CProgram8.cpp, what data type will be using from the given scenario
as shown in table 3.2
7. SUPPLEMENTARY PROBLEMS

Direction: Save the program as ACT3a.Cpp, ACT3b.Cpp, ACT3c.Cpp and ACT3d.Cpp in the local disk. Put
a comment and type the programmer’s name, course and section and date performed on the first five lines
of editor. Create a pseudo code and flowchart for each item. Please provide extra sheet for the answer.

1. Make and run a program that will input 5 numbers and output the highest and lowest numbers. Refer to
the table below for the given input.

Table3.3 Highest and Lowest Number


INPUT OUTPUT
1st num 2nd num 3rd num 4th num 5th num HIGHEST LOWEST
100 349 46 23 23
0.34 0.76 0.66 1.65 2.0
1560 830 7856 10067 8942
65.65 33.33 12.12 10.10 48.88
556.87 345.98 999.65 111.65 788.43

Sample Output:
Input 5 numbers: 5 2 3 4 1

The highest is 5 and the lowest is 1

2.Make and run a program that will input 3 numbers and display the numbers in ascending and descending
order.

Sample Output:
Input 3 numbers: 3 4 1

The Ascending order is 1 3 4

The Descending order is 4 3 1


3. Make and run a program that will input a year and output its equivalent Roman numeral. Range of input:
1000-3000. (Roman Conversion: I=1 V=5 X=10 L=50 C=100 D=500 M=1000).

Sample Output:

4. Make and run a program that will compute the total cost charges of a telephone call rendered from a
particular network using the given in table 3.4. The user will input call destination code (1 to 5), time code
(1=off-peak, 2=peak), and the duration of call

. Table 3.4 Phone Call Charges

Rate/
Rate/min
Off-peak Hours (1) min Peak hours (2)

Calls to the same


1 P8 1 Calls to the same P3
network network
2 Call to other network P8 2 Call to other network P4

3 Call to a landline P8 3 Call to a landline P4

4 National direct dial P 11 4 National direct dial P7

5 International direct dial P 20 5 International direct dial P 20


Sample Output

9. Assessment (Rubric for Laboratory Performance):

Laboratory Activity No. 4


ITERATIVE STATEMENTS
Course Code: CS100A Program:
Course Title: Fundamentals of Programming and Algorithm Date Performed:
Section: Date Submitted:
Name: Instructor:

1. Objective:
1.1. This activity aims to demonstrate the different forms of Iterative statements in C programming.
2. Intended Learning Outcomes (ILOs):
The students should be able to:
2.1 Analyze the program flow in each looping statement.
2.2. Create a C program using looping statement with conditional statement. .
3. Discussion
Iterative Statements
It is often known as looping, and they run many times while specific condition is true.
1. While Loop. A loop that valuate the condition yielding to true or false. If the condition is false, exit the
while statement and continue to the next statement. If the condition is true, execute each of the statements
inside the braces then go back to the evaluation of condition.
while (expression / condition)
{
Statement;
}

2.do-While Loop. A loop which the statements will be performed at least once before the expression is
evaluated.
do{
Statement;
}
while(expression / condition)
3. For Loop. A loop that first initialize the variable then evaluate if the condition is true or false. If the
condition is true, the statement will be executed then continue to counter or process. If the condition is
false, then exit the for-statement and continue to the next statement.

4. Resources:
Computer with DevC/C++ Application

5. Procedure
Program 1. Factors of a number.
Sample Program 4.1. Factors of a Number
1. Open the DevC/C++ application and create new source
file.
main( )
2. Type the code as shown in Sample Program4.1.
{ int num, divisor;
3. Save the code as CProgram10.cpp.
cout<<"Enter an integer: ";
4. Compile or press CTRL+F9.
cin>>num;
5. Run the program or press CTRL+F10.
divisor = num;
6. Determine and write the output below if Input value for
while ( divisor > 0 )
num=9.25.
{
Sample Output: if ( num%divisor == 0 )
cout<<"\n"<<divisor;
divisor--;
}
getch( );
}

7. Explain briefly the output.

Sample Program 4.2. Square of


Program 2. Square of a number. Number.
-----code omitted------
1. Open the DevC/C++ application and create new source main( )
{
int square=0, num, ctr;
cout<<"Input a number: ";
cin>>num;
ctr=num;
do
file.
2. Type the code as shown in Sample Program4.2.
3. Save the code as CProgra11.cpp.
4. Compile and run the program.
5. How many loops does the program has if the input num=25? Write the output and explain the answer at
the space provided next page.

Sample Output:

Explain your answer:

Program 3. C FOR Infinity.

1. Open the DevC/C++ application and create new source file.


2. Type the code as shown in Sample Program4.3 into the editor.
3. Save the code as CProgra12.cpp.
4. Compile and run the program.
5. Write the output in the box provided below.
Sample Output
6. Explain the program flow and when the program will be terminated.

Program 4. FOR Right Triangle.

1. Open the DevC/C++ application ad create new source file.


2. Type the code as shown in Sample Program4.4.
3. Save the code as CProgra12.cpp.
4. Compile and run the program.
5. Compare your output from the Sample output as shown below.

Sample Output
6. Are the outputs the same?(yes/no)_________
7. If no, Why?_________________________________________________________________________

8. Explain the program flow

6. Data/Program Analysis

1. Create a program that will implement a WHILE LOOP equivalent to Sample Program 4.3 and save as
CProgram13.cpp. Write the complete program on the space provided.

2. From Sample program 4.4, what will be the value or code needed for line 8 and line 9 for output
required? Write the answer in the space provided below.
3. Briefly discuss the difference between num++ and ++num.

4. From Sample Program 4.1, assume input value for num= 256. How many loops does the program have
before it terminates? Explain.

7. SUPPLEMENTARY PROBLEMS

Direction: Save the program as ACT4a.Cpp, ACT4b.Cpp, ACT4c.Cpp, ACT4d.Cpp, ACT4e.Cpp and
ACT4f.Cpp in the local disk. . Put a comment and type the programmer’s name, course and section and
date performed on the first five lines of the C editor.

A. Using while loop

1. Make and run a program that will output all the common factors of two numbers.
2. Make and run a program that will display all the consonants from ’A’ to ’Z’.

B. Using do-while loop

1. Make and run a program that will output all the prime numbers from 1-100.
2. Make and run a program that will allow the user to input ten numbers and display the total number
of positive and negative numbers entered.

C. Using for loop

1. Make and run a program that will display the numbers 1, 2, 3, and so on depending on the number
of lines the user will enter. For example, if input=3, first line of output should be 1, next line 2 3, and the last
line 4 5 6.
2. Make and run a program that will be able to display the following output:
*

* *

* * * * *

* * * *

* * * * *

9. Assessment (Rubric for Laboratory Performance):

Laboratory Activity No. 5


FUNCTIONS
Course Code: CS100A Program:
Course Title: Fundamentals of Programming and Algorithm Date Performed:
Section: Date Submitted:
Name: Instructor:
1. Objective:
This activity aims to demonstrate the flow of a program using function in C++ programming.
2. Intended Learning Outcomes (ILOs):
The student shall be able to
1. Demonstrate on how to implement functions in constructing C++ program
2. Evaluate the use of functions in constructing C++ program.

3. Discussion
One of the distinct advantages of C/C++ language is being structured, meaning it can have modules.
Because of this, one can easily define any function, besides those standard built-in functions. Functions are
subroutines containing a statement or collection of statements that perform a certain task. The simplest
function structure is:

function_name()
{ statement1;
statement2;
🡫
statementN;
}

Since it is only the main() that is actually executed by the compiler, a function must first be called before it
can be used. Prior to this calling, that function must first be declared. A function declaration, which is also
known as a function prototype, whose general syntax is written below, is needed only when that function is
defined after main(). This is done so that the compiler can ascertain that such function exists. When a
function is called, the same syntax as the function prototype is followed.

function_name();

In some instances, a called function may also receive data from the function calling it. By default,
values of the identifiers being passed are actually sent. This is known as passing by value. This passing by
value is done successively in such a way that the value of the first identifier being sent is stored in the first
receiving variable, the value of the next identifier being sent is stored in the second receiving variable, and
so on. In return, the called function may or may not send back data. It must be understood, however, that a
function may receive as many values as possible but can only send back a maximum of one value. The
values that will be passed to the function’s formal parameter, which are also known as arguments or actual
parameter must then be specified when the function is called.

function_name ( var1, var2, …, varN );

On the receiving side, the called function must then be able to receive the values of the actual
parameter passed to it by individually declaring these values, also referred to as formal parameters in the
function header line.

returned_type function_name ( var1_type var1_name, …, varN_type varN_name )

When a function has finished its task and needs to go back to the calling function, the return keyword is
used. This return statement causes an immediate exit from the function being called and eventually causes
program execution to return to the calling function.

return;

It can also be used to return a value or a result of an expression, which is evaluated first and then
converted to the data type declared in the function header line.

return (value);
return (expression);
If a function need not return any value to the calling function, the keyword void is used instead of a
particular data type. Similarly, if the called function is not to receive any value, void can be written inside the
parentheses or nothing at all.

void example (void)


void example ()

void example (int x)

int example (void)


int example ()

Function prototypes of functions with parameters must be almost identical, although the variable names
in the prototype may be omitted without affecting the program. It should also be noted that function
prototypes are terminated with semicolon while function header lines are not.

4. Resources:
Computer with DevC/C++ Application

5. Procedure:

Program 1. Cube of a number.

1. Open the DevC/C++ application ad create new source file.


2. Type the code as shown in Sample Program5.1.
3. Save the code as CProgra14.cpp.
4. Compile and run the program.

Sample Program 5.1 Cube of a number


5. Write the output in the box provided below.

6. What is the significant of variable x in the program?_______________________________________


__________________________________________________________________________________
____________________________________________________________________________________
_____________________________________________________________________________________

Program 2. Function of Exponents.

1. Open the DevC/C++ application and create new source file.


2. Type the code as shown in Sample Program5.2.
3. Save the code as CProgra15.cpp.
4. Use power ( ) as a function prototype.
5. Compile and run the program.

Sample Program 5.2


6. Write the output in the box provided below.

Sample output:

Program 3. Arithmetic in Function.

1. Open the DevC/C++ application and create new source file.


2. Save the program as CProgram16.c
3. Ask the user to input three numbers. Use variables num1 as the first number to input, num2 as the
second and num3 as the third number to input. Consider num1 as the least significant digit and num3 as the
most significant digit. (e.g. num1-num2-num3).
4. Perform operation such as sum, difference, product, quotient and modulus.
5. Use only function prototype for following operation: add( ) for sum, sub( ) for difference, mul( ) for product,
div( ) for quotient and mod( ) for modulus.
6. Compile and run the program
7. Write the program code and program output in the box provided below.
Program code Program Output
6. Data/Program Analysis

1. What are the advantages of using functions in creating a program?

2. From Sample Program 5.1, move the power ( ) function and place it after main( ) function. Observe and
explain the output.
_____________________________________________________________________________________
_

3. Explain why does the variable x and y declared outside the function.

4. From Sample Program of line 6, replace the statement by “return(x*x*x,x*x,x)”. What will be the output of
the program, assume input value for num=9. Explain.
5. From Sample Program 5.2, move the statements of line 18 and place it to the statement in between of
curly brace “{“ and a statement “printf(“Enter base:”);” of line 14. What will be the output of the program and
explain?

7. SUPPLEMENTARY PROBLEMS
Direction: Save the program as ACT5a.C, ACTA5b.C, ACT5c.C and ACT5d.C in the local disk. . Put a
comment and type the programmer’s name, course and section and date performed on the first five lines of
C editor.

1. Make and run a program that will display the average of scores entered by a user. The program
should ask how many times the user will enter scores.

Sample Output:
How many scores? 5

85

76

84

90

86

The average score is 84.2

2. Make and run a program that will allow the user to enter currency in peso. And by passing it, a
separate function must compute for its equivalent exchange rate but will not return any value. The
user must have options (dollar, pound, yen) to what currency it will be converted. Use passing by
reference.
Sample Output:

What currency do you have? Dollar


Conversion:
How much? 100
1 USD = 0.505561 Pounds
You have 100 USD you want this to convert in?
Yen

This is equivalent to 10470.7 Yen


1 USD = 104.707 Yen

1 USD = 42.3422 Peso

3. Write a function name rightTriangle ( ) that accepts the lengths of two sides of a right triangle as the
arguments a and b. The subroutine should determine and return the hypotenuse c, of the right triangle.

4. Write a function named year() that has an integer parameter named yr and four integer reference
parameters named month, week, day, and hour. The function is to convert the past number of years into a
number of months, weeks, days and hours. Use passing by reference. Include this function in a working
program.
Sample Output:
Conversion: Enter a number of years: 1
1 year = 12 months
1 year is 12 months, 48 weeks, 365 days and 8760
1 week = 7 days
hours
1 month = 4 weeks

9. Assessment (Rubric for Laboratory Performance):


Laboratory Activity No. 6
ARRAYS
Course Code: CS100A Program:
Course Title: Fundamentals of Programming and Algorithm Date Performed:
Section: Date Submitted:
Name: Instructor:

1. Objective:
This activity aims the students to implement array in constructing C program.
2. Intended Learning Outcomes (ILOs):
The students should be able to
1. Demonstrate the process of accessing and storing data in an Array.
2. Create a C program using different forms of Array.
3. Discussion
An array is a number of fixed-size variables that is referenced by a common name. The variables are referenced
by an index. In C/C++ programming, the starting index is zero (0). An array name is just like any variable, which can
store different values without having to use different variable names. The general syntax for array declaration is:

data_type array_name [array_size];

Arrays usually have a size that is constant.


int const num = 9;
int score[num];

Array elements can also be initialized using any of the following formats:
data_type array_name[array_size]={value1,value2, …, valueN};
data_type array_name[]={value1,value2, …, valueN};

Thus, the example above can be initialized as:


int const num= 9;
int score[num]={70,75,80,85,90,95,100,80,90};

When array elements are initialized, the size of the array can be omitted. If this is the case, the computer will
allot the number of the initializes as the size of the array. When the initializing list is less than that of the declared
array size, the values of the elements that are not declared will be initially set to zero, 0.

int score[ ]= {70,75,80,85,90,95,100,80,90};

This array can be viewed in the computer as:

score[1] score[2] Score[3] Score[4] score[5] score[6] score[7] score[8]


score[0]

70 75 80 85 90 95 100 80 90

Arrays are also useful in forming tables or matrices. That can be implemented using a two-dimensional array.
As the name suggests, it has two dimensions: a row size and a column size.

data_type array_name [row_size] [column_size];

Elements of a two-dimensional array can be initialized using any of the following methods:

data_type array_name [row_size][column_size]={value1, value2, …, valueN };


data_type array_name [row size][column_size]={{elements of row1},
{elements of row2},
{elements of rowN}};

As with single-dimensional arrays, row and column sizes of a two-dimensional array need to be declared as
constants. Also, when initializing the elements of the two-dimensional array, the row size is optional but the column
size must be defined so that the compiler may know the limit of the array.

As an example, the succeeding initializations are valid and are all the same:

int matrix [ 2 ] [ 3 ] = { 8, 3, 1, 0, 5, 18 };
int matrix [ ] [ 3 ] = {8, 3, 1, 0, 5, 18 };
int matrix [ 2 ] [ 3 ] = { { 8, 3, 1 }, { 0, 5, 18 } };
int matrix [ ] [ 3 ] = { { 8, 3, 1 }, { 0, 5, 18 } };

That particular array can be viewed as:


col 1 col 2 col 3
row 1 8 3 1
row 2 0 5 18

In accessing individual array elements, the index or the respective row and column positions should be
identified. Any valid expression that leads to an integer can be used as a proper index of any array element. But
since the compiler does not perform bounds checking, it is the responsibility of the programmer to assure that any
element being accessed is within the range of the array size.

4. Resources:

Computer with DevC/C++ Application


5. Procedure:

Program 1. Maximum Number.


1. Open the DevC/C++ application ad create new source file.
2. Type the code as shown in Sample Program6.1.
3. Save the code as CProgra17.c.
6. Compile and run the program.
7. Write the program output in the box provided.

Program Output: Sample Program 6.1


7. What type of an Array does the program has? Explain._______________________________________

Program 2. Number Reverse.


1. Open the DevC/C++ application and create
new source file.
2. Type the code as shown in Sample
Program6.2 into the editor.
3. Save the code as CProgram18.c.
6. Compile and run the Program.

Sample Output:

Part 3. Get the Determinants. Write and run a program that allows the user to computes for the
determinants and the roots of unknown variables.
1. Open the DevC/C++ Application and create new file.
2. Save the program as CProgram19.c.
3. Use det( ) as function prototype in getting the determinants and detX( ) in getting the root of X, detY( ) in
getting the root of Y and detZ( ) in getting the roots of Z from the given equation below. USE array name:
arrayDet[ ][ ].

4. Display the equation into 4x4 matrixes.


5. Compute for the determinants.
6. Use the determinants to compute for the roots of variable X,Y and Z.
7. Compile and run the program.
8. Write the program code and the program output in the box provided below.
6. Data and Results:
1. From Sample Program 6.1 line 10, consider input numbers 25.56, 35.54, 45.34, 65.67 and 20.66. What
will be the value of variable max? Explain.

2. From Sample Program 6.1 line 14, consider input numbers 25, 35, 45, 65 and 20. What will be the value
of variable max if the storage of an array is val[2]? Explain.
4. What happens if the number of initializes is more than the size of the array?

3. From Sample Program 6.2, add a function prototype that will get the average of the input number after
displaying the reverse of the number. Write the program code and program output below.

7. SUPPLEMENTARY PROBLEMS
Direction: Save the program as ACT6a.C, ACT6b.C and ACT6c.C in the local disk. . Put a comment and
type the programmer’s name, course and section and date performed on the first five lines of C editor.

1. Using one-dimensional array, make and run a program that will allow a user to input 15 numbers
and sort them from highest to lowest.

Sample Output:
What are the 20 numbers?

5 9 6 1 0 2 11 15 16 78 52 3 4 7 10 8 12 0 13 14

The highest to lowest order will be:


0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 78 52

2. Make and run a program that will let the user to input two numbers. Display a multiplication table
using the entered numbers as its size. Set maximum size to 20.

Sample Output

3. Make and run a program that will allow the 2 users that will act as a player to participate in XOX game
Sample Output:
ROW
1 2 3
/COLUMN
1 X O O
2 O X X
3 O X X
ROW COLUMN
Player 1 (X) – 3 3
Player 2 (0) – 3 1
Player 1 with X symbol wins!

9. Assessment (Rubric for Laboratory Performance):


Laboratory Activity No. 7
STRING
Course Code: CS100A Program:
Course Title: Fundamentals of Programming and Algorithm Date Performed:
Section: Date Submitted:
Name: Instructor:

1. Objective:
This activity aims to illustrate the behavioural set of characters in an Array.
2. Intended Learning Outcomes (ILOs):
The students should be able to:
1. Demonstrate the use of manipulating characters in an array.
2. Apply different functions of string in constructing C program.

3. Discussion
A string is a number of characters treated as a single variable. It is more specifically an array (one-dimensional)
of characters.
char string_name [size_of_string];

Strings can be initialized using any of the formats below:


char string_name[size_of_string]={‘char1’,‘char2’, …,‘charN’};
char string_name[]={‘char1’,‘char2’, …,‘charN’};
char string_name[size_of_string ]=“string”;
char string_name[]=“string”;
char string_name[size_of_string];

As an example:
char mystr[11]={“Computer 1”};

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [ 10 ]
C o m p u t E R 1 \0

Observing the string structure after the last element ‘1’, we can see that there is a null value present, which
denotes the end of the string. Accessing the elements of a string is the same as accessing the elements of an array,
where we just call the field or element number of the desired value. A simple example is if we want to output all upper
case letters.
cout<<mystr[0];
cout<<mystr[6];

The code will output the letters corresponding to the element number, which will display C and e.

Pre-Defined Functions for String Manipulation


There are more than 50 pre-defined functions in C++ language used to manipulate strings. These functions can
be used once the string.h is included. Following are some of the most commonly used string manipulator functions.

Returned
Function Syntax Data Description
Type
toupper( ) toupper(char) char Converts <char> to its uppercase value.
tolower( ) tolower(char) char Converts <char> to its lowercase value.
strlwr( ) strlwr(string) string Converts <string> to lowercase characters.
Strupr( )
strupr(string) string Converts <string> to uppercase characters.
Calculates length of <string>, excluding the null
Strlen( ) strlen(string) integer
character.
Copies <string> to <stringnew>, stopping after
strcpy(stringnew,
Strcpy( ) string the terminating null character has also been
string)
copied.
Strcat( ) strcat(stringnew, string Appends a copy of <string> to the end of
string) <stringnew>.
strncpy(str1, str2, Copy only a number of characters, given by
strncpy( ) string
size) <size>, of <str1> to <str2>.
Strset( ) strset(string, ’chr’) string Sets all characters in <string> to <chr>.
Compares the length of <str1> and <str2>.
strcmp(<str1>, str1 > str2 => (+) value
Strcmp( ) integer
<str2>) str1 < str2 => (-) value
str1 = str2 => 0
Reverses the characters in <string> except the
Strrev( ) strrev(string) string
null value at the last element of the string.

4. Resources:

Computer with DevC/C++ Application


5. Procedure:
Program 1. Playing with copy
1. Open the DevC/C++ application and create new source file.
2. Type the code as shown in Sample Program7.1.
3. Save the code as CProgram20.c.
4. Use strcpy ( ) function to copy a string from one variable to another.
5. Compile and run the program.

Sample Program 7.1 PLAYING WITH COPY


Expected output

6. Compare the output on the expected output as shown above.


7. Are the outputs the same?Yes/No._______
8. If no, what is/are the problem encountered?

9. Explain how the strcpy( ) implemented in the Sample program 7.1?

Program 2. Count your Word


1. Open the DevC/C++ application and create new source file.
2. Type the code as shown in Sample Program7.2.
3. Save the code as CProgram21.c.
4. Use strlen( ) function to count the string.
5. Compile and run the program.
6. Write the output in the box provided below.

Program 3. String COPY-CAT


1. Open the DevC/C++ application
and create new source file.
2. Type the code as shown in Sample
Program7.3.
3. Save the code as CProgram22.c.
4. Compile and run the program.
5. Write the output in the box provided below.

Program Output

6. Explain briefly the program flow of Sample Program 7.3

Program 4. Searching for String.


1. Open the DevC/C++ application and create new source file.
2. Type the code as shown in Sample Program7.4.
3. Save the code as CProgram23.c.
4. Compile and run the program.
5. Write the output in the box provided below.

6. In what scenario does the condition of line 10 of Sample Program 7.4 will become true? Explain.

6. Data and Results:

1. From Sample Program 7.1 line 10, change the statement by “printf(“%s”,str2);”. Observe the output and
explain.

2. From Sample Program 7.4, explain how the strncmp( ) used in the program.

3. What is the significance of using a string.h in the program?


4. How many loops does the line 11 and line 12 for variable ctr and lnctr respectively can display an output
of “hell”, if the input string is “hello”? Explain

7. SUPPLEMENTARY PROBLEMS
Direction: Save the program as ACT7a.C, ACT7b.C and ACT7c.C and ACT7d.c in the local disk. . Put a
comment and type the programmer’s name, course and section and date performed on the first five lines of
C editor.

1. Create and run a program that will accept not more than 30 characters and replace the entire lower
case letter to upper case and the entire upper case letter to lower case.
Sample Output:
The brown fox jumps over the lazy dog

THE BROWN FOX JUMPS OVER THE LAZY DOG

2. Create and run a program that will reverse the entered string without using the function strrev().
Sample Output:
Enter a word: Technology
The reverse of this word is ygolonhceT

3. Create and run a program that will accept a maximum of 40 characters and output this format to a word
without a space.
Sample Output:
The brown fox jumps over the lazy dog

Thebrownfoxjumpsoverthelazydog
4. Create and run a program that will search an academic program and its particular course and will display
the grades or standing of the student as shown in the scenario in table 7.2 below. Hint use strcmp( )

Table 7.2 Academic Records

PROGRAM COURSES GRADES STATUS


Civil Engineering Mechanics 3.0 Passed
Structure Analysis 4.0 Incomplete
Design 5.0 Failed
Computer Engineering Computer 5.0 Failed
Fundamentals
Computer Hardware 1.25 Passed
Data structure 2.75 Passed
Industrial Engineering Floor Plan 1.50 Passed
Management and 2.50 Passed
analysis
On-the-job Training 4.0 Incomplete
9. Assessment (Rubric for Laboratory Performance):

Installing Dev-C/C++
The software Dev-C++ 4.9.9.2 contains only a paltry 59MB, be sure that your computer has an enough
capacity before installing this.

1. From your storage device (E: ), double-click the DevC/ C++ folder, then double click the devcpp-
4.9.9.2_setup application(see figure l.l.1 and figure l.l.2).

2. Dev-C/C++ begins with a warning (shown in Figure l.1.2) that you’d better uninstall any older version
of Dev-C++ you may have hanging around, and then reboot and start over.
Figure l.1.1:
Getting started.
Dev CPP 4.9.9.2
Is the recent version of DevC/ C++
Environment. This is an
Open source software.

Figure l.1.2
:
You must uninstall
Earlier versions of
Dev-C/C++ before you
begin the installation
process.

1. If you don’t have to uninstall an old version of Dev-C/C++ just click ok and wait for a bit after loading is
done and skip to Step 5;if you do have to uninstall, abort the current installation process by closing the
Run window.
s

2. Okay, if you’re on this step, you’re uninstalling: Open the Dev-CPP folder on your C-drive (C: ) and
double-click the Uninstall.exe file there. (see figure l.3.1)

Figure l.3.1
Click the start then
click my computer, then go to C:,
then Click the Dev-Cpp folder.
3. Click Uninstall. Wait until the program will completely uninstall.(see figure l.4.1)

Figure l. 4.1
Once the dialogue box
appears. Click Yes
for removing all remaining configuration
files.

4. Once it is done for loading, the Installer Language dialogue box will appear then click ok for English
language.(see figure l.5.1)

Figure l. 5.1:

You can drop down for any other


language that you want.

6. Read the EULA (End-user Legal


Agreement) and then click I Agree if you
can live with its provisions. (see figure
l.6.1)
Figure l. 6.1

Clicking cancel means not installing this software


on your computer

7. Accept the default directory, c:\Dev-CPP.(see figure l.7.1)

Figure l. 7.1:

The default location


for the Dev-C++ environment is
provided.
Make sure that you have
an enough room for the
program, wherever you
decide to put it.

8. Click install
While the installation is going on, Dev-C++ presents a window that asks whether you want to install for all
users once it’s done copying files onto your hard drive. That question boils down to this: If someone else
logs on to your computer, do you want her or him to be able to execute Dev-C++? (The answer is “Yes” in
my case.)(see figure l. 8.1)

Figure l. 8.1:

The Dev-C++ installation


process unzips a large
number of mostly small files.

9. Click finish.(see figure l.9.1)

Figure l. 9.1

click finish to complete


the installation
then click yes for
the configuration
of the startup settings
of the environment.
2. DevC++Configuration
In setting the option is a procedure unto its self. You can change the theme, the environment and others In
Dev CPP.

1. Click the Next Button.

Figure 2.1.1
Select the language
that you want, in my
Case, I chose English.
Click the drop down
button, to select the
list of theme,
it consist of; new look,
Gnome and Blue
, click the preview to
view each theme. Other
option is the XP theme, .

2. After you set the environment of the DevC++, you will be ask if want to use the special features of
the DevC++. This features allows you to retrieve information such as finding the function and other
prototyping in the programming in c++. I chose “Yes, I want to use this feature”. If you select “No, I
prefer to use Dev C++ without it” proceed to step 4.
Figure 2.2.1

You can select “No , I prefer


To use DevC++ without it”
Because you can add this
Feature once you have
Successfully installed the
DevC++ on your editor option.

3. In this step you are accepting to use


the additional feature of the DevC+ +.
Click “Yes, create the cache now” to
have automatically used the
standard location in DevC++ for the additional feature then click next and wait until the loading is finish.

Figure 2.3.1

You can select the “ Use this


Directory instead of the
Standard one:”then click Next
if you want to
Locate the additional feature
on other location.
You can Select “No, do not create
The cache” then click Next
Then proceed to step 4.
.

4. Click the check box to finish the configuration.

Figure 2.4.1

The software program


Will be open, the dialogue
Box for the tips will appear,
Click close to start
Creating program.
3. Creating a your First C program.
“Hello World”
In this section, you create a simple program that will only display the statement “Hello
World”. First , encode the C++ code then save it as FirstProgram.CPP and the convert the
C++ code to an executable program.
1. Open the Bloodshed Dev C++.
2. Click Start➪Programs➪Bloodshed Dev-C++➪Dev-C++ to start up the Dev-C++ tool.
3. Choose File➪New➪Source File.
Dev C++ opens a white blank window wherein you can enter the new code.
4. Enter exactly the following code.

#include<stdio.h>
#include<conio.h>
main()
{printf(”Hello World”);
getch();
}

5. Save the code. Choose File➪Save as then type FirstProgram then choose .CPP as file type.
6. To run the program or convert it to an executable program choose the Execute ➪Compile or
press F9 for shortcut key to run the program. Then the compile progress dialogue box will
appear(see figure 3.6.1), afterward the executable file will be display usually in a black
window(FirstProgram.exe)(see figure 3.6.2)
Figure 3.6.1
The user is rewarded
With a simple done
Message on the status
If the program is
error free

Figure 3.6.2

this is an exucutable
display for the program
FirstProgram.CPP, the data
Type for this is .exe.

Dev C++ generates a message if it finds any type of error in your C++ Code. The message at the bottom of
the window has more than three messages if theres an error and it include the specific C++ code that has

You might also like