Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Computer Programming 1ST TERM REVIEWER

This document provides an introduction to computer programming concepts. It defines key terms like computer programs, programming languages, source code, language translators, low-level vs high-level languages, machine language, assembly language, programming paradigms, and the program development life cycle. It also discusses algorithm development using pseudocode and flowcharts. Programming involves using code to give computers instructions to perform tasks through a defined process from requirements analysis through testing and documentation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Computer Programming 1ST TERM REVIEWER

This document provides an introduction to computer programming concepts. It defines key terms like computer programs, programming languages, source code, language translators, low-level vs high-level languages, machine language, assembly language, programming paradigms, and the program development life cycle. It also discusses algorithm development using pseudocode and flowcharts. Programming involves using code to give computers instructions to perform tasks through a defined process from requirements analysis through testing and documentation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Module 1: Introduction to

Programming [Sub 1-2]

PROGRAMMING
multistep process for creating a program.

way of giving computer instructions (known as code) about what they should do
next.

Computer Programming Terms:


Computer Program

a list or sequence of instructions that tells a computer what to do, written in a


programming language.

Programming Language (PL)

written language make all the computer programs and software, that tells the
computer what to do.

Syntax, PL’s own grammar that consists of rules governing the structure and
content of the statement that should be followed.

Programmer writes source code using a programming languge to create


programs

Source Code

written set of instructions and statements to develop a program

can be written in low-level or high-level language and must be translated to


machine language (binary form) using a language translator.

Language Translator

Assembler, translates a program written from an assembly language to a low-


level language.

Interpreter, translates each statement or one line at a time and executed


immediately after translation. [ex: JavaScript, Python, Ruby]

Module 1: Introduction to Programming [Sub 1-2] 1


Compiler, translates all statements at one time. It provides all the error
messages – called diagnostics- at once. [ex: C, C++, Java}

Low-Level Language High-Level Language

instructions tied directly to one uses English-like instructions


type of computer, often cryptic and can be run on a variety of
and not human-readable. [ex: computer types. [ex: Visual
machine language, assembly Basic, C, C++, Java}
language]
Processing time is slower than
Processing time is faster than Low-Level Language
High-Level Language

Machine Language

all data is represented by microscopic electronic switches that can be either


OFF (designated by a 0) or ON (designated by a 1).

instructions written in 0s and 1s are called machine language or machine


code, each class of computer has its own particular machine language. [ex:
0100 0001 = capital ‘A’]

Assembly Language

programming language with symbolic names for opcodes, and decimals or


labels for memory addresses. [ex: ADD 1, 2 MUL 2, 3}

assembly languge programs must be translated into machine instructions,


using an assembler.

Programming Paradigm
way of programming to solve problem using some programming language.

way to classify programming languages based on their features.

Procedure-Oriented Program

The programmer must instruct the computer every step of the way, from start
to its completion, concentrates on the major tasks the program needs to
perform.

[ex: In a payroll program, the program typically performs severaltasks, such


as inputting the employee data, calculating thegross pay, taxes, net pay,
and outputting a paycheck.]

Module 1: Introduction to Programming [Sub 1-2] 2


Object-Oriented Program

the programmer focus on objects that the program can use to accomplish its
goal. The objects can take on many different forms.
[ex: In Windows-based program, it typically use objects suchas check boxes,
list boxes, and buttons]

Program Development Life Cycle


is a set of steps or phrases that are used to develop program in any
programming language

STEPS IN PROGRAM DEVELOPMENT

1. Requirement Analysis

Requirement, what system should do.

the collection of information and definition of the characteristics or features of


the desired system.

2. System Design

The program design process describes the algorithm for the solution of the
problem.

An algorithm, instructions that describe how data will be processed to


produce the desired output.

To formulate the algorithm, a programmer may choose between


pseudocodes or flowcharts

pseudocode ,an algorithm written in normal Human langugage statements to


describe the logic and processing flow.

Example:

flowchart, visual representation of the sequence of steps and decisions


needed to perform a process. Each step in the sequence is noted within a

Module 1: Introduction to Programming [Sub 1-2] 3


diagram shape.

Example:

3. Coding or Writing The Program

actual writing of the program based on the design specification

4. Testing and Debugging

running various tests, such as desk checking and debugging- alpha testing

Beta testing is performed by real users of the software application in a real


environment

1. Desk Checking - manual testing

2. Debugging - detecting, locating and removing all errors

Type of Errors

Syntax Error, most common error and incorrect use of


programming language statements

