Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

1ST SEMESTER: FINALS EXAMINATION

CP1 – COMPUTER PROGRAMMING (COMP 002)


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

SYLLABUS RULES OR PRECEDENCE & ASSOCIATIVITY


1. Program Control Structures (Loops)
2. Array Operators Associativity
3. Functions
+ (unary), - (unary), ++, --, ! Right to left

PROGRAM CONTROL STRUCTURE


/, *, % Left to right

+, - Left to right
CONTROL STRUCTURE
● Analyzes and chooses in which direction a program <, <=, >, >= Left to right
flows based on certain parameters or conditions.
==, != Left to right
● Way to specify flow of control in programs.
● Any algorithm or program can be clearer and more && Left to right
understood if they use control structures as self-
contained modules.
|| Left to right
● Three types of logic/flow of control:
o Sequence logic/flow =, +=, -=, *=, /=, etc. Right to left
o Selection logic/conditional flow
o Iteration logic/repetitive flow
• ! operator is unary (operator with only one operand).
FLOW OF CONTROL
• All other relational, equality and logical operators
are binary.
SEQUENTIAL FLOW OF CONTROL o 0 or 0.0 or \0 or NULL = false.
● Statements in a program are normally executed one o Any non-zero = true.
after another. COMPOUND STATEMENT
● Often it is desirable to alter the sequential flow of control
● Series of declarations and statements surrounded by
to provide for a choice of action, or repetition of action.
braces. It is also known as block.
● By means of if, if-else, and switch statement, a
● Purpose:
selection among alternative actions is made.
o Grouping statements into an executable unit.
● By means of while, for and do statements, interactive o Achieve the desired flow of control in if, if-else,
actions can be taken. while, for, and switch statements.
● Syntax:
RELATIONAL, EQUALITY, LOGICAL OPERATORS compound_statement{{declaration}{statement}}

Symbol Meaning Expression Example:


#include <stdio.h>
#include <conio.h>
RELATIONAL OPERATORS void main()
{
< Less than expr < expr int a=1, b, c;
{
> Greater than expr > expr b=2;
c=3;
}
<= Less than or equal to expr <= expr getch();
}
>= Greater than or equal to expr >= expr

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

Expressions in if statement is relational,


logical, equality is permissible in any domain.
1ST SEMESTER: FINALS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

