You are on page 1of 12

1ST SEMESTER: MIDTERMS EXAMINATION

CP1 – COMPUTER PROGRAMMING (COMP 002)


Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

SYLLABUS PROGRAM/SOFTWARE
1. Programming Concepts ● The list of instructions that the computer must follow to
2. Basic Program Structure be able to process data into information.
3. Using Conditional Constructs ● These instructions consist of statements written in a
specific programming language. When a program is
written, we are basically solving a problem. To solve a
PROGRAMMING CONCEPTS problem, we need to use our mind power or logic to
develop the detailed instructions.
COMPUTER
PROGRAMMING
● An electronic device that accepts data, processes it,
produces results, displays them to the users, and ● The procedure of developing the detailed
stores the results for future usage. instructions for the computer.

DATA FIVE-STEP PROCESS OF PROGRAMMING


● A collection of unorganized facts & figures and does
1. Define the problem.
not provide any further information regarding patterns,
2. Design the solution/program.
context, etc. DDCTD
3. Code the program.
● Unstructured facts and figures. 4. Test the program.
5. Document the program.
INFORMATION
● A structured data i.e. organized meaningful and Define the problem.
processed data. ● The problem definition step means that there should be
● To process the data and convert into information, a clear understanding of the problem. It requires
computer is used. performing the following:

HARDWARE 1. Specify program objectives and identify the users of


the program.
● Mechanical device that makes up computer.
2. Specify the output requirements.
● Consists of interconnected electronic devices that we 3. Specify the input requirements.
can use to control computer’s operation, input, and 4. Specify processing requirements.
output. 5. Study feasibility of implementing the program.
● Computer hardware is a collection of several 6. Document the analysis.
components working together. Some parts are
essential, and others are added advantages. Design the solution/program.
● Examples of hardware are CPU, keyboard, mouse, hard ● In designing the program, the following steps are done:
disk, Basic Input Output System (BIOS), etc.
1. Determine the program logic through top-down
SOFTWARE approach and modularization, using hierarchy
● Software instructions are programmed in a computer charts.
language, translated into machine language, and 2. Design details using pseudo-code and /or
executed by computer. Software can be categorized into flowcharts.
two types – System and Application Software. 3. Test design with a structural walkthrough.
o Program - A set of instructions that drives Structural walkthrough consists of reviewing process
computer to do stipulated tasks. with other programmers and system analyst and
scrutinize (“walkthrough”) the programmer’s work.
TYPES OF SOFTWARE
Code the program.
Operates directly on hardware ● Program coding is the step which translates the logic of
devices of computer. It provides a the program based on the pseudo-code (algorithm) or
platform to run an application. It flowcharts into a high-level programming language
provides and supports user using the syntax and semantics of the specific language.
System
functionality. ● Pseudo-code/flowcharts → programming languages
Software
● This step include:
Examples of system software include
operating systems such as 1. Determine the appropriate programming language to
Windows, Linux, Unix, etc. use.
2. Code the program in the specific programming
Designed for benefit of users to language decided on.
perform one or more tasks.
Application Test the program.
Software Examples of application software
include Microsoft Word, Excel, ● Program testing consists of desk checking,
PowerPoint, Oracle, etc. debugging, and running real data to make sure that
the program works.
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

● Desk checking - reading through or checking the Indicates only


program manually to ensure that it is free from errors Sequential sequentially accessible
and the logic works. Access data such as those on
● Debugging - detecting, locating, and removing errors in Storage magnetic tapes &
the computer program. cassette tapes.

Indicates directly
TYPES OF ERROR Direct
accessible data, such as
Access
those on magnetic disks
Can be typographical error or Storage
Syntax error & floppy disks.
incorrect format of the statement used.
Indicates data on media
Caused by incorrect use of control
Logic error Documents human beings can read.
structures.

Document the program. Indicates data on any


