You are on page 1of 40

Exercise # ___ Title: Algorithm

Pageno. Date:___

Objectives: At the End of this exercise you should be able to understand the meaning of algorithm as a step of in problem solving. And to know the basic terms, operations and control structures in constructing an algorithm. . Background Algorithm is a set of instructions that specify a sequence of operations to be carried out in order to solve a specific problem. Character Sets Alphabetic character any symbol that characterized as letter (a-z, A-Z). Numeric characters any symbol that represents a number (digits 0-9 and its combinations.

Special Characters symbols that is not a letter or number (!@#$%*()_<?>/ etc). Data Items Data items provide information about the object to which the program refers in general term. Data items are represented in the computer memory by one or more bits. Two divisions: variable and constant. Variables Variable is named data item, the value of which may change during the program execution. Constant A constant is a data item that the value remains unchanged throughout the computation based on an algorithm and is therefore, specified by its value, which is used directly in an algorithm or in a program. 1. Literal constant constant whose value is a number intended for computation. It also known as numeric constant. 2. Non-Literal constant constant whose value is not intended for computation. It can be any group of characters enclosed between quotation marks. Identifier is a word or sequence of characters that forms the name of an object. It refers to any name given by the programmer. It can be program name, variable name, label name, array name and others. Rules in naming identifier

1. 2. 3. 4.

The first character must be alphabetic (a z, A Z, or _). The next characters may be a letter, number, underscore and or dash. There should be no space between symbols The length of the identifier should not be greater than eight characters.

Data type is an interpretation applied to a set of bits representing a given data item. It indicates the characteristics of the values that may be stored in the associated variable. 1. An integer is any signed or unsigned number with no fractional parts. Ex. -11, 11, 1982 2. A real number is any signed or unsigned number with an integer and fractional part. Ex. 1.25, -5.18, 9.20 3. A character is any alphabetic, number or special symbol. A collection of characters is called string. 4. The logical (Boolean) is a data type with a value of either true or false. Operators Arithmetic Operators Operator Action + ^ Subtraction, unary minus Addition Exponentiation ++ Relational Operators Operator Meaning > Greater than >= < Greater than or equal Less than

Operator Action * / Multiplication Division Decrement Increment

Operator <= == !=

Meaning Less than or equal Equal Not equal

Logical Operators Operator Meaning && AND || ! OR NOT

A F F T T

AND B X F T F T F F F T

A F F T T

OR B F T F T

NOT X F F F T A F T X T F

Conversion of Algebraic Expressions to programming notation

Algebraic Expressions 1. 3 + 5(3-9) 10 9 2. 5 + 2 73 7 3. 4 1 63 4. 4A (5 K ) 2 5. 6 + BC

Programming Notation 2 + 5 * (3-9) 5 + 10 / 2 9 (7 + 3) / (4 1) -7 (6 + 3)^(1/2) / (4*A) 6 + ((5 + K)^2))/(B + C)

Hierarchy of Operations 1. Expressions inside the parenthesis 2. Exponentiation (if occur consecutively deal from left to right) 3. Multiplication / Division (left to right) 4. Addition / Subtraction (left to right) 5. Relational Operator 6. Logical Operator Example: 1. X = (5 + 1^3) + 9^(1/2) 5+1 +3 6+3 X= 9 2. X = NOT(5+7*3=36)OR (2+1=3) AND (NOT(2+3=5) X = NOT(5+21=36)OR (3=3) AND (NOT(5=5)) X = NOT(26=36)OR TRUE AND (NOT (TRUE)) X = NOT(FALSE) OR TRUE AND FALSE X = TRUE OR TRUE AND FALSE X = TRUE OR FALSE X = TRUE

Exercise no. 1: Algorirthm NAME: ____________________________________

SECTION: _______________ DATE: __________________

I. Write VALID if the identifier is valid. Otherwise write INVALID. Strictly no erasures. 1. 2. 3. 4. 5. obiwan Average 123pass total allowance leo@yahoo.com 6. X + 7 7. Exam#2 8. UST 9. ICSA 10. Y=5

II. Conversion of Expression to Programming Notation

Y 5 Y 2 2. Y = 4X + 2X + 12 3. P is 75 less 5% of B 4. The sum of N and X is J 5. B is twice the value of E 6. 75% of E is B 7. B is half the value of E 8. The product of M and E is B 9. P is E less B 10. The sum of the square of T and K is L 11. The square of the sum of T and K is B 12. The n root of the sum of M and 5 is W 13. N is the cube-root of T Y 14. H = Y + 1T 15. P = N + 5 N Y
1. X = 5 -

III. True or False 1. 2. 3. 4. 5. Y = True AND True OR False AND True OR True A = (False AND NOT False OR True) AND NOT(False OR True) X = ((True AND False OR True) AND True) OR False) AND True B = True AND NOT False OR ((False AND False) OR True) Z = False OR True OR NOT(True OR True OR False AND False)

IV. Perform the indicated operations 1. X = Not(5*2 + 25 < 31) AND (2^3 = 6) OR (3^2 > 2^3)

2. Y = (5^3 = 3^5) AND NOT(100/10 + 5 = 100/15) OR (15/3 + 2 < 6)

3. N = (5^3 < 3^5) OR (200/10 + 5 = 200/15) OR NOT (15/3+2 < 6)

Exercise # ___ Title: Flowcharting

Pageno. Date:___

Objectives: At the End of this exercise you should be able to understand the basic flowcharting symbols and its functions. And to be able to convert an algorithm into flowchart. Background Flowchart is the graphical representation of an algorithm; the predefined graphic symbols are used to indicate the various operations and the flow. Flowcharting symbols commonly used Terminal Box Used to represent the beginning (Start) or the end (End) of a task Flowline Used to connect symbols and indicate the flow of logic. Initialization Box Use to declare beginning value Input/Output Box Used for input and output operations, such as reading and printing. The data to be read or printed are described inside. Processing Used for arithmetic and data-manipulation operations. The instructions are listed inside the symbol. Decision Box Used for any logic or comparison operations. The path chosen depends on whether the answer to a question is yes or no. or True or False On-page Connector Allows flowchart to be continued on the same page. Off-page Connector Allows the continuation on other pages.

Flowchart Operations Start / End START END Signifies the start or end of the flowchart

Variable declaration / Constant declaration X = 11 PI = 3.1416

Input Operation INPUT A, B or READ A, B

Output Operation OUTPUT A, B or WRITE A, B

Processing SUM = x + 2 Y = SUM + A

Conditional or Decision X>Y

SEQUENTIAL FLOWCHART Sequential is very simple design. It does not involve conditional or iterative processing. Design in this type is normally from top to bottom or left to right. Sample Problem: Design a flowchart that will accept two numbers and display the computed sum and product. Solution. START A=0 B=0 Sum = 0, product = 0 INPUT A, B Sum = A + B Product = A + B DISPLAY Sum, Product

END

Exercise no. 2: Sequential Flowchart NAME: ____________________________________

SECTION: _______________ DATE: __________________

1. Create a program flowchart that converts the input dollar to its peso exchange rate equivalent. Assume that the present exchange rate is 51.50 pesos against the dollar. Then display the peso equivalent exchange rate.

2. Design a program flowchart to find the circumference of a circle. Use the formula: C=2r, where is approximately equivalent to 3.1416.

3. Write a program flowchart that exchanges the value of two variable : x and y. The output must be: the value of variable y will become the value of variable x, and vise versa.

Exercise # ___ Title: Selection / Conditional Flowcharting

Pageno. Date:___

Objectives: At the End of this exercise you should be able to understand the uses of decision box and its functions. And to be able to convert an conditional algorithm into flowchart. Background CONDITIONAL STATEMENTS Conditional statement is being implemented in flowchart through the use of decision symbol. Program execution may take two different paths, the true and the false. The path is taken depends upon the condition. Single Sided Alternative One side has an action; the other side has nothing (null case) Sample Structure:

Double / Dual Sided Alternative Each of the 2 paths you can follow contains instructions Sample Structure:

Multiple Alternative Has more than one condition, each of which leads to a specific task or set of instructions. Sample Structure:

Sample Problem: Design a flowchart that will accept an integer input and will determine whether the value is greater than zero, less than zero or equal to zero. If the value is equal to zero write 0, if more than 0 write G otherwise write L.

START

X=0

INPUT X NO X=0 YES WRITE 0 WRITE L X>0 NO YES

WRITE G

END

Exercise no. 3: Conditional Flowchart NAME: ____________________________________

SECTION: _______________ DATE: __________________

1. Write a program flowchart that determines if the input letter is a VOWEL or CONSONANT. The vowels are: A E I O U. Your program must be able to handle a capital or small input letter.

2. Create a program flowchart for the Air Force to label an aircraft as military or civilian. The program is to be given the planes observed speed in km/h and its estimated length in meters. For Planes traveling in excess of 1100 km/h, and longer than 52 meters, you should label them as civilian aircraft, and shorter such as 500 km/h and 20 meters as military aircraft. For planes traveling at more slower speeds, you will issue an Its a bird message.

Exercise # ___ Title: Case Structure Flowchart

Pageno. Date:___

Objectives: At the End of this exercise you should be able to understand the case structure flowchart and its functions. And to be able to convert a case structure algorithm into flowchart. Background CASE STRUCTURE A more convenient way to handle multiple selections or multiple alternative. Examples of usage: menu options testing one variable that can have a few different values

Sample Structure:

Exercise no. 4: Case Structure Flowchart NAME: ____________________________________

SECTION: _______________ DATE: __________________

1. Write a program flowchart that determines if the input letter is a VOWEL or CONSONANT. The vowels are: A E I O U. Your program must be able to handle a capital or small input letter.

2. Create a program flowchart for the Air Force to label an aircraft as military or civilian. The program is to be given the planes observed speed in km/h and its estimated length in meters. For Planes traveling in excess of 1100 km/h, and longer than 52 meters, you should label them as civilian aircraft, and shorter such as 500 km/h and 20 meters as military aircraft. For planes traveling at more slower speeds, you will issue an Its a bird message.

3. Write a program flowchart that accepts a number and outputs its equivalent in words.(use extra sheet of paper if needed) Sample input/output dialogue: Enter a number : 1380 One thousand three hundred eighty Take note that the maximum input number is 3000.

Exercise # ___ Title: Iterative / Repetitive Flowchart

Pageno. Date:___

Objectives: At the End of this exercise you should be able to understand iteration or repetitive structure flowchart and its functions. And to be able to convert an iterative algorithm into flowchart. Background ITERATIVE STATEMENTS The loop mechanism causes repetition of a sequence of statement/s based on the given condition/s. Most of the time, when a body of the loop is executed, the value of at least one variable changed. Therefore, most loop mechanism has cumulative effect. Counter a variable used to determine number of loops Accumulator a variable use to store results of an iteration Sample structure:

Sample Problem: Design a flowchart that will print HI five times. START

X=0 Y=HI

OUTPUT Y X=X + 1 NO X<5 YES END

Exercise no. 5: Iterative Flowchart NAME: ____________________________________

SECTION: _______________ DATE: __________________

1. Write a program flowchart which produces the given sequence nos. (in alternate arrangement) using looping statements: 1, 5, 2, 4, 3, 3, 4, 2, 5, 1

2. Create a program flowchart that reverses the input number n. Formulate an equation to come up with the answer: Sample input/output dialogue: Enter a number : 1238 Reverse number : 8321 Input data Output value

3. Create a program flowchart that generates and displays the Fibonacci sequence numbers of n(as input). In Fibonacci, the current third number is the sum of two previous numbers. Sample input/output dialogue: Enter a no. 9 Fibonacci series : 1 1 2 3 5 8 13 21 34

Exercise # ___ Title: Turbo C/C++ Environment and I/O Statement

Pageno. Date:___

Objectives: At the End of this exercise you should be able to understand the environment of Turbo C/C++ environment and to be able to create and run program generated from flowchart. And to be able to understand the basic C/C++ structure and its syntax. Background Turbo C Environment Editor used to create program source code. Compiler used to convert source code into machine language. Debugger used for testing a program and locating programming errors. Run-time the capability to run a program within the Turbo C environment User-Interface the various features of Turbo C are integrated into a single program, which allows you to smoothly process from source code entry to compilation, to debugging, to running without leaving the Turbo C environment. The Basic Types Type Character Integer Floating point Double floating point Long Integer Valueless Type char int long int float double

Keyword char int float double long int Void Minimum Range 127 to 127 or 0 to 255 32,767 to 32,767 2,147,483,647 to 2,147,483,647 6 digits of precision 10 digits of precision

Escape Character \n \t \f \b \0 \ \% \a \\ \r \ \v

Meaning (name of character) Insert a new line Horizontal Tab Formfeed Backspace Null character Single quote Percent symbol Alert Backslash Carriage return Double quote Vertical tab

Identifiers An identifier is composed of sequence of letters, digits and a special character (underscore) Identifiers are defined be the programmer, and should be descriptive An identifier consists of as many as 127 characters The first character must be a letter or an underscore (_). Characters after the first letter can be letters, digits and underscores. Identifier are case sensitive; Example VALID INDENTIFIER a123 _Leonid BILLING Receipt XYZ789 month_and_year INVALID INDENTIFIER 123 - does not start with a letter month and year - uses illegal space character scanf - uses predefined identifier

Variables A variable is an identifier which can be assigned a value within a program. Store a value that can be changed. Constants Constants are identifiers that can store a value that cannot be changed It is advisable to use capital letters with underscores between each word to differentiate them from variables Keywords

A pre-defined words of the language. Keywords are also known as reserved words Keywords are words reserved by programming language for expressing various statements and constructs

Examples of C keywords char int long double float short switch if break case else while goto void do

Operators and Expressions An operator is a symbol that represents an operation to be performed. Expressions may either be arithmetic or logical, but the result would be an integer or a real value. Arithmetic Operators OPERATOR * / % + ++ -FUNCTION Multiplication Division Modulus Addition Subtraction Increment Decrement SAMPLE C=A*B C=A/B C=A%B C=A+B C=AB C++ or ++C C- - or - - C

Relational and Logical Operators Refer to page 2, Exercise 1

C/C++ Program Structure <comment/s> <header file/s> <constant definition/s> <function definition/s> <main program> <variable declaration/s> <statement/s> Header File Format: #include<header file> Header File stdio.h conio.h math.h string.h Routine Declared Defines standard input output tells C how to perform or execute input and output functions. Declares various functions used in calling the DOS console I/O routines, such as clrscr(), getch(), gotoxy(x,y) and others Declares math routines such as sin(), cos( )and sqrt(). All string routines are defined in this file.

main function Format: main( ) { /*variable declaration/s*/ /*statement/s*/ } Variable Declarations Format: <data_type> <identifier> Example: int num; char letter; float average; double area;

Input and Output Functions Output function Output means writing information to the screen. Standard Output (stdout) printf function Format printf(<format string>[,<identifier-list>]); Ex. printf(Hello %s, word1); printf(Hello Wolrd); Input

Format Specification %c %d %f %ld %lf %s

Meaning Character Integer Float Long integer Double String

function Input means reading values from the keyboard. Need to press the <Enter> key to transfer your input to C for processing scanf function

Format scanf(<format string> , &<identifier-list>); Ex. scanf(%s, &name); scanf(%d %d %d, &quiz1, &quiz2, &quiz3);

Sample problem: 1. Create a program to display the string Hello World /*helloworld*/ #include <stdio.h> #include <conio.h> main( ) { clrscr(); printf(HELLO WORLD !); getch(); }

2. Create a program to calculate the sum of two floating point number and display the result with 2 digit precision. #include <stdio.h> #include <conio.h> main() { clrscr(); float x, y, sum; printf(\nEnter First no:); scanf(%f,&x); printf(\nEnter second no:); scanf(%f,&x); sum = x + y; printf(The sum of x and y is %.2f., sum); getch(); }

Exercise no. 6: Turbo C/C++ Environment and I/O statements NAME: ____________________________________ SECTION: _______________ DATE: __________________ 1. Create a program that converts the input Celsius degree temperature to its Fahrenheit degree temperature. Derive the formula from C = 5/9 * (F-32)

2. Create a program to find the radius of a circle. Derive the formula from: C=2r, where is approximately equivalent to 3.1416. 3.

4. Write a program flowchart that exchanges the value of two variable : x and y. The output must be: the value of variable y will become the value of variable x, and vise versa.

Exercise # ___ Title: Turbo C/C++ Conditional Statements

Pageno. Date:___

Objectives: At the End of this exercise you should be able to understand the Turbo C/C++ Conditional statement syntax and to be able to create a program using conditional statements. Background Conditional Statements Format Single Statement Option 1 if(condition) statement; Option 2 if(condition) statement; else statement; Example 1: if( age > 18) printf(\nQualified to vote); Example 2: if( age >= 18) printf(\nQualified to vote); else printf(\nToo Young to vote); Example 3: if( age >= 18) && (age <=100) printf(\nQualified to vote); else if( age>=1) && (age <=17) printf(\nToo Young to vote); else printf(\nOut of range);

Option 3 if(condition) statement; else if(condition1) statement; . . . else if(conditionn) statement; else statement;

Exercise no. 7: Turbo C/C++ Conditional statements NAME: ____________________________________ SECTION: _______________ DATE: __________________ 1. Write a program that determines if the input letter is a VOWEL or CONSONANT. The vowels are: A E I O U. Your program must be able to handle a capital or small input letter.

2. Create a program flowchart for the Air Force to label an aircraft as military or civilian. The program is to be given the planes observed speed in km/h and its estimated length in meters. For Planes traveling in excess of 1100 km/h, and longer than 52 meters, you should label them as civilian aircraft, and shorter such as 500 km/h and 20 meters as military aircraft. For planes traveling at more slower speeds, you will issue an Its a bird message.

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

Exercise # ___ Title: Turbo C/C++ Switch Case Statements

Pageno. Date:___

Objectives: At the End of this exercise you should be able to understand the Turbo C/C++ Switch Case statement syntax and to be able to create a program using switch case statements. Background Switch Case Statement The switch case statement is a multi-way decision that tests whether an expression matches one of a number of constant integer or character values and branches accordingly. If the case matches the expression value, execution starts at the case and end with a break statement. Format: switch(expression) case const-value1: statement1; statement; break; case const-value2: statement1; statement; break; . . . case const-valuen: statement1; statement; break; default: statements;

Sample Problem 1: Write a program that will ask the user to input two numbers and let him/her choose what to compute, such as 1]sum 2]diff 3]product. Solution: #include<stdio.h> #include<conio.h> main() { int a,b; int sum,diff,product; int choice; clrscr() printf(\nInput 2 nos:); scanf(%d%d,&a,&b); clrscr(); printf(\n1]sum\n2]difference\n3]product); printf(\nchoice:); scanf(%d,&choice); switch(choice) { case 1: sum = a + b; printf(\nThe sum is %d,sum); break; case 2: diff = a - b; printf(\nThe diff is %d,diff); break; case 3: product = a * b; printf(\nThe product is %d,product); break; } getch(); }