The if-else statement ● continue; Causes the current iteration of the loop to
● Form: stop and causes the next iteration of the loop to begin
if (expr) immediately. Occurs inside for, while, and do loops.
statement; ● Example:
else do {
statement2; scanf(“%d”,&num);
● Action: If expr is non-zero (true), then statement1 is
if (x < 0 )
continue;
executed and statement2 is skipped; if expr is 0 (false), printf(“%d”,x);
then statement1 is skipped and statement2 is executed. } while (x != 100);
If both cases are 0, it will pass to the next statement.
● Example: An if-else statement can be used as the statement
if (a > b) { part of another if statement, this is what you
b++; call nested if.
printf(“Value is smaller %d\n”, b);
} ● Example:
else if(x == 50) {
printf(“You got a bigger value %d\n”, a); if(y >= 120) {
sum = x + y;
An if-else statement can be used as the statement printf(“the sum of x and y is %d”, sum);
}
part of another if statement, this is what you
else {
call nested if. diff = x – y;
printf(“the difference between x and y is %d”, diff);
● Example: }
if(x == 50) { else {
if(y >= 120) { printf(“Next time”);
sum = x + y; }
printf(“the sum of x and y is %d”, sum); LOOPS
}
else { ● Repetition of action in computers where a looping
diff = x – y; control mechanism executes specific statements, which
printf(“the difference between x and y is %d”, diff); is convenient for fixing large amounts of data.
}
else { The while statement
printf(“Next time”);
}
● Form:
while(expr)
The switch statement statement;
● Form: next statement;
switch(expression) {
case <constant expression>:
● Action: Expr is evaluated. If expr is non-zero (true), then
statement is executed and passed back at the beginning
statement;
of loop; when it reaches expr as 0 (false), the control will
break;
execute the next statement.
case <constant expression>:
statement; ● Example:
break; while(number != 0) {
default: scanf (“%d”,&number);
statement; sum += number;
}
● Action: Evaluates to an int, conditional, char, or double printf(“ the sum of all numbers is %d”,sum);
value.
- Case list: consists of constants whose type matches
The for statement
that of the switch expression. (no var/expr) ● Form:
- Break: at the point, execution should jump to the end for(initialization; condition; increment)
of the switch statement. statement;
- Default: specifies an action to be taken if the value ● Action: Allows many variants, but there are three parts:
of the switch expression does not match any of the o Initialization – assignment statement that is used to
listed values. set the loop control variable.
o Condition – expression that determines when the
Unconditional Transfer Statement loop will exit.
● break(); Used to terminate a case in a switch statement; o Increment - defines how the loop control variable will
terminates loop through bypassing, but program control change each time the loop is repeated.
resumes at the next statement. ● Example:
● Example: for(x = 100; x != 65; x += 5) {
while(1) { z = sqrt(x);
scanf(“%lf”, &x); printf(“The square root of %d is %f”,x, z);
if(x < 0.0) }
break;
printf(“%f\n”, sqrt(x)); An important point above for loop is that conditional
} test is always performed at the top of the loop. This
means that the code inside the loop may not be executed
at all if the condition is FALSE to begin with. For loops
can be also nested.
1ST SEMESTER: FINALS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

The do statement ● Example:


● Form: int ccis[5];
do { char mander[30];
statement; float coke[10];
} while(expr); double dutch[12];
next statement; ● In each case, all of the array elements are automatically
● Action: First statement is executed and expr is set to 0 except those that have been explicitly initialized
evaluated. If true, control passes back to the beginning within the array definition.
of the do statements and loops. If false, control passes ● One dimensional array string data type – a character
to the next statement. in a string can be accessed either as an element in an
● Example: array by making use of a pointer to character. The
do { flexibility it proves makes C especially useful in writing
scanf(“%d”,&num); string processing programs.
sum += num; ● How strings are handled:
} while (num > 100); o When string constant is assigned to an external or
printf(“Then sum is %d”, sum); a static character array as part of the array
definition, the array size specification is usually
omitted.
ARRAY o It provides a null character ‘\0’ automatically at the
● Fixed-size, sequenced collection of elements of the end of every string.
same data type. ● Example: hev[4] = “ABI”
● Sequence of data items that are of the same type, they hev[0] = “A”; hev[1] = “B”; hev[2] = “I”; hev[3] = ‘\0’
are indexable, and that are stored contiguously.
● Represent a large number of homogeneous values.
ACCESSING ELEMENTS IN ARRAYS
● Since the elements can be individually addressed, we
can refer the elements through subscripts or square ● C uses an index to access individual elements in an
brackets. array. The index must be integral value or an expression
that evaluates to an integral value.
● Example: El0, El[0]
● The simplest form for accessing an element is a
● Loops are used to process arrays more numeric constant.
conveniently.
● Example: score[20]; refer: score[0], score[1]
● Indexing – A convention where you refer elements
through their specific place or order with subscripts or ● The array’s name is a symbolic reference for the
square brackets. (Number[i]). address to the first byte of the array.
● The index represents an offset from the beginning of the
DECLARATION AND DEFINITION array to the element being referred to.
● With these two pieces of data, C can calculate the
● Declaration and definition tells the compiler: address of any element in the array using the following
o The name of the array simple formula:
o The type of each element
o The size or number of elements in the array. element address = array address + (sizeof(element) * index

For example, assume that scores is stored in memory at


location 10,000. Since scores is an integer, the size of one
element is the size of an integer. Assuming an integer size of
two, the address of the element at index 3 is:

element address = 10,000 + 2 * 3 + 10,006

STORING VALUES IN ARRAY

INITIALIZATION

● They are defined in the same manner as ordinary ● Initialization of all elements in an array can be done at
variables, except that each array name must be the time of declaration and definition, just as with
accompanied by a size specification (number of variables.
elements).
● For each element in the array we provide a value. The
● For one dimensional array, the size is specified by a only difference is that the values must be enclosed
positive integer expression enclosed in square brackets. in braces and, if there are more than one, separated
● General Form: by commas.
storage class data-type array[expression]; ● It is a compile error to specify more values than there
are elements n the array. The initial values must appear
on the order in which they will be assigned to the
1ST SEMESTER: FINALS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

individual array elements, enclosed in braces and


separated by commas. ADVANTAGES OF USING FUNCTIONS
● General Form:
storage class data-type 1. Fits naturally with the top-down design approach. It helps
arrayname[expression] = {value1, value2,… to streamline the design of a program and prevents small
value n); details from obscuring the program logic.
● Examples: 2. Can be used more than once in a program and in
int first_array[5]; different programs, thereby sharing programming time. It
int second_array[] = {1, 2, 3, 4}; can be viewed as a block box which performs a particular
int third_array[15] = {3, 7, 4, 6, 1}; task within a program, and these blocks helps you to
accomplish various necessary tasks.
● When the array is completely initialized, it is not 3. Provides a natural method for dividing a programming
necessary to specify the size of the array. task among a team of programmers. By defining a
● If the number of value provided is less than the number function as a block box which accepts inputs and
of elements in the array, the unassigned elements are produces output, the function can be programmed as an
filled with zeros. independent entity.
4. Can be tested individually. By testing functions at a time,
INPUTTING VALUES the process of debugging an entire program is organized
● This can be done using a loop when the array is going and simplified.
to be completely filled, the most appropriate loop is the
for loop because the number of element are fixed and
known. FUNCTION DECLARATIONS
● Example: ● Contains the name of the function, type of the value to
int scores[10]; be returned (the data type will be void), and the number
… and types of the arguments that must be supplied in a
for(int i = 0; i < 10; i++) call of the function.
scanf(“%d”, &scores[i]); ● A function declaration may contain argument names.
● Even though we are dealing with array elements, the ● Syntax:
address operator (&) is still necessary in the scanf type function_name (parameter list);
call. ● Example:
● When there is a possibility that all the elements are not void ccis();
going to be filled, then one of the event-controlled loops int ccis(int bscs, int bsit);
(while or do-while) should be used. float ccis(float x, float y);
● Individual elements can be assigned values using the
assignment operator. Any value that reduces to the FUNCTION DEFINITION
proper type can be assigned to an individual array ● Code that describes what a function does.
element. ● It must not be confused with the function declaration.
● Example: ● Form:
int scores[10] = 96; Type function_name (parameter list)
● You cannot assign one array to another array, even if {
they match full in type and size. You have to copy declaration
arrays at the individual element level. local variables
● Example: statement
for(int i = 0; i < 25; i++) }
second[i] = first[i]; ● A function definition starts with the type of the function.
● If the values of an array follow a pattern, we can use a ● If no value is returned, then the value type is void.
loop to assign values. For example, the following loop ● If the type is something other than void, then the value
assigns a value that is twice the index number to array is returned by the function will be converted, if
scores. necessary, to this type.
● Example: ● The name of the function is followed by a parenthesized
for(int i = 0; i < 25; i++) list of parameter declarations. It act as a placeholder for
scores[i] = i * 2; values that are passed when the function is invoked
(formal parameters). The function body is a block, or a
FUNCTION compound statement, and it too may contain
declarations.
FUNCTION ● Example:
double twice(double x){ /*function definition*/
● Used to implement this “top-down” method of return(2.0 * x);
programming (problem decomposition). }
● A section of a program which performs a specific task.
int all_add(int a, int b, int c){ /*function definition*/
● The task assigned to a function is performed return(a + b + c);
whenever C encounters the function name. }
● A function is actually a subprogram, that performs a task
within a program and is written in a form similar to C LOCAL VARIABLES TO A FUNCTION
main program.
1ST SEMESTER: FINALS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

● Local variables - any variables declared in the body of ● ANSI C provides a new function declaration syntax
function. called functional prototype.
● Global variables – declared external to the function. ● It tells the compiler the number and the type of
arguments that are to be passed to the function and the
Local variables… type of the value that is to be returned by the function.
● Syntax:
● Are referred to as automatic variables or the keyword type function_name(parameter type list);
auto. ● Example:
● Can be referenced only by statements that are inside the double sqrt(double);
block in which the variables are declared.
● Not known outside their own code. A block of code is Tells the compiler that sqrt() is a function that takes a single
begun and terminated when an opening and closing argument of type double and returns a double.
curly brace ( { } ) is encountered.
● Exists only while the block code in which they are ● Function prototype allows the compiler to check the
declared is executing. They are created upon entry into code more thoroughly.
its block and destroyed upon exit. ● Also, values passed to function are properly coerced.

GLOBAL VARIABLE TO A FUNCTION NOTE: In C++, function prototypes are required and the
● They are known throughout the entire program and use of void in the parameter type list in both function
maybe used in any piece of code. prototypes and the function definition is optional.
● They hold their values during the entire execution of the
program. ● Example:
● They are created by declaring them outside of any
Void func(); [equivalent to void func(void);]
function. They maybe accessed by any expression
regardless of what function that expression is in. PARAMETER LISTS
● The storage for global variables is in fixed region of ● A function header identified the parameters which are to
memory set aside for this purpose by the compiler. be passed to the function.
● Helpful when the same amount of data is used in many ● In the header and in the actual body of the function, the
functions in your program. parameters used are FORMAL parameters which are
replaced by the ACTUAL parameter when the function
AVOIDING UNNECESSARY GLOBAL VARIABLES is called.
● Since the FORMAL parameters are eventually replaced,
1. They take up memory the entire time of your program is they are not program variable.
executing not just when they are needed. ● In particular, you can assign to FORMAL parameters the
2. Relying to global variables instead of local variables. It names of program variable which will eventually replace
makes the function less general because it relies on a them.
variable outside of it.
3. Overuse of global variables that can lead to program FUNCTION INVOCATION AND CALL BY VALUE
error because of unknown and unwanted side effects. ● A program consists of one or more function definitions,
THE return STATEMENT including main(), which serves as the entry point for
● May or may not include in an expression (void data type) program execution.
● Syntax: ● When encountering a function name, program control
return; // return(expression); transfers to that function, known as invocation or
● Example: calling.
float f(char a, char b, char c){ ● Upon completing its tasks, control returns to the calling
int i; environment for further execution.

return i; /*the value will be converted to float*/ ● Functions are invoked by specifying their names
} followed by arguments enclosed in parentheses.
● There can be zero or more return statements in a ● Arguments provided during invocation should match in
function. If there is no return statement, then control number and type (or compatible type) with the
variable is passed back to the calling environment when parameters defined in the function.
the closing brace of the body is encountered (“falling off ● Type compatibility is enforced by the compiler when
the end”). function prototypes are employed.
● Arguments are passed "call by value," implying that
● Example (program segment): each argument's value is locally used in place of the
double value(double x){ corresponding formal parameter.
if (x >= 0.0) ● Function calls can originate from either the main
return x;
else
program or within other functions, with the function
return -x; initiating the call termed the calling function or calling
} environment.
● Value parameter – copy of a variable which is private to
FUNCTION PROTOTYPES the function. The function is given a copy of the actual
● Functions should be declared before they are used. parameter to manipulate. However, the manipulation
does not affect any of the variables in the calling
1ST SEMESTER: FINALS EXAMINATION
CP1 – COMPUTER PROGRAMMING (COMP 002)
Geuel John D. Rivera | BSCS 1-5 | Prof. Arnie Fabregas

program.
● Example:
#include <stdio.h>

// Global declaration

int sum;
void func_sample(int y);

// Program entry point

void main (){


int = 5;
printf(“The value of n here is %d”, n);

func_sample(n); // Calling the function

prinf(“The value of n is %d”, n);


} //Program termination

// Process of the global function

func_sample(int y){
y *= 3;
printf(“The new value of y is %d”, y);
}

CALL BY REFERENCE/VARIABLE PARAMETERS

● Used to change the value of variable in the calling


environment.
● The use of addresses of variables as argument to
function can produce the effect of “call by reference”
● How it works: Pointers must be used in the parameter
list in the function definition. When the function is called,
address of the variables must be passed.
● In passing a variable parameter to a function, C does not
pass the actual value, instead, it passes a pointer to a
variable being passed, that is, we pass the address of
the memory location holding the value of the variable
being passed.
● & - used as address operator, meaning “the address of”
● * - indirection operator, meaning “content of address”

You might also like