medium that displays
● Documenting the program consists of the written
Display information used by
descriptions of what the program is all about and how to
human beings, such as
use it.
monitor.
● The documentation should prepare for the users,
operators, and the programmers. The steps are as Composed of two parts;
follows: condition for termination
and loop name are
1. Write user documentation. This is the manual that is Loop Limit written in the symbol
prepared to help the user use the programs. indicating the start & the
2. Write operator documentation. This manual gives end of the loop
the computer operator information on what to do when respectively.
the program flashes an error message.
3. Write program documentation. The program This oval, which contains
documentation consists of the testing of the whole either the word ‘START’
programs. This documentation helps train the new or the word ‘STOP’,
programmers to maintain existing system. indicates the starting and
Terminal stopping point in the
Maintenance - keeping the programs in working conditions, Symbol flowchart. A flowchart
error free and up to date. can only have one
starting point, but it may
PROGRAM LOGIC FORMULATION have many possible
● A step-by-step development of a solution to a given stopping points.
problem.
● This is the most difficult part of solving a problem with a This parallelogram is
computer. used for INPUT and
● It is a routine to translate your method into the OUTPUT instruction.
required language, for example C language and any INPUT means to enter
other programming languages. data into a computer or
Input/Output to use the computer to
TOOLS USED IN THE DEVELOPMENT Symbol read the available data
from magnetic disk.
OUTPUT means to
FLOWCHART
display the result of
● It consists of boxes with different shapes that contain compilation or condition
simple statements or sentence commonly called of the given solution.
instructions and connected together by lines.
This rectangle is used for
any data processing
FLOWCHART SYMBOLS
Processing operations for which
Symbol requirements of the
Symbol Meaning problem are usually done
here.
Indicates Data
Data This diamond-shaped
symbol contains a
Decision condition. If the condition
Indicates data stored in Symbol is true, the marked path
Stored Data formats suitable for TRUE is to be followed.
processing If the condition is false,
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

SELECTION STRUCTURE
the marked path FALSE
is to be followed. ● One of several alternative actions is selected and
executed.
Arrows are used to direct ● It involves the use of decision based on the given
Arrowheads/ the flow of the flowchart. condition. It uses decision block or the diamond-
Flow lines It shows the flow of the shaped block. Alternative action will be represented
solution. by a processing block.
● Examples of selection structure in flowchart:
It is used as a
continuation symbol of a
Connector
flowchart. It shows the
flow of the solution.

It is used to initialize
Initialization/ variables not explicitly
Preparation defined in the input but a
Symbol requirement in the
production of the output.

TYPES OF FLOWCHARTS

Indicated a flowchart for a targeted


System flowchart
system as a whole.

Used to describe processing


Program flowchart procedures based on detailed REPETITION STRUCTURE
analysis.
● One or more steps is performed repeatedly.
● Uses loop in performing the program.
FLOWCHART DEVELOPMENT ● Examples of repetition structure in flowchart:
A Structured Flowchart requires the systematic organization
of its steps to ensure clarity and understanding in both the
flowchart itself and the corresponding program
implementation.

Structured flowcharts are designed using the three most


basic methods of control.

THREE MOST BASIC METHODS OF CONTROL

SEQUENTIAL STRUCTURE
● Steps are performed in a strictly sequential manner;
each step being executed exactly once. This is the
simplest method of control. It is easy to develop and
understand.
● Example of sequential structure in flowchart:

ALGORITHM
● A set or series of instruction for carrying a task.
● It is also a procedure to produce the required output from
the given input.
● It is similar with a paragraph that expresses a single
thought. It uses English language. It is also known as
pseudo code.

ALGORITHM DEVELOPMENT

An algorithm, akin to a flowchart, requires organized and clear


steps for a coherent program implementation. The three
fundamental control methods in a structured flowchart also
apply to a structured algorithm.
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