Sample Problem 2: Write a program that will ask the user to input two numbers and let him/her choose what to compute, such as A]sum B]diff C]product. Solution: #include<stdio.h> #include<conio.h> main() { int a,b; int sum,diff,product; char choice; clrscr() printf(\nInput 2 nos:); scanf(%d%d,&a,&b); clrscr(); printf(\n1]sum\n2]difference\n3]product); printf(\nchoice:); scanf(%c,&choice); choice = getchar(); switch(choice) { case a: case A: sum = a + b; printf(\nThe sum is %d,sum); break; case b case B: diff = a - b; printf(\nThe diff is %d,diff); break; case c case C: product = a * b; printf(\nThe product is %d,product); break; } getch(); }

Exercise no. 7: Turbo C/C++ Conditional statements NAME: ____________________________________ SECTION: _______________ DATE: __________________ 1. Write a program that determines if the input letter is a VOWEL or CONSONANT. The vowels are: A E I O U. Your program must be able to handle a capital or small input letter.

2. Create a program for the Air Force to label an aircraft as military or civilian. The program is to be given the planes observed speed in km/h and its estimated length in meters. For Planes traveling in excess of 1100 km/h, and longer than 52 meters, you should label them as civilian aircraft, and shorter such as 500 km/h and 20 meters as military aircraft. For planes traveling at more slower speeds, you will issue an Its a bird message.

