COMP PROG 1 - Notes (1)
COMP PROG 1 - Notes (1)
COMPUTER
An electronic device that accepts data from the user, processes it, produces results,
displays them to the users, and stores the results for future usage.
DATA
Collection of unorganized facts and figures and does not provide any further
information regarding patterns, context, etc.
Data means “unstructured facts and figures”. SOFTWARE
INFORMATION Set of instructions that drives computer to do stipulated tasks is called a program.
Software Instructions – programmed in a computer language, translated into
Is a structured data = organized meaningful and processed data. machine language, and executed by computer.
Computer – to process the data and convert into information. Categorized into two types ---
_________________________________________________________________________ System Software
Application Software
The procedure of developing the detailed instructions for the computer is called The steps include:
programming. It is a five step process namely: 1. Determine the appropriate programming language to use.
2. Code the program in the specific programming language decided on.
PROGRAM LOGIC FORMULATION LOOP LIMIT Composed of two parts; condition for termination
and loop name are written in the symbol indicating
Is a step-by-step development of a solution to a given problem. the start & the end of the loop respectively.
Actually, the most difficult part of solving a problem with a computer.
After you come up with a method of solution, it is a routine to translate your method into TERMINAL SYMBOL This oval, which contains either the word start or
the required language, for example C language and any other programming languages. the word stop, indicates the starting and stopping
point in the flowchart. A flowchart can only have
one starting point but it may have many possible
stopping points.
There are two most commonly used tools that will be of great help for you to formulate a
better solution. These are the flowchart and algorithm.
INPUT/OUTPUT SYMBOL This parallelogram is used for INPUT and OUTPUT
instruction. INPUT means to enter data into a
computer or to use the computer to read the
FLOWCHART available data from magnetic disk. OUTPUT
means to display the result of compilation or
condition of the given solution.
ARROWHEADS/ FLOW LINES Arrows are used to direct the flow of the flowchart.
It shows the flow of the solution.
PREPARATION SYMBOL
TYPES OF FLOWCHARTS
SYSTEM FLOWCHART
Indicates a flowchart for a targeted system as a whole.
A System Flowchart Example:
PROGRAM FLOWCHART
Used to describe processing procedures based on detailed analysis.
*System Flowchart will be discussed thoroughly on System Analysis and Design
FLOWCHART DEVELOPMENT
The steps that comprise a flowchart must be organize in an orderly,
understandable and clear manner so that the program that implements this
flowchart is similarly in an orderly, understandable and clear manner.
STRUCTURED FLOWCHART
- Orderly, understandable and clear solution.
- A design using the three most basic methods of control.
- The basic methods will be our guide to produce a correct structured flowchart
necessary to prepare a correct program.
1. SEQUENTIAL
- Steps are performed in a strictly sequential manner.
- Each step being executed exactly once.
- Simplest method of control.
- Easy to develop and understand.
Figure 1.2 Shows flowchart on how to determine the product of the three numbers.
2. SELECTION STRUCTURE
- One of the several alternative actions is selected and executed.
- It involves the use of decision based on the given condition.
- Uses a decision block or the diamond-shaped block.
- Alternative action will be presented by a processing block.
Figure 1.3 Flowchart that determines if the average of the students is “PASSING” or
“FAILING”
Figure 1.4 Shows the flowchart that will be determine the positive and negative number. 3. Repetition Structure
- One or more steps is performed repeatedly. Figure 1.6 Shows the flowchart for the printing of numbers from 1-10.
Figure 1.5 Shows the flowchart for the printing of all odd numbers from 1-10.
These three structures appear to be very simple, but in fact they are sufficiently powerful
that any flowchart can be constructed using them.
_________________________________________________________________________
ALGORITHM 3. Certain keywords that are common in high-level language may be used.
- For example: Read or enter to indicate input operation; display, print and
Set or series of instructions for carrying a particular task.
write for output operation.
Also a procedure to produce the required output from the given input.
4. Indentation is used to set of certain key blocks of instructions.
Similar with a paragraph that expresses a single thought.
Uses ENGLISH LANGUAGE.
Also known as PSEUDO CODE. STRUCTURE OF AN ALGORITHM
Can be displayed in a structure diagram that shows the various that must be
performed and their relation to one another.
ALGORITHM DEVELOPMENT
These diagrams are especially useful in describing algorithms for more complex problem.
The steps that comprise an algorithm are similar with flowchart.
Must be organized in orderly, understandable, and clear manner so that the program
that implements this algorithm is similarly orderly, understandable and clear manner. Examples in Flowchart Development using the Three Basic Control Structures:
The three basic methods of control used in a structured flowchart are also
1. SEQUENTIAL STRUCTURE
applicable in structured algorithm.
Figure 1.7 Algorithm that shows the printing of the sum.
1. SEQUENTIAL
2. SELECTION
3. REPETITION
PSEUDO CODE
A mixture of language and symbols, terms and other feature commonly used one or
more high-level languages.
High-level Languages
- Programs used by the computer. Figure 1.8 Algorithm that shows how to determine the product of three numbers.
Typically, the common features of various pseudo codes that appear in textbook are the
following:
1. The usual computer symbols are used for arithmetic operations are:
- “+” for ADDITION
- “-“ for SUBTRACTION
- ” * “ for MULTIPLICATION
- “ / “ for DIVISION
2. Symbolic names (identifiers) are used to represent quantities being processed
by the algorithm.
2. SELECTION STRUCTURE
Figure 1.9 Algorithm that shows how to determine the positive and negative number.
3. REPETITION STRUCTURE
Figure 1.10 Algorithm that shows the printing of numbers from 1-10
UNIT 2: BASIC PROGRAM STRUCTURE (C LANGUAGE)
DEFINITION OF TERMS
OVERVIEW
Source Code
- Good language to introduce yourself to programming world.
- A simple procedural language. - Text of a program that a user can read.
- Well suited as an introduction to coding: It’s a tried-and-true language.
Interpreter
- Allows you to understand computing processes at a deep level.
- Reads source code one at a time then perform instructions from that line.
INTRODUCTION Compiler
- General-purpose programming language that features economy of expression, - Reads entire source code then converts it into object code.
modern control flow and data structures and a rich set of operations.
- Called as “system programming language” as it is useful for writing compilers and Object Code
operating systems. - Translation of source code in a form that can be executed by computer.
- A structured programming language, considered as high-level language because it
allows programmers to concentrate on the problems at hand. Compile Time
Library
- Collection of pre-written. - This version of C is significantly extended from the “base bone” language of Ritchie’s
specifications. The extension included enhancements which make the Turbo C
Semantic/Run
compatible with the new proposed and ANSI Standard.
- Time errors are detected during execution-time. 3. Compiler
- Used to convert source code into binary code or machine code.
PROGRAMMING PROCESS 4. Debugger
- Used for testing program and locating programming errors.
- Names used to reference variables, functions, labels, and other user-defined objects.
- Sequence of letters, numbers, or underscore.
a. Can vary from one to several characters. First character must be a letter or an
underscore with subsequent characters being letters, numbers, or underscore. Must
not have space or hyphen.
b. Must consist of alphabetic characters, digits, and underscores only.
Turbo C c. First 63 characters are significant. Identifiers are case sensitive.
- Version of C language. d. Cannot be the same as Turbo C keyword and should not have the same name as a
- Complete environment to create, test, and run programs. function.
COMPONENTS OF TURBO C
1. Editor
- Used to create program source code.
2. Extended C Language
- Occupies 4 bytes.
- Can include exponent ranging from 3.4 E to -38 to 3.4 E +38.
2.3. DOUBLE
2.4. CHAR
- Single letter, digit, punction mark, or control symbols enclosed within single quotation
mark.
- Can be assigned with an integer value between -128 and +127.
- Byte size: 16, Minimum Value: 0, Minimum Value: 65536. 3. VARIABLES – LANGUAGE ELEMENT OF C
2.2. FLOAT - Are identifiers which can be assigned a value within a program.
- Has 32 valid characters namely: letters, digits, and underscore.
- Consist of optional sign + or -, followed by one or more digit, a decimal point, and or
one or more further digits.
3.1. VARIABLE DECLARATION
3.3. GLOBAL AND LOCAL VARIABLES
- When we create variables, declaration gives them a symbolic name, and the
definition reserves memory for them. 3.3.1. GLOBAL VARIABLE
data-type variable-name; one variable declared (a) - Initialized at the start of the program, initialized to zero if no other initializer is
int a; specified.
- Constant int.
- Used at the beginning of the program, also used for declaring constants.
4.3. FLOATING POINT CONSTANT
#define variable value
- Constant numbers with decimal.
5.2. TYPE MODIFIERS
const float a = float;
- Used to alter meaning of the base type to more precisely fit the needs of various
situation.
4.4. STRING CONSTANT - Includes signed, unsigned, long, and short.
- Constant string.
- This declaration is introduced by the word #define follow by a constant name and its
value.
ASSIGNMENT STATEMENT
5. MODIFIERS
- Process of assigning values to variables.
5.1. ACCESS MODIFIERS - Equal sign is the assignment operator.
5.1.1. CONST
- Variables declared under this modifier cannot be changed during the execution of the HOW TO ASSIGN VALUES TO VARIABLES
program.
1. Variable must be on left side of equal sign while value must be on the right side
const data-type variable = value; of equal sign.
2. Any expression can be assigned on variable.
3. Expressions are not allowed on the left side of the assignment operator.
follows its operand, C uses the operands value before incrementing or decrementing
it.
ASSIGNING VALUES TO VARIABLES
Types of Arithmetic Operators
a. Unary
- Require only a single operand.
b. Binary
- Require two operands.
c. Combined
- Is a shorthand operation.
OPERATORS
1. Arithmetic Operators
4. Ternary Operators
5. Comma Operators
- Used to string together several expressions.
- Evaluates the operands from left to right but the result is of the right-most operand.
EXPRESSIONS
UNIT 3: INPUT / OUTPUT STATEMENTS PROGRAM STRUCTURE Example: stdio.h, string.h, and math.h
OVERVIEW Function Prototype - introduced by ANSI C. Are available in the standard header files
in the standard library.
● Input and output terminology is referring to the communication between a
computer program and its user. ⇒ stdio.h should be included whenever the function printf() and scanf() is used.
● Input – is the user giving something to the program. ⇒ Both are passed as list of arguments that can be thought of as control string and
● Output – is the program giving something to the user. other arguments.
INTERACTIVE INPUT / OUTPUT Control String - is a string and may contain conversion specifications or formats.
3.1 C – Compiler Pre-Processor #include<stdio.h> - It causes a copy of the standard header file stdio.h to be
included in the code when compilation occurs.
The lines that begin with a # are called preprocessing directives.
3.2 Standard Input / Output (stdio.h)
Line 4 Beginning the body of the function – This opening brace marks the start
Field – it is where the argument is printed.
of the statements that make up the function. The function definition is
Field Width – the number of characters in its field. It can be specified in a format as ended with a closing brace, } .
integer occurring between the percent character (%) and the conversion character.
Line 5 A declaration statement – announces that we will be using variables
Example: called c1, c2, c3 and these variables will be of char(character) type. All
statements in C program should be terminated with a semicolon.
printf(“%c%3c%5c\n”, ‘A’, ‘B’, ‘C’);
Line 6 - 8 A declaration statement – announces that we will be using a variable
Will Print: called i of int(integer) type. And declares the use of float and double types.
A _ _ B _ _ _ _ C Line 9 A print statement – prints the phrase within the quotes.
Address Operator “&” Line 10 An input statement – this reads the values of c1, c2, c3, i, x, and y and
⇒ The expression &x is read as “the address of x”. store them in their corresponding addresses.
⇒ When the keyboard is used to input values into a program, a sequence of characters is When reading in numbers, scanf() will skip white space (blank, newlines,
typed, and it is this sequence of characters, called the input stream, that is received by and tabs), but when reading in a character, white space is not skipped.
the program.
Line 11 & 12 A print statement – this prints the values which the user may enter.
Other Functions of scanf()
Line 13 Function returns a value unless declared as void.
⇒ It can be used to convert a string of decimal digits into an integer value and to store the
value at the appropriate memory. Line 14 End of the function
⇒ It returns as an int the number of successful conversions accomplished. The function
printf() returns as an int the number of characters printed, or a negative value in case of
an error. The Escape Sequence
Explanation
Line 1 Including another file – tells the computer to include information found in
the file stdio.h
Line 2 A comment – You can use the symbols /* and **/ to enclose comments.
Comments are remarks to help clarify a program. They are intended for the
reader and are ignored by the computer.
\n newline
Output
Writes a string to the screen, followed by a newline. It can only output a string
puts() of characters. It cannot output numbers or do format conversion. Takes up
less space and runs faster.
putchar() Writes a string (character) to the screen.
global declaration/s;
function1()
local variables;
statement sequence;
}
function2()
local variables;
statement sequence;
main()
local variables;
statement sequence;
}
THE CONDITIONAL
STATEMENTS/CONSTRUCTS
SINGLE SELECTION CONSTRUCTS
The if statement
the code can be written to be more efficient and more understandable by using a
single if statement with a compound statement for its body.
ex.
ex.
An if-else statement can be used as the statement part of another if statement, this is
what you call nested if
Syntax:
switch(expression)
break;
case constant expression:
break;
[default
statement;]
Action:
The switch expression may be any expression which evaluates to an int, conditional,
char or double value. The case list consists of constants whose type matches that of
the switch expression.
NOTE: Case list cannot include variables or expressions. After the statements for
a case, a keyword break maybe used.
Break keyword - means at that point, execution should jump to the end of
the switch statement.
Note the optional switch constant default. This switch constant can be used to specify
an action to be taken if the value of the switch expression does not match any of the
listed values.
ex. This program will prompt the user to input an integer number which will determine
the corresponding month in words
ex. Program that allow user to enter integers until he/she enters a negative number or a
zero
- causes the current iteration of the loop to stop and causes the next iteration of the loop
to begin immediately. The continue statement may only occur inside for,
while, and do loops.
Scanf Syntax:
Printf statement;
Syntax: pow
NESTED FOR LOOP double pow( double, double)
Calling syntax
double x = sqrt (25.00)
FUNCTIONS
Output
sqrt(25) = 5.00
1. strcpy(s1, s2);
Copies string s2 into string s1.
log
2. strcat(s1, s2);
Concatenates string s2 onto the end of string s1. double log(double)
calling syntax
double x = floor (6.24)
output
floor(6.24) = 6
ceil
double ceil(double)
Calling syntax
double x = ceil (6.64)
Output
ceil (6.64) = 7
abs
double abs(do+uble)
calling syntax
double x = abs (-512)
output
abs (-345) = 345
STRING/ARRAY 1. strcpy(s1, s2);
Copies string s2 into string s1.
- Strings are actually one-dimensional array of characters terminated by a null
character ‘\0’.
2. strcat(s1, s2);
- This a null-terminated string contains the characters that comprise the string followed
Concatenates string s2 onto the end of string s1.
by a null.
The following declaration and initialization create a string consisting of the word “Hello”. To 3. strlen(s1);
hold the null character at the end of the array, the size of the character array containing the Returns the length of string s1.
string is one more than the number of characters in the world “Hello.”
4. strcmps(s1, s2);
char greeting [6] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’ }; returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
if you follow the rule of array initialization then you can write the above statements as follows:
5. strchr(s1, ch);
char greeting [ ] = “Hello”; Returns a substring of string beginning at the first occurrence of character c up to the
end of string
6. strrev(string)
Reverses all characters except the null terminator in the string.
MATH FUNCTIONS
pow (Power)
- the pow function is used to calculate the power of the base raised to the power of
exponent.
- It accepts two double values as arguments which are the base and exponents
numbers and it returns a single double integer which is base to the power of
exponent.
double floor(double)
calling syntax
double x = floor (6.24)
output
floor(6.24) = 6
FUNCTION A function definition in C programming consists of a function header and a function
body. Here are all the parts of a function –
- is a group of statements that together perform a task.
Return Type – a function may return a value. The return_type is the data
- Every C program has at least one function, which is main(), and all the most trivial
type of the value the function returns. Some functions perform the desired
programs can define additional functions.
operations without returning a value. In this case, the return_type is the void.
- You can divide up your code into separate functions.
- Dividing the code is up to the programmer, but logically the division is such that each
Function Name – this is the actual name of the function. The function name
function performs a specific task.
and the parameter list together constitute the function signature.
- A function can also be referred as a method or a sub-routine or a procedure
FUNCTION DEFINITION
- A function definition provides the actual body of the function.
return_type function_name ( parameter list )
{
body of the function
}
FUNCTION CALL
- Function execution in the main program.
- To use a function, you will have to call that function to perform the defined task.
- When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
- To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned
value.
FUNCTION ARGUMENTS
Formal Parameters
Call Parameters
TWO TYPES OF FUNCTION BY DEFINITION
LOCAL VARIABLE
- Variables are declared inside a function or block are called local variables. They
can be used only by statements that are inside that function or block of code.
- Local variables are not known to functions outside their own.
- This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
C-RECURSION GLOBAL VARIABLES
- are defined outside a function, usually on top of the program.
Recursion is the process of repeating items in a self-similar way a function to call
- Global variables hold their values throughout the lifetime of your program and they
itself.
can be accessed inside any of the functions defined for the program.
- need to be careful to define an exit condition from the function, otherwise it will go
into an infinite loop.
- Can be accessed by any function. That is, global variable is available for use
throughout your entire program after its declaration.
ARRAY The General Form – One-dimensional array
- Is a fixed-size, sequenced collection of elements of the same data type. storage class data-type arrayname [expression];
Elements – refer to list of variables of the same data type that can be grouped into Example:
an array
int ccmit[5];
Ex. char bscs[30];
int a, b, c, d, e, f, g, h, i, j; there are 10 variables of type integer that can be float bsit[20];
grouped into an array. double ITCS[12];
float a, b, c, d, e; there are 5 variables of type float that can be grouped into an
array;
char a, b, c, d, e; there are 5 variables of type character that can be grouped into
an array;
that character array is also known as STRING
- array is a sequence of data items that are the same type, that are indexible, and
that are stored contiguously.
- Are data type that is used to represent a large number of homogenous values.
- A sequenced collection, we can refer to the elements in the array as the first
element, the second element, and so forth until we get to the last element.
Each data element is accessed using an index.
- Array use loops to read and write the elements. INDEX = x[0], x[1], x[2], x[3], x[4]
x[3] = 0 y[0] = 0
y[0] = 0
INPUTTING VALUES
int scores[10];
int i; …
for(i=0; i<10; i++)
scanf(“%d”, &scores[i]);
INPUTTING VALUES
for(i=0; i<10; i++)
scores[i] = i * 2;
EXAMPLE:
EXAMPLE:
SEARCH Step 6: Print Element x Found at index i and go to step 8
- C program to implement search (searching algorithm), which is used to find whether Step 7: Print element not found
a number is present in an array and if it is present, then at what location it occurs.
Step 8: Exit
- It is also known as sequential search.
PSEUDOCODE
LINEAR SEARCH
procedure linear_search (list, value)
- Is a very simple search algorithm.
- A sequential search is made over all items one by one. for each item in the list
- Every item is checked and if a match is found then that particular item is returned,
otherwise the search continues till the end of the data collection. if match item == value
return the item’s location
end if
end for
end procedure
BINARY SEARCH
- Is a fast search algorithm with run-time complexity of O(log n).
- This search algorithm works on the principle of divide and conquer.
- For this algorithm to work properly, the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the collection.
- If a match occurs, then the index of item is returned.
ALGORITHM - If the middle item is greater than the item, then the item is searched in the sub-array
Linear Search (Array A, Value x) to the left of the middle item.
- Otherwise, the item is searched for in the sub-array to the right of the middle item.
Step 1; Set i to 1 - This process continues on the sub-array as well until the size of the subarray.
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: set i to i + 1
Step 5: Go to Step 2
HOW BINARY SEARCH WORKS?
- For a binary search to work, it is mandatory for the target array to be sorted. We shall
learn the process of binary search with a pictorial example.
- The following is our sorted array and let us assume that we need to search the
location of value 31 using binary search.