PSEUDO CODE
BASIC PROGRAM STRUCTURE
● A mixture of language and symbols, terms and other INTRODUCTION TO C
features commonly used one or more high-level
languages.
C LANGUAGE
● High-level languages are programs used by the
computer. ● A general-purpose programming language which
features economy of expression, modern control flow
Typically, the common features of various pseudo codes that and data structures and a rich set of operations.
appear in textbook are the following: ● is has been called as “system programming language”
because it is useful for writing compilers and operating
1. The usual computer symbols are used for arithmetic systems.
operations: “+” for addition, “-“ for subtraction, “*” for ● A structured programming language. It is considered a
multiplication, and “/” for division. high- level language because it allows the programmers
2. Symbolic names (identifiers) are used to represent to concentrate on the problems at hand.
quantities being processed by the algorithm.
3. Certain keywords that are common in high-level language
may be used, for example, read or enter to indicate input HISTORY OF C
operation; display, print and write for output operations.
4. Indentation is used to set off certain key blocks of Basic Combined Programming Language (BCPL)
instructions. is developed by Martin Richards in 1967.
1967
This language is turn strongly influenced the
Three basic control structures in algorithm. development of the next language –B.

1. Sequential structure B is written and developed by Ken Thompson in


1970 for the first UNIX system on the DEC
1970
PDP-7. Both BCPL and B are “typeless”
languages.

C is an expansion of B. A programming language


designed by Dennis Ritchie in 1972 at AT&T Bell
Laboratories. C was originally designed for and
2. Selection structure 1972
implemented on the UNIX operating system on the
DEC PDP-II. The new C added something that B
did not have data types.

Turbo C is a version of C developed by Borland


International Corporation in 1987. This version is
designed to run on various microcomputer
1987
systems, namely those which use the operating
system MS-DOS, the operating system for the IBM
Personal Computers and Compatibles.

3. Repetition structure
INTERPRETER
ALGORITHM PrintOddNumbers ● Reads the source code of your program one line at a
A -> 1, B -> 10 time and performs the specific instructions contained in
INPUT A, B that line.
WHILE A <= B DO
IF A is odd THEN
OUTPUT A COMPILER
END IF ● Reads the entire program and converts it into object
A -> A + 1 code-the form that can be directly executed by the
END WHILE
computer.
END PrintOddNumbers

COMPILE TIME
● Events that occur during the compilation process.

OBJECT CODE
● A translation of the program source code in a form that
can be directly executed by the computer. It is also
called the binary code and machine code.
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

THE PROGRAMMING PROCESS Used for testing program and locating


Debugger
programming errors.

Time Environment is the capability for running


Run
programs within the Turbo C system.

The various features of Turbo C are


integrated into a single program which allows
User you to smoothly proceed from source code
Interface entry to compilation to debugging to running
without never leaving the Turbo C
environment.

THE LANGUAGE ELEMENT OF C

IDENTIFIERS

IDENTIFIERS
● Names that are used to reference variables, functions,
labels, and various other user-defined object.
● Sequence of letters, digits and the special character ‘_’,
which is called an underscore.
SOURCE CODE
● The text of a program that a user can read. Rules in naming identifiers:
● Commonly thought of as a program.
1. An identifier in Turbo C can vary from one to several
characters; the first character must be a letter or an
RUN TIME underscore with subsequent characters being letters,
● Refers to the events that occur while the program is numbers, or the underscore. It may not have a space
executing. or a hyphen.
2. Must consist only of alphabetic characters, digits, or
LIBRARY underscores.
● Collection of pre-written. 3. The first 63 characters of an identifier name are
significant. In C, upper-and lower case are treated as
● Ex. #include <stdio.h> different and distinct from one another.
Example: Sname, Sname, and sName are three separate
SYNTAX ERRORS identifiers
● Detected during execution-time.
4. An identifier may not be the same as a Turbo C
SEMANTIC/RUN keyword, and it should not have the same name as a
function.
● Time errors are detected during execution time.
DATA TYPES
COMPONENTS OF TURBO C
int variable
Turbo C is more than just a version of the C language.
Rather, it includes a complete environment in which to create, ● Whole number consisting of an optional sign (+ or -)
test, and run programs. This programming environment followed by a sequence of digit. It cannot contain
consists of several components: commas.
● Variables of this type are often used for controlling loops
and conditional statements.
TURBO C COMPONENTS
TYPES OF INTEGERS
Editor Used to create program source code.
Type Byte size Min. value Max. value
This version of C is significantly extended
from the “base bone” language of Ritchie’s Short int 2 -32768 +32767
Extended C specifications. This extension includes
language enhancement which make the Turbo C Int 4 -2147483648 +2147483647
compatible with the new proposed and ANSI
Standard. Long int 4 -2147483648 +2147483647