Run-time Error, software error occurs while program is being


executed

Logical Error, mistake in a program’s source code that results

3. Run real data

5. Documentation and Maintenance

Module 1: Introduction to Programming [Sub 1-2] 4


Documentation, written detailed description of programming cycle and
specific facts about the program.

Maintenance, any activity designed to keep programs error-free, up-to-date


and in good working condition.

characters (char) = single “letter”


str = series of characters

int = whole number

float = w/ decimals

MODULE 2: Program Logic Design &


Formulation
ALGORITHM
step-by-step method of solving a problem, based on conducting a sequence of
specified actions.

Can be expressed using pseudocode or flowchart

Plan the algorithm that will transform the problem’s input into its output.

Write the algorithm in the Processing column of the Input-Process-Output (IPO)


chart.

Each instruction in the algorithm will describe an action that the computer needs
to take.

Thus, each instruction should start with a verb

most begin: enter the input items

next, record instructions to process the input items to achieve the problem’s
output (processing typically involves performing one or more calculations
using the input items)

most ends with instruction to display, print, or store the output items

Module 1: Introduction to Programming [Sub 1-2] 5


Display, print, and store refer to the computer screen, printer, and a file on a disk,
respectively.

PSEUDOCODE
also called false code because, it has no syntax like any of the programming
language and this can’t be compiled or interpreted by the computer

an implementation of an algorithm in the form of annotations and informative text


written in plain English.

Not standardized

Every programmer has his or her own version, but you will find some similarities
among other versions.

Writing a Pseudocode

Keywords are used to indicate common input-output and processing operations,


written fully in uppercase.

KEYWORDS:

Module 1: Introduction to Programming [Sub 1-2] 6


START: this is the start of your pseudocode.

INPUT, ENTER, READ / GET: this is data retrieved from the user
through typing or through an input device.

PRINT, OUTPUT, DISPLAY, SHOW: show your output to a screen or the


relevant output device.

COMPUTE, CALCULATE, DETERMINE: used to calculate the result of


an expression.

SET, INIT: initialize values

INCREMENT, BUMP: increase the value of a variable

DECREMENT: reduce the value of a variable

Mathematical, relational and logical operators to express arithmetic and logic


operations.

COMMON OPERATORS:

Comparison (Relational): =, ≠, <, >, ≤, ≥