4. Write a program that accepts a number and outputs its equivalent in words.(use extra sheet of paper if needed) Sample input/output dialogue: Enter a number : 1380 One thousand three hundred eighty Take note that the maximum input number is 3000.

Exercise # ___ Title: Turbo C/C++ Switch Case Statements

Pageno. Date:___

Objectives: At the End of this exercise you should be able to understand the Turbo C/C++ Iterative statements (for loop, while loop, and do-while loop) syntax and to be able to create a program using the different looping statements. Background for loop Format Option 1 for(initialization; condition; incrementation/decrementation) statement; Option 2 (compounded statements) for(initialization; condition; incrementation/decrementation) { statement1; statementn; } while loop Format initialization; while(condition) { statement; incrementation/decrementation; } do -- while loop Format initialization; do { statement; incrementation/decrementation; } while(condition);

Sample problem: Write a program that calculate and produces these two columns sequence numbers using the three looping statements: Sequence nos. 1 2 3 4 5 Solution using for loop for(ctr = 1; ctr<=5; ctr++) { printf(\n%d\t%d,ctr,ctr*ctr); } Solution using while loop num=1; while(num<=5) { printf(\n%d\t%d,num,num*num); num++; } Solution using do --- while loop num=1; do { printf(\n%d\t%d,num,num*num); num++; } while(num<=5); Squared 1 4 9 16 25

Exercise no. 8: Turbo C/C++ Iterative statements NAME: ____________________________________

SECTION: _______________ DATE: __________________

1. Write a program flowchart which produces the given sequence nos. (in alternate arrangement) using looping statements (using for loop) 1, 5, 2, 4, 3, 3, 4, 2, 5, 1

2. Create a program flowchart that reverses the input number n. Formulate an equation to come up with the answer: (using while loop and do while) Sample input/output dialogue: Enter a number : 1238 Reverse number : 8321 Input data Output value

3. Create a program flowchart that generates and displays the Fibonacci sequence numbers of n(as input). In Fibonacci, the current third number is the sum of two previous numbers. (use for loop) Sample input/output dialogue: Enter a no. 9 Fibonacci series : 1 1 2 3 5 8 13 21 34