Used to convert source code into Unsigned int 16 0 65536


Compiler
machine/binary code.
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

float variable Several ways to initialize a variable:


● Consists of an optional sign (+ or -), followed by one or
1. By assigning an assignment statement (=). may be used
more digits, a decimal point, and or one or more further
to assign values to variables of any types.
digits.
● It occupies 4 bytes. It can include an optional exponent Syntax: variable-name = expression;
ranging from 3.4 E to -38 to 3.4 E +38. Example:
x = -1; Assignment statement (=)
double (double precision) Chl = ‘A’; is NOT the same with
● A special float which can store more significant digits Bb = ‘H’; equal expression (==).
and have a longer exponent. It occupies 8 bytes in the Age = ‘18’;
memory.
● It ranges from 1.7 E – 308 to 1.7 E +308. 2. By using function scanf.

char variable Syntax: scanf(“%<variable>”, &<variable_name>);


● A single letter, digit, punctuation mark or control symbol Example: %d – int
recognized by the computer. %f – float
● Written enclosed within single quotation marks, but scanf(“%d”, &x); %c – single char
literals string is enclosed in double quotation marks. scanf(“%lf”, &y); %s – string of char
● A character may be assigned an integer value between %lf – double float
-128 and +127. Unsigned char data type may be
assigned an integer value from 0 to 255.
3. By assigning values during declaration.
Example:
char c; char B = ’*’; char a[30]; a = ”apple”; Example:
int x = 3;
void variable char y = ‘x’;
double a, b = 100.00;
● “no data type”, “no value”, “no parameters”.
● Three uses of void: GLOBAL AND LOCAL VARIABLES
o To declare explicitly a function as returning no value.
o To declare explicitly a function having no parameters.
GLOBAL VARIABLES
o To create generic pointers.
● Initialized only at the start of the program.
VARIABLES AND CONSTANT DECLARATIONS ● All global variables are initialized to zero (0) if no other
initializer is specified.
VARIABLES ● They are usually defined outside any function, usually at
● Identifiers which can be assigned a value within a the very top of the program.
program.
● It has 32 valid characters, and these are letters, digits, LOCAL VARIABLES
and underscore. ● Initialized each time the function in which they are
declared is entered.
VARIABLE DECLARATION ● Usually inside any block or function
● Each variable in program must be declared and defined. ● We also have to declare the local variable at the
In C, a declaration is used to name an object such as beginning of the given block.
variables.
● Definitions are used to create the object. When we CONSTANTS
create variables, the declaration gives them a symbolic ● Refers to fixed values that may not be altered by the
name and the definition reserves memory for them. program.
● NOTE: Turbo C constant can be any of the basic data
Syntax: Data-type <variable list>; types or known as Literal Constants.
Example:
int x, y, z;
/*list of variables are CHARACTER CONSTANTS
char a, b;
double s; separated by commas.*/ ● They are enclosed between single quotes.
float ave; ● Example: ‘a’, ‘%%’, ‘M’, ‘I’, ‘S’, ‘S’, ‘U’
char Sname[30];
INTEGER CONSTANTS
VARIABLE INITIALIZATION ● They are specified as number without fractional
● The process of assigning starting values to the components (whole numbers)
variables. ● Example: 10, -20, 143
● It is important to remember that variables are not
initialized automatically. When variable is defined, they
usually contain garbage, so we need to initialize them or
store data in them before accessing their values.
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

FLOATING-POINT CONSTANTS ASSIGNMENT STATEMENT