(in coding, instead of “=” they use “==”
Assignment: ← or := Example: c ← 2πr,
and instead of “≠”, they use “!” and “=”
c := 2πr
Example: a = b, x ≠ y, m > n, s < t, n1 ≤
n2

Arithmetic: +, −, ×, /, mod Example: a + Logical: and, or Example: m > n and s < t


b, x – y, m x n, s / t, num mod 2 m > n or s < t

KEYWORDS in CONDITIONAL:

Need statements which evaluate expressions and execute instructions


depending on whether the expression evaluated to True or False.

IF — THEN - ENDIF

IF - ELSE IF — ENDIF

IF — ELSEIF — ELSE - ENDIF

CASE - OTHERS - ENDCASE

Example:

Module 1: Introduction to Programming [Sub 1-2] 7


KEYWORDS in ITERATION/LOOPING:

to iterate is to repeat a set of instructions in order to generate a sequence of


outcomes

[for more info, go back to the recording around 45:00]

FLOWCHART
pictorial representation of an ordered, step-by-step solution to a problem.

Program Flowchart is a diagram that uses a set of standard graphic symbols to


represent the sequence of coded instruction fed into a computer, enebling it to
perform specified logical and arithmetical operations.

FLOWCHART SYMBOLS

Module 1: Introduction to Programming [Sub 1-2] 8


Flowcharts can be used to express different structures:

FLOWCHART GUIDELINES PROGRAM


FLOWCHART
All necessary requirements should be listed out in
logical order.

It should be clear, neat and easy to follow.

Usual direction is from left to right or top to bottom.

One flow line should come out from process


symbol.

One flow line should enter a decision symbol, but


two or three flow lines, one for each possible
answer, should leave the decision symbol.

Module 1: Introduction to Programming [Sub 1-2] 9


Has a logical start and finish

If it becomes complex, better use connector


symbols to reduce number of flow lines

Avoid intersection of flow lines

MODULE 3: Introduction to C++


Programming

Module 1: Introduction to Programming [Sub 1-2] 10


C++
Is an extension of C.

Is a statically typed, compiled, general-purpose, case-sensitive, free-form


programming language that supports procedural, object-oriented, and generic
programming

Is regarded as a middle-level language (both high-level and low-level langugage)

History of C++
developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill,
New Jersey, as an enhancement to the C language and originally named C with
Classes but later it was renamed C++ in 1983

STRUCTURE OF C++

Preprocessor Directives

Lines beginning with hash or pound sign (#) are directives for the processor.
They tell the compiler to preprocess the source code before compiling.

No white space should appear before the #, and semi colon (;) is NOT required
at the end.

Common examples of some preprocessor directives are: #include, and #define

Module 1: Introduction to Programming [Sub 1-2] 11


#include directive - instruct the compiler to add the contents of an include
file into your program during compilation.

Syntax:
#include<header_file>

Examples:
#include<iostream>
[this specific file iostream includes the declarations of the basic
standard input-output library in C++— ex: cin, cout]
#include<math.h>
[math.h header defines various mathematical functions and one
macro— ex: pow, sqrt]
#include<string>

#define directives - define symbolic names and constants.

Syntax:
#define identifier value

Examples:
#define TRUE 1
#define PI 3.14159
#define NAME “SAM”

Module 1: Introduction to Programming [Sub 1-2] 12


Comment Line

All lines beginning with two slash signs (//) are considered comments and do not
have effect on the behavior of the program

/* block comments */
purpose is only to allow the programmer to insert notes or descriptions
embedded within the source code.

using namespace std;

All the elements of the standard C++ library are declared within what is called
namespace, the namespace with the name std (standard).

int main ()

function named main is a special function in all C++ programs; it is the function
called when the program is run. Semi colon is NOT required at the end.

{ and }

open brace ({) indicates the beginning of main’s function definition and the
closing brace (}) indicated its end.

Everything between these braces is the function’s body that defines what
happens when main is called

All functions use braces to indicate the beginning and end of their definitions.

Program Statement

statement is a simple or compound expression that can actually produce some


effect. Line 7 is a C++ output statement

Module 1: Introduction to Programming [Sub 1-2] 13


It is the meat of a program, specifying its actual behavior. Each statement much
be terminated by a semicolon (;)

A compound statement, also called a block, is a group of two or more C++


statements enclosed in braces.

return 0;

defines the exit status of the process or application

terminates main( ) function and causes it to return the value 0 to the calling
process

it should end with semicolon (;)

ELEMENTS OF C++
Character Set - can be letters (lowercase & uppercase), digits and special
characters

Module 1: Introduction to Programming [Sub 1-2] 14


Keywords - reserved words with special meaning in C++.
Remember that keywords are case sensitive and should be in lowercase; Other
names which you should not use as variables are the names of data type such
as int, char, float.
[ANSI (American National Standard Institute)]

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

Data Types

Identifiers - name used to identify a variable, function, class, module, or any


other user-defined item.

Starts with letter A to Z or a to z or an underscore (_) followed by zero or


more letters, underscores and digits (0 to 9)

Does not allow punctuation characters such as @, $, and % within


identifiers.

Variable - also known as user-defined identifier. It is a data storage location


that has a value, which can change during program execution.

You must initialize a variable - probably giving it a value of zero - before


you use it in a calculation or you need to make sure that it is given a
value in some other way. Otherwise, it contains a random number.
All variables in C++ must be declared prior to their use.

Can be given any name up to 31 characters in length which is composed


of any following characters:
• Characters a to z and A to Z (NOTE: upper case and lower case are
distinct)
• The first character must be a letter.
• Only letters, digits or underscores may follow the initial letter. (use

Module 1: Introduction to Programming [Sub 1-2] 15


underscore to separate words or capitalize the first letter)
• Blank spaces and special characters are not allowed

Creating a Variable Name

Constants

Operators

Assignment; Arithmetic; Compound Operators; Increment/Decrement;


Relational; Logical; Bitwise Operators; Conditional/Ternary Operators

DATA TYPES
All variables use data-type during declaration to restrict the type of data to be
stored. Therefore, we can say that data types are used to tell the varibales the
type of data it can store.

Whenever a variable is defined in C++, the compiler allocates some memory for
that variable based on the data-type with which it is declared.

Every data type requires different amount of memory.

Primitive Data Types are built-in or predefined data types and can be used
directly by the user to declare variables [ex: int, char, float, bool etc.]

Integer Floating Point

Character Double Floating Point

Boolean Valueless or Void

Wide Character

Datatype Modifiers are used with the built-in data types to modify the length of
data that a particular data type can hold.
Data type modifiers in C++ are: Signed, Unsigned, Short, Long

Module 1: Introduction to Programming [Sub 1-2] 16


C++ DATA TYPES

Module 1: Introduction to Programming [Sub 1-2] 17


Integer (int.) data type is for storing (+/-) whole number. It requires 4 bytes of
memory space and ranges from -2147483648 to 2147483647.

Character (char.) data type is for storing characters. It requires 1 byte of


memory space and ranges from -128 to 127 or 0 to 255.

Boolean (bool.) data type is for storing boolean or logical values. It can store
either true or false.

Floating Point (float.) data type is for storing single precision floating point
values or decimal values. It requires 4 byte of memory space.

Double Floating Point (double.) data type is used for storing double precision
floating point values or decimal values. Typically requires 8 bytes of memory
space.

Void datatype represents a valueless entity. Used for those function which does
not returns a value.

Wide Character (wchar_t) data type is also character data type but this data
type has size greater than the normal 8-bit data type. It is generally 2 or 4 bytes
long.

DECLARING VARIABLES
Syntax:
datatype variable_name;
datatype var1, var2, varn;’
Examples:

int value;
char letter; —> letter variable can only store single character input
float num;
int a, size, x;
double interest, profit;
char name[20]; —> name variable can store up to 20 character input

ASSIGNING VALUES TO VARIABLES


Syntax:
datatype variable_name = initial value;
Examples:

Module 1: Introduction to Programming [Sub 1-2] 18


int value1 = 0;
int x = 1, y = 2;
float pi = 3.1416;
char letter = ‘A’;
Syntax:
datatype var_name [size] = initial value;

datatype var_name [row size] [column size] = initial value;


Examples:
char name[3] = “FEU”;
char name[3] = {’F’, ‘E’, ‘U’};
int table [2] [3] = {{1, 2, 3}, {4, 5, 6}};

Module 1: Introduction to Programming [Sub 1-2] 19


There are 3 Places in C++ Program
where Variables can be Declared:

1. Outside of all functions, including


the main() function. This sort of
variable is called global and may
be used by any part of the program.

2. Inside the function. Variables in this


way are called local variables and
may be used only by statements
that are also in the same function.

3. In the declaration of a formal


parameter of a function. The
formal parameters are used to
receive the arguments when
that function is called.

Module 1: Introduction to Programming [Sub 1-2] 20


CONSTANTS
Constant is any expression that has a fixed value.

Unlike variable, the value stored in a constant cannot be changed during


program execution

A character is enclosed between single quotes.

String constant contains a series of characters enclosed by double quotation

Integer numbers are specified as numerical (whole number) constants without


fractional components. No need to write quotes (”) to express a numerical
constant

Floating-point constants require the use of decimal point followed by the


number’s fractional component. It may include a decimal point, an e character or
both.

With the const keyword you can declare constants with a specific type in the
same way as you would do with a variable.

Example:
const int StartYear= 2005; —> #define StartYear 2005
const float pi = 3.14159;
const char name[4] = “FEU”;

Note: This is also the same with #define preprocessor directive

C++ OPERATORS & EXPRESSIONS


OPERATORS are the symbols that tell the compiler to perform specific mathematical
or logical manipulations

Types of Operators

Module 1: Introduction to Programming [Sub 1-2] 21


Assignment Operators - a single equal sign (=) which means that the value on
the right side of the assignment expression is assigned to the variable on the left.
[ Example: sum = x+y ]

Arithmetic Operators`

Operator Precedence specified the oder of operations in expressions that


contain more than one operator.`

ORDER OF
PRECEDENCE (Left to
Right Evaluation)

()

++, --

*, /, %

+, -

Example

Compound Operators - +=, -=, *=, /=, %=


Example: x += y;

Module 1: Introduction to Programming [Sub 1-2] 22


expression equivalent to…

y += x; y = y + x;

x -= 5; x = x - 5;

x /= y; x = x / y;

price *= units + 1; price = price * (units+1);

Increment / Decrement Operators - increment operator ++ adds 1 to its


operand, and the decrement operator — subtracts 1 from its operand.
Both increment and decrement operators can either precede (prefix) or follow
(postfix) the operand.
x = x+1; is the same as x++; —> postfix form
x = x+1; can be written as ++x; —> prefix form

Example: Assume x = 2;

Relational Operators - allow the comparison of two or more numerical values,


yielding a result based on whatever the comparison is true (1) or false (0)

Operator Meaning

== Equal to

! = (≠) Not equal to

< Less than

Module 1: Introduction to Programming [Sub 1-2] 23


Operator Meaning

> Greater than

< = (≤) Less than or equal to

> = (≥) Greater than or equal to

Examples:

Expression Evaluated as

5 == 1 0 (false)

5≥1 1 (true)

5≠1 1 (true)

(5+10) == (3*5) 1 (true)

Logical Operators - used to combine two or more conditions or to complement


the evaluation of the original condition in consideration. The result of the
operation of a logical operator is a boolean value either true or false.

Operator Description Example

If both the operands are non-


&& zero, then condition becomes (A && B) is false.
true.

If any of the two operands is


|| non-zero, then condition (A || B ) is true.
becomes true.

Use to reverses the logical


state of its operand. If a
! ! (A && B) is true.
condition is true, then Logical
NOT operator will make false.

Bitwise Operators - works on bits and perform bit-by-bit operation.

Operator Equivalent Description

& AND Bitwise AND

Module 1: Introduction to Programming [Sub 1-2] 24


| OR Bitwise inclusive OR

^ XOR Bitwise exclusive OR

Unary complement (bit


~ NOT
inversion)

<< SHL Shift bits left

>> SHR Shift bits right

Conditional Operators (Ternary Operators) - ? and : are used to construct


conditional expressions.
Format:
Exp = Exp1 [condition] ? Exp2 [true] : Exp3 [false] ;

Example:
Assume x = 1, y = 5;
Test = x < = y ? 1 : 0;
Result: 1

MODULE 4:
C++ Basic Input/Output
In C++, input and output (I/O) operators are used to take input and display
output. The operator used for taking the input is known as the extraction or get
from operator (>>), while the operator used for displaying the output is known as
the insertion or put to operator (<<).

The standard C++ library includes the header file iostream, where the standard
input and output stream objects are declared.

Module 1: Introduction to Programming [Sub 1-2] 25


STANDARD OUTPUT
COUT

syntax:
cout << varName; or
cout << “Some String”; or
cout << value/expression;

Insertion operator (<<) is commonly known as the output operator.

The standard output by default is the screen, and the C++ stream object defined
to access it is cout.
Example:

Chaining insertions is especially useful to mix literals and variables in a single


statement:
cout << “I am” << age << “years old and my zipcode is” << zipcode;

Assuming the age variable contains the value 39 and the zipcode variable
contains 1440, the output of the previous statement would be:

cout does not do automatically add line breaks at the end, unless instructed to
do so.
Example:
cout << “This is a sentence.”;
cout << “This is another sentence.”;

Module 1: Introduction to Programming [Sub 1-2] 26


To insert a line break, a new-line character shall be inserted at the exact
position the line should be broken. In C++, a new-line character can be
specified as \n (backslash character followed by a lowercase n).

ESCAPE CODES
are used to represent certain special
characters within string literals and
character literals.

STANDARD INPUT
cin
syntax:
cin >> varName; or
cin >> varName1 >> varName2 >> … >> varNamen;

Extraction Operator (>>) commonly known as the input operator.

Standard input by default is the keyboard, and the C++ stream object defined to
access it is cin

Module 1: Introduction to Programming [Sub 1-2] 27


The object cin is connected to the
input device.

The age entered by the user is


extracted from cin using the
extraction operator(>>) and the
extracted data is then stored in the
variable age present on the right
side of the extraction operator.

INPUT / OUTPUT STATEMENTS


BASIC I/O (cin/cout)
Example 1: Create a program that computes the area of the rectangle.

Example 2: Outputting Characters using single variable

Module 1: Introduction to Programming [Sub 1-2] 28


Example 3:
Input Strings using <string.h>
directive and getline();
getline() is a standard library fuction in
C++ and is used to read a string or a
line from input stream. It is present in
the <string> header.

getline() - standard library function in C++ and is used to read a string or a line
from input stream.

Takes the stream (cin) as first argument, and the string variable as second.

TYPE CONVERSION
process of converting one predefined type into another.

When variables of one type are mixed with variables of another type, a type
conversion will occur.

C++ facilitates the type conversion into the following two forms:

Implicit Type Conversion

Explicit Type Conversion

DATA TYPES (32-bit)

Module 1: Introduction to Programming [Sub 1-2] 29


IMPLICIT TYPE CONVERSION (Automatic Type Conversion)

Conversion performed by the compiler without programmer’s intervention.

It is applied generally whenever differing data types ar intermixed in an


expression, so as not to lose information.
bool → char → shot int → int → unsigned int → long → unsigned → long long →
float → double → long double

Ex 1: Conversion from int to double

Ex 2: Automatic Conversion from double to int

Module 1: Introduction to Programming [Sub 1-2] 30


DATA LOSS DURING CONVERSION

Conversion from one data type to


another is prone to data loss. This
happens when data of a larger type
is converted to data of a smaller
type

EXPLICIT TYPE CONVERSION

An operand to a specific type is called type casting. An explicit type conversion is


user-defined that forces an expression to be of specific data type. This is the
general form to perform type casting in C++:
(datatype) expression;

For example, to make sure that expression (x+y/2) evaluates to type float, write it
as:
(float) (x+y/2);

Module 1: Introduction to Programming [Sub 1-2] 31


COMMON MATHEMATICAL LIBRARY FUNCTIONS
FUNCTION DESCRIPTION EXPRESSION

pow Raise to power pow(base, exponent);

get the absolute value of an


abs abs(value);
integer value

sqrt Compute square root sqrt(variable);

ceil Round up value ceil(variable);

floor Round down value floor(variable);

Rounds removes digits after


trunc trunc(variable);
decimal point

Rounds given number to the


round round(varable);
closest integer

sets the decimal precision to be


setprecision used to format floating-point setprecision(value);
values on output operations

Module 1: Introduction to Programming [Sub 1-2] 32


pow( ) and sqrt ( ) - power of the given number while sqrt() returns the square
root of the value. These math functions are part of <math.h> header.

abs( ) and fabs( ) - used to retrieve or calculate the absolute value. abs( ) is
used to calculate the absolute value for integer type numbers whereas fabs( )
are used for floating type numbers.

floor( ) and ceil( ) - functions map a real number to the greatest (ceiling)
preceding or least (floor) succeeding integer. Part of <math.h> header.

trunc( ) - round (truncate) the value toward zero and returns the nearest integral
value.

round( ) - round the given number to the closest integer.

setprecision( ) - used along with fixed provides precision to floating point


numbers correct to decimal numbers mentioned in the brackets of the
setprecision. Part of <ionmanip> header

MODULE 5:

Module 1: Introduction to Programming [Sub 1-2] 33


PROGRAM CONTROL STRUCTURE: CONDITIONAL
CONTROL STRUCTURE
Flow of control refers to the order in which a program’s statements are executed. Any
algorithm can be built using combinations of four standardized flow of control
structures:

Normal flow of control for all programs is sequential

Selection is used to select which statements are performed next based on a


condition

Repetition is used to repeat a set of statements

Invocation is used to invoke a sequence of instructions using a single


statement, as in calling a function

RELATIONAL EXPRESSION
An expression created using a relational operator.

Relational expressions are also known as conditions

The expression is interpreted as either true (non-zero) or false (0).

Relational Operator Meaning

< Less than

> Greater than

≤ (< =) Less than or equal

≥ (> =) Greater than or equal

== Equal to

≠ (! =) Not equal to

ANATOMY OF A RELATIONAL EXPRESSION

Module 1: Introduction to Programming [Sub 1-2] 34


Character data can also be compared using relational operators.

LOGICAL EXPRESSION
More complex conditions can be created using the logical operations AND(&&),
OR(||), and NOT(!)

ANATOMY OF A LOGICAL EXPRESSION

IF STATEMENT
The if statement allows you to control if a program enters a section of code or
not based on whether a given condition is true or false. One of the important
functions of the if statement is that it allows the program to select an action
based upon the user's input.
• if
• if-else
• if-ladder
• nested if

Module 1: Introduction to Programming [Sub 1-2] 35


IF-ELSE STATEMENT
The structure of an if-else statement:
if (expression)
statement_TRUE;
else
statement_FALSE;

Module 1: Introduction to Programming [Sub 1-2] 36


IF-LADDER STATEMENT
structure of an if-ladder statement:

if (expression1)
statement1;
else if (expression2)
statement2;
else
statement3;

Note: Whether the indentation exists or not, the compiler will, by default, associate
an else with the closest previous unpaired if, unless braces are used to alter this
default pairing

Module 1: Introduction to Programming [Sub 1-2] 37


Module 1: Introduction to Programming [Sub 1-2] 38
NESTED IF STATEMENT
Nested if statements means if or if-else statement inside another if statement

Module 1: Introduction to Programming [Sub 1-2] 39


Module 1: Introduction to Programming [Sub 1-2] 40
THE SWITCH STATEMENT
allows a variable to be tested for
equality against a list of values.
Each value is called a case, and the
variable being switched on is
checked for each switch case.

POINTS TO REMEMBER

Do not use floats in switch statements.

Expression evalueted by switch should match a case. This means that the
matching case must also be an integer or a constant expression which evaluates
to an integer.

Letters (not words) can be used in case statements as constants.

Use break statement to stop further execution otherwise it continues execution


with whatever code that follows.

Module 1: Introduction to Programming [Sub 1-2] 41


MODULE 6:

REPITITION CONTROL STRUCTURES


Repetition structures, or loops are used when a program needs to repeatedly
process one or more instrcutions until some condition is met, at which time the
loop ends.

The process of performing the same task over and over again is called iteration,
and C++ provides built-in iteration functionality.

C++ provides three different forms of repetition statements:

while structure

for structure

do-while structure

The condition being tested can be evaluated at either (1) the beginning or (2) the
end of the repeating section of code.

Pre-Test Loop (entrance-controlled loop) - test occurs at the beginning of the


loop.

Post-Tes Loop (exit-controlled loop) - test occurs at the end of the loop.

COUNTER-CONTROLLED REPETITION REQUIRES…


the name of a control variable (or loop counter)

the initial value of the control variable

Module 1: Introduction to Programming [Sub 1-2] 42


the loop-continuation condition that tests for the final value of the control variable
to determine when to exit

the control variable to be incremented (or decremented) each time through the
loop

FOR STATEMENT
used for repeating a statement or series of statements as long as a given
conditional expression evaluates to true. [pre-test loop]

Syntax:
for (initialization; condition; update statement) {
statement(s);
}

Module 1: Introduction to Programming [Sub 1-2] 43


Module 1: Introduction to Programming [Sub 1-2] 44
WHILE STATEMENT

Module 1: Introduction to Programming [Sub 1-2] 45


Used for repeating a statement or series of statements as long as given
conditional expression is evaluated to true. [pre-test loop]

Syntax:
while (condition expression){
statement(s);

SENTINEL-CONTROLLED WHILE LOOP

tested in condition; loop ends when sentinel encountered

Syntax:
cin >> variable; //initialize loop control variable

while (variable ! = sentinel) {


.
.
cin >> variable; //update loop control variable
.
}

Module 1: Introduction to Programming [Sub 1-2] 46


DO WHILE STATEMENT
executes a statement or statements then repeats the execution as long as a
given conditional expression evaluates to true. [post-test loop]

Syntax:
do{
statements;
} while (conditional expression);

CONTINUE STATEMENT
used inside loops. When a continue statement is encountered inside a loop,
control jumps to the beginning of the loop for next iteration, skipping the
execution of statements inside the body of loop for the current iteration.

Module 1: Introduction to Programming [Sub 1-2] 47


BREAK STATEMENT
It is used to come out of the loop instantly. When a break statement is
encountered inside a loop, the control directly comes out of loop and the loop
gets terminated. It is used with if statement, whenever used inside loop

GOTO STATEMENT
It allows making an absolute jump to another point in the program. You should
use this feature carefully since its execution ignores any type of nesting
limitation.

The destination point is identified by a label, which is then used as an argument


for the goto instruction.

A label is made of a valid identifier followed by a colon (:). i.e. Here:

Module 1: Introduction to Programming [Sub 1-2] 48


LOOPING STRUCTURE:
Infinite Loop - if a condition never becomes false
Nested Loop - a loop inside another loop

MODULE 7: Functions and Recursion


FUNCTIONS
a group of statements that is executed when it is called from some point of the
program.

Module 1: Introduction to Programming [Sub 1-2] 49


a self contained block of code with a specific purpose. It has a name that is used
to identify and call it for execution.

subprogram that acts on data and often returns a value.

ADVANTAGE OF USING A FUNCTION

Easier to maintain

Update and debug than one very long program.

By programming in a modular (functional) fashion, several programmers can


work independently on separate functions which can be assembled at a later
date to create the entire project.

USER-DEFINED FUNCTION
A user defined function is a programmed routine that has its parameters set by
the user of the system.

User defined functions are functions that perform specific tasks within a larger
system, such as a database or spreadsheet program.

DECLARATION OF A USER-DEFINED FUNCTION

The standard form of declaration of a function is

If the function returns a value then the type of that value must be specified in
return_type. For the moment this could be int, float or char. If the function does

Module 1: Introduction to Programming [Sub 1-2] 50


not return a value then the return_type must be void.

The function_name follows the same rules of composition as identifiers.

The parameter_list lists the formal parameters of the function together with their
types.

The local_definitions are definitions of variables that are used in the


function_implementation. These variables have no meaning outside the function

The function_implementation consists of C++ executable statements that


implement the effect of the function

STRUCTURE OF A FUNCTION

FUNCTION HEADER

In the first line of thecode in the previous slide:


int sum (int x, int y)

It has three main parts:

The name of the function i.e. sum

The parameters of the function enclosed in parenthesis

The return valur type i.e. int

FUNCTION BODY

What ever is written with in { } in the above example is the body of the function.

Example:
int sum (int x, int y)
{ int ans = 0; //holds the answer that will be returned
ans = x + y; //calculate the sum
return ans; //return the answer
}

Module 1: Introduction to Programming [Sub 1-2] 51


FUNCTION PROTOTYPE

It provides the basic information about a function which tells the compiler that the
function is used correctly or not.

It contains the same information as the function header contains.

It can be used to check the calls to the function for the proper number of
parameters and the correct types of parameters.

Note: The data types of the parameters must be compatible


otherwise the compiler will issue an error message.

To write the prototype, simply copy the header from the function to the beginning
of the program and append a semicolon to the end as a signal to the compiler
that this is not a function but a prototype.

The prototype of the function in the above example would be like


int sum (int x, int y);

The only difference between the header and the prototype is the semicolon ;

NON-VOID FUNCTION

A function that can be made to return a single value to the calling program is
referred to as non-void function.

Module 1: Introduction to Programming [Sub 1-2] 52


Example:
int square(int x)
{ int ans = 0; //holds the answer that will be returned
ans = x*x; //calculates the square of the number
return ans; //returns the answer
}

VOID FUNCTION

A function that is written to perform specific task


and return multiple values to calling program are
called void functions

Module 1: Introduction to Programming [Sub 1-2] 53


ACTUAL ARGUMENTS AND FORMAL PARAMETERS

Actual arguments are variables/values used within the function call while formal
parameters are variables used within the function header that receives the copy
of the actual argument values.

Note: The number of actual arguments must be the same as the number of formal
parameters

The correspondence between actual and formal parameter is one-to-one basis


according to the respective orders

Module 1: Introduction to Programming [Sub 1-2] 54


PASS BY VALUE
when calling a function with parameters, what we have passed to the function
were copies of their values but never the variables themselves.

In some cases where you need to manipulate from inside a function the value of
an external variable we can use arguments passed by reference.

Module 1: Introduction to Programming [Sub 1-2] 55


In the declaration, the type of each parameter was followed by an ampersand
sign (&) to specify that their corresponding arguments are to be passed by
reference instead of by value.

When a variable is passed by reference we are not passing a copy of its value,
but we are somehow passing the variable itself to the function. and any
modification that we do to the local variables will have an effect in their
counterpart variables passed as arguments in the call to the function.

RECURSION OVERVIEW
A function that calls itself is known as a recursive function.

Recursive call is a function call in which the function being called is the same as
the one making the call.

Recursion is a programming technique in which procedures and functions call


themselves.

Module 1: Introduction to Programming [Sub 1-2] 56


Module 1: Introduction to Programming [Sub 1-2] 57
RULES FOR RECURSIVE FUNCTION
1. In recursion, it is essential for a function to call itself, otherwise recursion will not
take place.

2. Only user define function can be involved in recursion.

Module 1: Introduction to Programming [Sub 1-2] 58


3. To stop the recursive function it is necessary to base the recursion on test
condition and proper terminating statement such as exit() or return must be
written using if() statement.

4. When a recursive function is executed, the recursive calls are not implemented
instantly. All the recursive calls are pushed onto the stack until the terminating
condition is not detected, the recursive calls stored in the stack are popped and
executed.

5. During recursion, at each recursive call new memory is allocated to all the local
variables of the recursive functions with the same name.

ADVANTAGES & DISADVANTAGES OF RECURSION


Advantages of C++ Recursion

It makes our code shorter and cleaner.

Complex code and nested for loops are avoided here.

Recursion is required in problems concerning data structures and advanced


algorithms, such as Graph and Tree Traversal

Disadvantages of C++ Recursion

It takes a lot of stack space compared to an iterative program.

It uses more processor time.

It can be more difficult to debug compared to an equivalent iterative program.

[ good luck 🐝 tch ]

Module 1: Introduction to Programming [Sub 1-2] 59

You might also like