● Requires the use of decimal point followed by the
number’s fractional components. ASSIGNMENT
● Example: 80085.143, -3.14, 69.420 ● The process of assigning a value to a variable.
● In C, we use the equal sign (=) as the assignment
STRING/LITERAL STRING CONSTANTS operator.
● Consists of a phrase contained/enclosed within double
quotes. How to assign values to variables?
● String constants are used in printf statements to
introduce text messages into a program. 1. The variable must be on the left side of the equal
sign. Values must be on the right side of the equal
● Example: “miss”, “na”, “kita”, “SOBRA” sign.
2. Any expression can be assigned on the variable.
DECLARED CONSTANTS 3. Expressions are not allowed on the left side of the
● Defined using a ‘#’ defined declaration at the beginning assignment operator. The assignment operator
of the program. directs C to assign to the variable on the left side the
● This declaration is introduced by the word <#define> value on the right side.
follow by a constant name and its value.
● Example: #define missyou 143, #define hi 100 ● Example: x = 55; sum = a + b; Name = “El”

ACCESS MODIFIERS OPERATORS


● C has two types of modifiers that are used to control the
way in which variables may be accessed or modified. OPERATOR
● A symbol that tells the compiler to perform specific
const mathematical, relational, or logical manipulations.
● Variables declared under this modifier can not be
changed during program execution. However, you may ARITHMETIC OPERATORS
give an initial value before the start of the program.
● A constant variable will receive its value either from an SYMBOL MEANING USE
explicit initialization or by some means dependent on the
hardware. * asterisk multiplication
● Syntax: const <data-type> variable = value;
● Example: const float version = 3.20; / Slash Division

+ Plus Addition
Using ‘#define’
● It is used at the beginning of the program. - Minus Subtraction
● Like const, #define is also used in declaring
constants. - Unary minus Negation
● Syntax: #define variable value
● Example: #define kiss 99 % Modulus Modulus division

NOTE: It is not necessary to tell a computer the type of a ++ Plus-plus Increment operator
declared constant. C determines the data type from the
assigned value. Remember that although, const and # -- Minus-minus Decrement operator
define defines a constant, the two modifiers have different
syntax. () Parenthesis parenthesis

TYPE MODIFIERS Important Notes:


MODIFIER 1. The operators +, -, *, and / all work the same way in
● Used to alter the meaning of the base type to fit the C as they do in the most computer languages.
needs of various situation more precisely. 2. When / is applied to an integer or character, any
remainder will be truncated (will only take the
● With the exception of the type void, the basic data type
whole number quotient).
may have more modifiers preceding them.
● Example: signed, short, unsigned, long Example: 11/2 = 5, 10/3 = 3, 13/6 = 2, 3/4 = 0

3. The modulus division operator, % yields the


remainder of an integer division. % cannot be used
on type float and double.

Example: 11 % 2 = 1, 5 % 3 = 2, 147 % 20 = 7
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

4. When an increment or decrement operator precedes


its operand, C performs the increment or decrement LONG HAND SHORTHAND
operation prior to using the operand’s value. If the
operator follows its operand, C uses the operand’s X = X + Y X+ = Y
value before incrementing or decrementing it.
X = X - Y X- = Y
Example: x = 10; x = 11; y = 11;
y = ++x; X = X * Y X* = Y

x = 10; x = 11; y = 10; X = X / Y X/ = Y


y = x++;
X = X % Y X% = Y
INCREMENT AND DECREMENT OPERATORS
● Increment is to add exactly one to the value of a RELATIONAL OPERATORS
variable.
o ++ increment operator
o x++ post-increment SYMBOL MEANING EXAMPLE
o ++x pre-increment
● Decrement is to subtract exactly one from the value of > Greater than a > b
a variable.
o -- decrement operator < Less than a < b

Example: >= Greater than or equal to ave >= 90


1. X = X + 1 or X+ = 1 is the same with X++
2. If Y = 10 and X = 3: <= Less than or equal to ave <= 90

Z = Y + X++ Z = Y + X; 13 == Equal to a == b
X = X + 1; 4
!= Not equal to a != 100
Z = Y + ++X X = X + 1; 4
Z = Y + X; 14
LOGICAL OPERATORS
Z = Y + X-- Z = Y + X; 13
X = X - 1; 2 SYMBOL MEANING EXAMPLE
Z = Y + --X X = X - 1; 2 && And N = 5 && 6
Z = Y + X; 12
|| Or 1 || 1
TYPES OF ARITHMETIC OPERATORS
! Not 5 != 6
UNARY OPERATORS
● Require only a single operand like unary plus and unary NOTE: In C, true is any value other than 0; false is 0
minus.
● Unary plus operator (+) – causes no change to the 1 True
quantity which follows.
● Unary minus operator (-) – causes the sign of the 0 False
following quantity to be changed.
● Example: Example:
Int x = 50 +x = 50; -x = -50 N = 10 ? 5 %% !(10 < 9) || 3 <= 4
1 && !(0) || 1
BINARY OPERATORS 1 && 1 || 1
● Requires two operands. N = 1
● Example:
+ (addition) X+Y TERNARY OPERATORS
x (multiplication) X * 3 ● Uses question mark and colon symbols.
● Expression1 is evaluated, if true, then expression2 is
COMBINED OPERATORS evaluated and become the value of the expression;
● C’s “shorthand” operation otherwise, expression3 is evaluated and its value
become the value of the expression
● Example:
X = X + Y; ● exp1 – conditional; exp2 – “if”; exp3 – “else”
X+ = Y (shorthand version) ● Syntax: Expression1? expression2: expression3;
● Example: x = 10, y = 5;
x > y? sum = x + y: diff = x – y;
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

COMMA OPERATORS ● An include file, is also called “header file”, can contain
● Used to string together several expressions. #define lines and other #include lines.
● Example: x = (y = 3, y++, y * 2); y = 10; ● By convention, the names of header files end in ‘.h’
y = 5; y = 4; y = 8; ● C system provides a number of standard header files.
x = (y = y – 5, 25/Y); ● Example: stdio.h, string.h, math.h
x = 5 o These files contain declarations of functions in the
Finally, x = 8 standard library, macros, structure templates, and
other programming elements that are commonly used.
EXPRESSIONS ● The preprocessing directive #include <stdio.h> causes
● Combinations of operators, constants, and variables. a copy of the standard header file stdio.h to be included
in the code when compilation occurs.
PRECEDENCE OF OPERATORS
STANDARD INPUT/OUTPUT
OPERATOR SYMBOLS USED Formatted Output

Arithmetic !, ++, --, *, /, %, +, - The printf() function


● This is used for output. The “f” in printf() function stands
Relational <, <=, >, >=, ==, != for “formatted”. Technically, these functions are not part
of the C Language, but rather are part of the C system.
Logical &&, || ● They exist in a library and available for use whenever a
C system resides.
Other Operators ?, :, =, +=, -=, *=, /= ● Syntax: printf(“%conversion specification”, variable);
● Example: x = 317; printf(“%d”, x);
USING CONDITIONAL STATEMENTS Function prototype
INPUT/OUTPUT STATEMENTS ● Improved kind of function declaration, introduced by
ANSI C.
C COMPILER PRE-PROCESSOR
● A statement that tells the compiler about the function's
● The use of #define and #include name, its return type, numbers and data types of its
● The compiler has a preprocessor built into it. Lines that parameters.
begin with a # are called preprocessing directives. ● Syntax: int heading (void);

The #define-line Control string


● This can occur anywhere in a program.
● A string that may contain conversion specifications or
● It affects only the lines in the file that come after it. formats.
● All #define are normally placed at the beginning of the ● A conversion specification begins with a percent
file. By convention, all identifiers that are to be changed character (%) and ends with a conversion character.
by the preprocessor are written in capital letters.
● Both printf() and scanf() are passed as list of arguments
● Example: #define LIMIT 100 that can be thought of as control string and other
#define PI 3.14 arguments.

Explanation:
Corresponding How the corresponding argument
● If the above lines occur in a file that is being compiled,
argument is printed
the preprocessor first changes all occurrences of the
identifier LIMIT to 100 and all occurrences of PI to
3.14159. %c As a character
● The identifier LIMIT and PI are called symbolic %d As a decimal integer
constants.
● The use of symbolic constants in a program makes it As a floating-point number in
more readable. More importantly, if a constant has been %e
scientific notation
defined symbolically by means of #define facility and
used throughout a program, it is easy to change later,
%f As a floating point
if necessary.
%lf As double
The #include
● This is commonly known as macro include. In the e-format of f-format
%g
● A preprocessing directive that causes a copy of the file whichever is shorter
to be included at this point in the file when compilation
occurs. A #include line can occur anywhere in a file, %s As a string
though it is typically at the head of the file.
● The quotes surrounding the name of the file are
Example: printf(“%c”, x);
necessary.
printf(“%s”, name);
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

field – the place where the argument is printed ENTER key is pressed.
● ENTER key is not stored byte is replaces be the null
field width – number of characters in its fields terminator.
The field width can be specified in a form at as an integer
getche()
occurring between the percent character (%) and the
conversion character. ● Reads the character without echo.
● Does not wait for carriage return or ENTER key.
Example: printf(“%c %3c %5c\n”, ‘A’, ‘B’, ‘C’);
Will print: A__B____C getch()
● Reads a character with echo.
Formatted Input
● Does not wait for carriage return or ENTER key.
The scanf() function
getchar()
● Analogous to printf(), but is used for input rather than
output. ● Reads a single individual character from the keyboard
● The first argument is a control string having formats that ● Waits for the carriage return or ENTER key.
corresponds to the various ways the characters in the
input stream to be interpreted. The other arguments are puts()
addresses. ● Writes a string to the screen, followed by a newline.
● Syntax: scanf(“%conversion specification”, &variable); ● It can only output a string of characters. It cannot output
● Example: scanf(“%d”, &x); numbers or do format conversion.
● Takes up less space and run faster.
scanf() can be used to convert a string of decimal digits
into an integer value and to store the value at the appropriate putchar()
place in memory:
● Writes a string (character) to the screen.

Conversion
Character
Valid characters in the input stream PROGRAM CONTROL STRUCTURE
%c To be a character CONTROL STRUCTURE
● Analyzes and chooses in which direction a program
%d To be a decimal integer flows based on certain parameters or conditions.
● Way to specify flow of control in programs.
%f To a floating-point number (float)
● Any algorithm or program can be clearer and more
understood if they use control structures as self-
%lf To a floating-point number (double)
contained modules.
%s To a string ● Three types of logic/flow of control:
o Sequence logic/flow
o Selection logic/conditional flow
ESCAPE SEQUENCE o Iteration logic/repetitive flow

FLOW OF CONTROL
Sequence Meaning
SEQUENTIAL FLOW OF CONTROL
\n Newline
● Statements in a program are normally executed one
\t Move to the next tab stop after another.
● Often it is desirable to alter the sequential flow of control
\xhh Insert char hh where hh is a hex. number to provide for a choice of action, or repetition of action.
● By means of if, if-else, and switch statement, a
\a Sound the bell selection among alternative actions is made.
● By means of while, for and do statements, interactive
\\ Insert a backslash character actions can be taken.

\” Insert a double quote RELATIONAL, EQUALITY, LOGICAL OPERATORS


\’ Insert a single quote
Symbol Meaning Expression

CONSOLE I/O (conio.h) RELATIONAL OPERATORS

gets() < Less than expr < expr


● This function takes the name of the string as an
arguments and reads characters from the keyboard until > Greater than expr > expr
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

CONDITIONAL STATEMENTS
<= Less than or equal to expr <= expr
The if statement
>= Greater than or equal to expr >= expr ● Form:
if (expr)
EQUALITY OPERATORS statement;
● Action: If expr is non-zero (true), then statement is
== Equal expr == expr executed; otherwise statement is skipped control
passes to the next statement.
!= Not equal expr != expr ● Example:
if (grade >= 90)
EQUALITY OPERATORS printf(“Congratulations!);
printf(“Your grade is %d\n”, grade);
! (unary) Negation !expr
Expressions in if statement is relational,
&& Logical “end” expr && expr logical, equality is permissible in any domain.

|| Logical “or” expr || expr The if-else statement


● Form:
if (expr)
RULES OR PRECEDENCE & ASSOCIATIVITY
statement;
else
Operators Associativity statement2;
● Action: If expr is non-zero (true), then statement1 is
+ (unary), - (unary), ++, --, ! Right to left executed and statement2 is skipped; if expr is 0 (false),
then statement1 is skipped and statement2 is executed.
*, /, % Left to right If both cases are 0, it will pass to the next statement.
● Example:
+, - Left to right if (a > b) {
b++;
<, <=, >, >= Left to right printf(“Value is smaller %d\n”, b);
}
==, != Left to right else
printf(“You got a bigger value %d\n”, a);
&& Left to right
An if-else statement can be used as the statement
|| Left to right part of another if statement, this is what you
call nested if.
=, +=, -=, *=, /=, etc. Right to left
● Example:
if(x == 50) {
• ! operator is unary (operator with only one operand). if(y >= 120) {
sum = x + y;
• All other relational, equality and logical operators
printf(“the sum of x and y is %d”, sum);
are binary.
}
o 0 or 0.0 or \0 or NULL = false.
else {
o Any non-zero = true.
diff = x – y;
COMPOUND STATEMENT printf(“the difference between x and y is %d”, diff);
}
● Series of declarations and statements surrounded by else {
braces. It is also known as block. printf(“Next time”);
● Purpose: }
o Grouping statements into an executable unit. The switch statement
o Achieve the desired flow of control in if, if-else, ● Form:
while, for, and switch statements. switch(expression) {
● Syntax: case <constant expression>:
compound_statement{{declaration}{statement}} statement;
break;
Example: case <constant expression>:
#include <stdio.h> statement;
#include <conio.h>
break;
void main()
{ default:
int a=1, b, c; statement;
{ ● Action: Evaluates to an int, conditional, char, or double
b=2; value.
c=3; - Case list: consists of constants whose type matches
}
that of the switch expression. (no var/expr)
getch();
}
1ST SEMESTER: MIDTERMS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

- Break: at the point, execution should jump to the end The for statement
of the switch statement. ● Form:
- Default: specifies an action to be taken if the value for(initialization; condition; increment)
of the switch expression does not match any of the statement;
listed values.
● Action: Allows many variants, but there are three parts:
o Initialization – assignment statement that is used to
Unconditional Transfer Statement
set the loop control variable.
● break(); Used to terminate a case in a switch statement; o Condition – expression that determines when the
terminates loop through bypassing, but program control loop will exit.
resumes at the next statement. o Increment - defines how the loop control variable will
● Example: change each time the loop is repeated.
while(1) { ● Example:
scanf(“%lf”, &x);
for(x = 100; x != 65; x += 5) {
if(x < 0.0)
break; z = sqrt(x);
printf(“%f\n”, sqrt(x)); printf(“The square root of %d is %f”,x, z);
} }
An important point above for loop is that conditional
● continue; Causes the current iteration of the loop to test is always performed at the top of the loop. This
stop and causes the next iteration of the loop to begin means that the code inside the loop may not be executed
immediately. Occurs inside for, while, and do loops. at all if the condition is FALSE to begin with. For loops
● Example: can be also nested.
do {
scanf(“%d”,&num); The do statement
if (x < 0 ) ● Form:
continue; do {
printf(“%d”,x); statement;
} while (x != 100);
} while(expr);
next statement;
An if-else statement can be used as the statement ● Action: First statement is executed and expr is
part of another if statement, this is what you evaluated. If true, control passes back to the beginning
call nested if. of the do statements and loops. If false, control passes
to the next statement.
● Example: ● Example:
if(x == 50) { do {
if(y >= 120) { scanf(“%d”,&num);
sum = x + y; sum += num;
printf(“the sum of x and y is %d”, sum); } while (num > 100);
} printf(“Then sum is %d”, sum);
else {
diff = x – y;
printf(“the difference between x and y is %d”, diff);
}
else {
printf(“Next time”);
}

LOOPS
● Repetition of action in computers where a looping
control mechanism executes specific statements, which
is convenient for fixing large amounts of data.

The while statement


● Form:
while(expr)
statement;
next statement;
● Action: Expr is evaluated. If expr is non-zero (true), then
statement is executed and passed back at the beginning
of loop; when it reaches expr as 0 (false), the control will
execute the next statement.
● Example:
while(number != 0) {
scanf (“%d”,&number);
sum += number;
}
printf(“ the sum of all numbers is %d”,sum);

You might also like