0% found this document useful (0 votes)
9 views

COMP PROG 1 - Notes (1)

Uploaded by

danielliwanag007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

COMP PROG 1 - Notes (1)

Uploaded by

danielliwanag007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

RED TEXTS ARE ONLY MY NOTES FOR U TO ATLEAST UNDERSTAND SOME TERMS.

HEHE HOPE THIS - Keyboard


REVIEWER HELPS YOU. GOODLUCK PUE~~! - Mouse
- Hard disk, etc.

UNIT 1: COMPUTER AND PROGRAMMING CONCEPTS


HARDWARE COMPONENTS
 Introduction to computers, software or programs, problem solving and how to write
programs/instructions using algorithms: flowcharting and pseudo coding specifically.  Computer Hardware – collection of several components working together.
- Some parts are essential and others are added advantages.
- made up of CPU and peripherals as shown in image below.
1.1 OVERVIEW OF COMPUTER HARDWARE AND SOFTWARE

COMPUTER
 An electronic device that accepts data from the user, processes it, produces results,
displays them to the users, and stores the results for future usage.
DATA
 Collection of unorganized facts and figures and does not provide any further
information regarding patterns, context, etc.
 Data means “unstructured facts and figures”. SOFTWARE

INFORMATION  Set of instructions that drives computer to do stipulated tasks is called a program.
 Software Instructions – programmed in a computer language, translated into
 Is a structured data = organized meaningful and processed data. machine language, and executed by computer.
 Computer – to process the data and convert into information.  Categorized into two types ---
_________________________________________________________________________  System Software
 Application Software

HARDWARE AND SOFTWARE


SYSTEM SOFTWARE
 Operates directly on hardware devices of computer.
HARDWARE  Provides a platform to run an application.
 A mechanical device that makes up computer.  Provides supports user functionality.
 Consists of interconnected electronic devices that are used to control computer’s  Examples of system software:
information, input and output. - Windows
 Examples: - Linux
- CPU - Unix, etc.
APPLICATION SOFTWARE
 Designed for benefit of users to perform one or more tasks. The problem definition step means that there should be clear understanding of the
 Examples of application software: problem. It requires performing the following.
- Microsoft Word
- Excel
- PowerPoint 1. Specify program objectives and identify the users of the program.
- Oracle, etc. 2. Specify the output requirements.
3. Specify the input requirements.
4. Specify processing requirements.
_________________________________________________________________________
5. Study feasibility of implementing the program.
6. Document the analysis.
1.2 STEPS IN PROGRAM DEVELOPMENT In designing a program, the following steps are done:
1. Determine the program logic through top-down approach and modularization, using
PROGRAM AND PROGRAMMING hierarchy charts.
Top-down approach = overall task is first fixed in terms of generalized sub-tasks; more
 Computer – tool used for processing data into information. defined
 The processing is controlled by a set of detailed step by step instructions. Modularization = long programs are split into smaller programs
2. Design details using pseudo-code and/or flowcharts.
 Program or Software Pseudo-code = plain language description of the steps in an algorithm or another system.
- list of instructions that the computer must follow to be able to process data into 3. Test design with a structural walkthrough. Structural walkthrough consists of
information. reviewing process with other programmers and system analyst and scrutinize
- These instructions consist of statements written in a specific programming (“walkthrough”) the programmer’s work.
language.
- When a program is written, we are basically solving a problem. To solve a
problem, we need to use our mind power or logic to develop the detailed Program coding is the step which translates the logic of the program based on the pseudo-
instructions. code (algorithm) or flowcharts into a high-level programming language using the syntax
(grammatical structure) and semantics (meaning and interpretation) of the specific language.

The procedure of developing the detailed instructions for the computer is called The steps include:
programming. It is a five step process namely: 1. Determine the appropriate programming language to use.
2. Code the program in the specific programming language decided on.

1. Define the problem


2. Design the solution/program Program Testing consists desk checking, debugging (process of eliminating errors in computer
3. Code the program codes or software) and running real data to make sure that the program works.
4. Test the program
5. Document the program Desk checking – reading through or checking the program manually to ensure that it’s free
from errors and the logic works.
Debugging – detecting, locating and removing errors in the computer program. Error may  Consists of boxes with different shapes that contain simple statements or sentence
be syntax errors or logic errors. commonly called instructions and connect together by lines.
 Easy to understand because its solution is represented in a picture.
Syntax Errors – can be typographical error or incorrect format of the statement used.
Logic Errors – are caused by incorrect use of control structures. (mistake in a program’s
source code; type of runtime error that simply produce the wrong output or may cause the program to
crash while running.)
Symbols used in flowcharts
Documenting the program consists of the written descriptions of what the program is all
about and how to use it (process of recording or writing instructions about the program was
desaigned.). The documentation should prepare for the users, operators and the
DATA Indicates Data.
programmers.
STORED DATA Indicates data stored in formats suitable for
processing.
1. Write user documentation. This is the manual that is prepared to help the user use
the program. SEQUENTIAL ACCESS STORAGE Indicates only sequentially accessible data such as
2. Write operator documentation. This manual gives the computer operator information those on magnetic tapes & cassette tapes.
on what to do when the program flashes an error message.
3. Write program documentation. The documentation helps train the new programmers DIRECT ACCESS STORAGE Indicates directly accessible data, such as those on
to maintain existing system. Maintenance here means keeping the programs in magnetic disks & floppy disks.
working conditions, error free and up to date.
DOCUMENTS Indicates data on media human beings can read.

DISPLAY Indicates data on any medium that displays


_________________________________________________________________________ information used by human beings, such as
monitor.

PROGRAM LOGIC FORMULATION LOOP LIMIT Composed of two parts; condition for termination
and loop name are written in the symbol indicating
 Is a step-by-step development of a solution to a given problem. the start & the end of the loop respectively.
 Actually, the most difficult part of solving a problem with a computer.
 After you come up with a method of solution, it is a routine to translate your method into TERMINAL SYMBOL This oval, which contains either the word start or
the required language, for example C language and any other programming languages. the word stop, indicates the starting and stopping
point in the flowchart. A flowchart can only have
one starting point but it may have many possible
stopping points.
There are two most commonly used tools that will be of great help for you to formulate a
better solution. These are the flowchart and algorithm.
INPUT/OUTPUT SYMBOL This parallelogram is used for INPUT and OUTPUT
instruction. INPUT means to enter data into a
computer or to use the computer to read the
FLOWCHART available data from magnetic disk. OUTPUT
means to display the result of compilation or
condition of the given solution.

PROCESSING SYMBOL This rectangle is used for ay data processing


operations for which requirements of the problem
are usually done here. Examples are computation
of average, and assignment of the value to the
variable. FIGURE 1.1 FLOWCHART SYMBOLS

DECISION SYMBOL This diamond-shaped symbol contains a condition.


if the condition is true, the marked path TRUE is to
be followed. If the condition is false, the marked
path FALSE is to be followed.

ARROWHEADS/ FLOW LINES Arrows are used to direct the flow of the flowchart.
It shows the flow of the solution.

CONNECTOR It is used as a continuation symbol of a flowchart. It


shows the flow of the solution.

INITIALIZATION / PREPARATION It is used to initialize variables not explicitly defined


SYMBOL in the input but a requirement in the production of
the output.

PREPARATION SYMBOL
TYPES OF FLOWCHARTS

 System Flowchart (process chart)


 Program Flowchart

SYSTEM FLOWCHART
 Indicates a flowchart for a targeted system as a whole.
A System Flowchart Example:

PROGRAM FLOWCHART
 Used to describe processing procedures based on detailed analysis.
*System Flowchart will be discussed thoroughly on System Analysis and Design

FLOWCHART DEVELOPMENT
 The steps that comprise a flowchart must be organize in an orderly,
understandable and clear manner so that the program that implements this
flowchart is similarly in an orderly, understandable and clear manner.
STRUCTURED FLOWCHART
- Orderly, understandable and clear solution.
- A design using the three most basic methods of control.
- The basic methods will be our guide to produce a correct structured flowchart
necessary to prepare a correct program.

1. SEQUENTIAL
- Steps are performed in a strictly sequential manner.
- Each step being executed exactly once.
- Simplest method of control.
- Easy to develop and understand.

Figure 1.2 Shows flowchart on how to determine the product of the three numbers.

2. SELECTION STRUCTURE
- One of the several alternative actions is selected and executed.
- It involves the use of decision based on the given condition.
- Uses a decision block or the diamond-shaped block.
- Alternative action will be presented by a processing block.
Figure 1.3 Flowchart that determines if the average of the students is “PASSING” or
“FAILING”

Figure 1.4 Shows the flowchart that will be determine the positive and negative number. 3. Repetition Structure
- One or more steps is performed repeatedly. Figure 1.6 Shows the flowchart for the printing of numbers from 1-10.
Figure 1.5 Shows the flowchart for the printing of all odd numbers from 1-10.

These three structures appear to be very simple, but in fact they are sufficiently powerful
that any flowchart can be constructed using them.

_________________________________________________________________________
ALGORITHM 3. Certain keywords that are common in high-level language may be used.
- For example: Read or enter to indicate input operation; display, print and
 Set or series of instructions for carrying a particular task.
write for output operation.
 Also a procedure to produce the required output from the given input.
4. Indentation is used to set of certain key blocks of instructions.
 Similar with a paragraph that expresses a single thought.
 Uses ENGLISH LANGUAGE.
 Also known as PSEUDO CODE. STRUCTURE OF AN ALGORITHM
 Can be displayed in a structure diagram that shows the various that must be
performed and their relation to one another.
ALGORITHM DEVELOPMENT
 These diagrams are especially useful in describing algorithms for more complex problem.
 The steps that comprise an algorithm are similar with flowchart.
 Must be organized in orderly, understandable, and clear manner so that the program
that implements this algorithm is similarly orderly, understandable and clear manner. Examples in Flowchart Development using the Three Basic Control Structures:
 The three basic methods of control used in a structured flowchart are also
1. SEQUENTIAL STRUCTURE
applicable in structured algorithm.
Figure 1.7 Algorithm that shows the printing of the sum.
1. SEQUENTIAL
2. SELECTION
3. REPETITION

PSEUDO CODE
 A mixture of language and symbols, terms and other feature commonly used one or
more high-level languages.
 High-level Languages
- Programs used by the computer. Figure 1.8 Algorithm that shows how to determine the product of three numbers.
 Typically, the common features of various pseudo codes that appear in textbook are the
following:

1. The usual computer symbols are used for arithmetic operations are:
- “+” for ADDITION
- “-“ for SUBTRACTION
- ” * “ for MULTIPLICATION
- “ / “ for DIVISION
2. Symbolic names (identifiers) are used to represent quantities being processed
by the algorithm.

2. SELECTION STRUCTURE
Figure 1.9 Algorithm that shows how to determine the positive and negative number.

3. REPETITION STRUCTURE
Figure 1.10 Algorithm that shows the printing of numbers from 1-10
UNIT 2: BASIC PROGRAM STRUCTURE (C LANGUAGE)

DEFINITION OF TERMS
OVERVIEW
Source Code
- Good language to introduce yourself to programming world.
- A simple procedural language. - Text of a program that a user can read.
- Well suited as an introduction to coding: It’s a tried-and-true language.
Interpreter
- Allows you to understand computing processes at a deep level.
- Reads source code one at a time then perform instructions from that line.
INTRODUCTION Compiler
- General-purpose programming language that features economy of expression, - Reads entire source code then converts it into object code.
modern control flow and data structures and a rich set of operations.
- Called as “system programming language” as it is useful for writing compilers and Object Code
operating systems. - Translation of source code in a form that can be executed by computer.
- A structured programming language, considered as high-level language because it
allows programmers to concentrate on the problems at hand. Compile Time

- Events that occur during compilation.


BRIEF HISTORY
Run Time
- Basic Combined Programming Language (BCPL) is developed by Martin Richards in
- Events that occur while program is actually executing.
1967. This language is turn strongly influenced the development of the next
language – B. Syntax Error
- B is written and developed by Ken Thompson in 1970 for the first UNIX system on
the DEC PDP-7. Both BCPL and B are “type less” languages. - Detected during compile time.
- C is an expansion of B. A programming language designed by Dennis Ritchie in - Occur due to error in syntax of sequence of characters.
1972 in AT and T Bell Laboratories. C was originally designed for and implemented Logical Error
on the UNIX operating system on the DEC PDP-II. The new C added something that
B did not have: data types. - Detected when output is incorrect.
- Turbo C is a particular version of C developed by Borland International Corporation - Occur due to error in program algorithm.
in 1987. This version is designed to run on various microcomputer systems, namely Runtime Error
those which use the operating system MS-DOS, the operating system for the IBM
Personal Computers and Compatibles. - Occur during run time like when program asks for int or number but user inputs string
or words.

Library
- Collection of pre-written. - This version of C is significantly extended from the “base bone” language of Ritchie’s
specifications. The extension included enhancements which make the Turbo C
Semantic/Run
compatible with the new proposed and ANSI Standard.
- Time errors are detected during execution-time. 3. Compiler
- Used to convert source code into binary code or machine code.
PROGRAMMING PROCESS 4. Debugger
- Used for testing program and locating programming errors.

5. Run Time Environment


- Capability for running programs within the Turbo C system.
6. User Interface
- Features of Turbo C are integrated in single program which allows you to smoothly
proceed from source code entry to compilation to debugging to running without ever
leaving the Turbo C environment.

1. IDENTIFIERS – LANGUAGE ELEMENT OF C

- Names used to reference variables, functions, labels, and other user-defined objects.
- Sequence of letters, numbers, or underscore.

1.1. RULES IN NAMING IDENTIFIERS

a. Can vary from one to several characters. First character must be a letter or an
underscore with subsequent characters being letters, numbers, or underscore. Must
not have space or hyphen.
b. Must consist of alphabetic characters, digits, and underscores only.
Turbo C c. First 63 characters are significant. Identifiers are case sensitive.
- Version of C language. d. Cannot be the same as Turbo C keyword and should not have the same name as a
- Complete environment to create, test, and run programs. function.

COMPONENTS OF TURBO C

1. Editor
- Used to create program source code.
2. Extended C Language
- Occupies 4 bytes.
- Can include exponent ranging from 3.4 E to -38 to 3.4 E +38.

2.3. DOUBLE

- Special float that can store more significant digits.


- Occupies 8 bytes.
- Can include exponent ranging from 1.7 E -308 to 1.7 E +308.

2.4. CHAR

- Single letter, digit, punction mark, or control symbols enclosed within single quotation
mark.
- Can be assigned with an integer value between -128 and +127.

2.4.1. UNSIGNED CHAR

- Can be assigned with an integer value from 0 to 255.

2. SIMPLE DATA TYPES – LANGUAGE ELEMENT OF C


2.5. VOID
2.1. INT
- Used to declare explicitly a function as returning no value.
- Whole number with optional + or -, followed by sequence of digits. - Used to declare a function having no parameters.
- Cannot contain commas. - Used to created generic pointers.
- Used for controlling loops and conditional statements.
- Byte size: 4, Minimum Value: -2147483648, Minimum Value: +2147483647.

2.1.1. SHORT INT

- Byte size: 2, Minimum Value: -32768, Minimum Value: +32767.

2.1.2. LONG INT

- Byte size: 4, Minimum Value: -2147483648, Minimum Value: +2147483647.

2.1.3. UNSIGNED INT

- Byte size: 16, Minimum Value: 0, Minimum Value: 65536. 3. VARIABLES – LANGUAGE ELEMENT OF C

2.2. FLOAT - Are identifiers which can be assigned a value within a program.
- Has 32 valid characters namely: letters, digits, and underscore.
- Consist of optional sign + or -, followed by one or more digit, a decimal point, and or
one or more further digits.
3.1. VARIABLE DECLARATION
3.3. GLOBAL AND LOCAL VARIABLES
- When we create variables, declaration gives them a symbolic name, and the
definition reserves memory for them. 3.3.1. GLOBAL VARIABLE

data-type variable-name; one variable declared (a) - Initialized at the start of the program, initialized to zero if no other initializer is
int a; specified.

data-type variable-list; three variables declared (b, c, d) 3.3.2. LOCAL VARIABLE


double b, c, d;
- Initialized each time the function in which they are declared is entered.

3.2. VARIABLES INITIALIZATION

- Process of assigning values to variables.

3.2.1. INITIALIZATION BY ASSIGNMENT

- By assignment statement with equal sign.

variable-name = expression; initializing variable x by assigning its


x = 5; value as 5.

3.2.2. INITIALIZATION USING SCANF

- Getting user input.

scanf(%conversion-character, initializing variable x by getting user


&variable-name); input.
scanf(“%d”, &x); 4. CONSTANTS – LANGUAGE ELEMENTS OF C

- Refer to fixed values that may not be altered by the program.


3.2.3. INITIALIZATION DURING DECLARATION 4.1. CHARACTER CONSTANT
- Adding value when the variable is declared. - Constant character enclosed in single quotes.
data-type variable-name = expression initializing variable x during declaration. const char a = character;
int x = 5;
4.2. INTEGER CONSTANT

- Constant int.

const int a = integer; 5.1.2. USING #DEFINE

- Used at the beginning of the program, also used for declaring constants.
4.3. FLOATING POINT CONSTANT
#define variable value
- Constant numbers with decimal.
5.2. TYPE MODIFIERS
const float a = float;
- Used to alter meaning of the base type to more precisely fit the needs of various
situation.
4.4. STRING CONSTANT - Includes signed, unsigned, long, and short.

- Constant string.

const char a[size] = string;

4.5. DECLARED CONSTANT

- This declaration is introduced by the word #define follow by a constant name and its
value.

#define variable value

ASSIGNMENT STATEMENT
5. MODIFIERS
- Process of assigning values to variables.
5.1. ACCESS MODIFIERS - Equal sign is the assignment operator.

5.1.1. CONST

- Variables declared under this modifier cannot be changed during the execution of the HOW TO ASSIGN VALUES TO VARIABLES
program.
1. Variable must be on left side of equal sign while value must be on the right side
const data-type variable = value; of equal sign.
2. Any expression can be assigned on variable.
3. Expressions are not allowed on the left side of the assignment operator.
follows its operand, C uses the operands value before incrementing or decrementing
it.
ASSIGNING VALUES TO VARIABLES
Types of Arithmetic Operators
a. Unary
- Require only a single operand.
b. Binary
- Require two operands.
c. Combined
- Is a shorthand operation.
OPERATORS

- Symbol that tells the compiler specific mathematical, relational, or logical


manipulations.

3 GENERAL CLASSES OF OPERATORS

1. Arithmetic Operators

* asterisk, for multiplication 2. Relational Operators


- Refers to relationship values can have with one another.
/ slash, for division
> greater than
+ plus, for addition
< less than
- minus, for subtraction
>= greater than or equal to
- unary minus, negation
<= less than or equal to
% modulus, modulus division
== equal to
++ plus plus, increment
!= not equal to
-- minus minus, decrement
3. Logical Operators
() parenthesis - Refers to the ways the relationships can be connected together using the rules of
formal logic.
- Using the division operator will not include the remainder.
- Modulus operator will return the remainder only, it cannot be used on type float and && and
double.
- When an increment or decrement operator precedes its operand, C performs the || or
increment or decrement operation prior to using the operands value. If the operator
! not - Are combinations of operators, constants, and variables.

4. Ternary Operators

expression1? expression2 : expression3;

- Uses question mark and colon symbols.

5. Comma Operators
- Used to string together several expressions.
- Evaluates the operands from left to right but the result is of the right-most operand.

EXPRESSIONS
UNIT 3: INPUT / OUTPUT STATEMENTS PROGRAM STRUCTURE Example: stdio.h, string.h, and math.h

OVERVIEW Function Prototype - introduced by ANSI C. Are available in the standard header files
in the standard library.
● Input and output terminology is referring to the communication between a
computer program and its user. ⇒ stdio.h should be included whenever the function printf() and scanf() is used.
● Input – is the user giving something to the program. ⇒ Both are passed as list of arguments that can be thought of as control string and
● Output – is the program giving something to the user. other arguments.

INTERACTIVE INPUT / OUTPUT Control String - is a string and may contain conversion specifications or formats.

3.1 C – Compiler Pre-Processor #include<stdio.h> - It causes a copy of the standard header file stdio.h to be
included in the code when compilation occurs.
The lines that begin with a # are called preprocessing directives.
3.2 Standard Input / Output (stdio.h)

#define #include The “f” stands for formatted.


a.k.a macro include or header Formatted Output Formatted Input
file printf() scanf()
Changes all the occurrences of
Definition Causes a copy of the file to be Definition This function is used for output. This function is used for input.
the identifier.
included at this point in the file
when compilation occurs. printf(“%conversion scanf(“%conversion
Syntax
specification", variable); specification", &variable);
Where to Place Can be anywhere, but normally in the beginning or head of the file.
x = 317;
Identifiers are written in capital The quotes “<>” surrounding the Example scanf(“%d”, &x);
NOTE printf(“%d”, x);
letters. name of the file are necessary.

Affects Only the lines that come after it


Conversion Specifications
#define LIMIT 100 #include<stdio.h>
Example Conversion Character – how the corresponding argument is printed.
#define PI 3.14159 #include<conio.h>
%c as a character
Symbolic Constants - makes it more readable, and easier to change later if necessary. %d as a decimal integer
Header File %e as a floating point number in scientific notation
⇒ It can contain #define lines and other #include lines. All header files ends in .h %f as a floating point
⇒ It contains the declarations of functions in the standard library, macros, structure
templates, and other programming elements that are commonly used. %lf as a double

%g in the e-format of f-format whichever is shorter


%s as a string Line 3 A function name – C program consists of one or more “functions,” which
are the basic modules of a C program.

Line 4 Beginning the body of the function – This opening brace marks the start
Field – it is where the argument is printed.
of the statements that make up the function. The function definition is
Field Width – the number of characters in its field. It can be specified in a format as ended with a closing brace, } .
integer occurring between the percent character (%) and the conversion character.
Line 5 A declaration statement – announces that we will be using variables
Example: called c1, c2, c3 and these variables will be of char(character) type. All
statements in C program should be terminated with a semicolon.
printf(“%c%3c%5c\n”, ‘A’, ‘B’, ‘C’);
Line 6 - 8 A declaration statement – announces that we will be using a variable
Will Print: called i of int(integer) type. And declares the use of float and double types.
A _ _ B _ _ _ _ C Line 9 A print statement – prints the phrase within the quotes.
Address Operator “&” Line 10 An input statement – this reads the values of c1, c2, c3, i, x, and y and
⇒ The expression &x is read as “the address of x”. store them in their corresponding addresses.
⇒ When the keyboard is used to input values into a program, a sequence of characters is When reading in numbers, scanf() will skip white space (blank, newlines,
typed, and it is this sequence of characters, called the input stream, that is received by and tabs), but when reading in a character, white space is not skipped.
the program.
Line 11 & 12 A print statement – this prints the values which the user may enter.
Other Functions of scanf()
Line 13 Function returns a value unless declared as void.
⇒ It can be used to convert a string of decimal digits into an integer value and to store the
value at the appropriate memory. Line 14 End of the function
⇒ It returns as an int the number of successful conversions accomplished. The function
printf() returns as an int the number of characters printed, or a negative value in case of
an error. The Escape Sequence

Sample Program Using printf() and scanf()

Explanation

Line 1 Including another file – tells the computer to include information found in
the file stdio.h

Line 2 A comment – You can use the symbols /* and **/ to enclose comments.
Comments are remarks to help clarify a program. They are intended for the
reader and are ignored by the computer.
\n newline

\t move to the next tab stop

\xhh insert char hh where hh is hexadecimal number

\a sound the bell

\\ insert a backslash character

\” insert a double quote

\’ insert a single quote

3.3 Console Input / Output (conio.h)

Input Sample Program 1


Reads until carriage return or ENTER key
Reads
pressed
gets() Name of the string Yes Sample Program 2
getche() Character without echo No
Sample Program 3
getch() Character with echo No
getchar() Single individual character Yes

Output
Writes a string to the screen, followed by a newline. It can only output a string
puts() of characters. It cannot output numbers or do format conversion. Takes up
less space and runs faster.
putchar() Writes a string (character) to the screen.

The General Form of the C Program

global declaration/s;

function1()

local variables;
statement sequence;

}
function2()

local variables;

statement sequence;

main()

local variables;

statement sequence;

}
THE CONDITIONAL
STATEMENTS/CONSTRUCTS
SINGLE SELECTION CONSTRUCTS
The if statement

is relational, logical, equality expression of an expression from any domain is


permissible (allowed)

appropriate, compound statement should be used to group a series of statements


under the control of a single if expression.

the code can be written to be more efficient and more understandable by using a
single if statement with a compound statement for its body.

ex.

The if- else statement

The general form is:


if(expression)
statement1
else
statement2

THE CONDITIONAL STATEMENTS/CONSTRUCTS 1


If expression is nonzero, then statement1 is executed and statement2 is skipped; if
expression is zero, then statement1 is skipped and statement2 is executed. In both
cases control then passes to the next statement.

ex.

An if-else statement can be used as the statement part of another if statement, this is
what you call nested if

MULTIPLE SELECTION CONSTRUCT

The switch STATEMENT

a multiway conditional statement generalizing the if-else statement

Syntax:
switch(expression)

{ case constant expression:


statement;

break;
case constant expression:

THE CONDITIONAL STATEMENTS/CONSTRUCTS 2


statement;
break;

case constant expression:


statement;

break;

[default
statement;]

Action:
The switch expression may be any expression which evaluates to an int, conditional,
char or double value. The case list consists of constants whose type matches that of
the switch expression.

NOTE: Case list cannot include variables or expressions. After the statements for
a case, a keyword break maybe used.

Break keyword - means at that point, execution should jump to the end of
the switch statement.

Switch statement - terminated by curly bracket ( } ).

Note the optional switch constant default. This switch constant can be used to specify
an action to be taken if the value of the switch expression does not match any of the
listed values.

ex. This program will prompt the user to input an integer number which will determine
the corresponding month in words

THE CONDITIONAL STATEMENTS/CONSTRUCTS 3


THE CONDITIONAL STATEMENTS/CONSTRUCTS 4
system(“cls”) = clearscreen function

UNCONDITIONAL TRANSFER STATEMENTS

The break and continue STATEMENTS

Two special statements: break(); and continue;

1. The break statement

it has two uses:

1. To terminate a CASE in the switch statement

2. To force termination of a loop, bypassing inside the loop, the loop is


immediately terminated and program control resumes at the next statement
following the loop.

ex. Program that allow user to enter integers until he/she enters a negative number or a
zero

THE CONDITIONAL STATEMENTS/CONSTRUCTS 5


1. The continue statement

- causes the current iteration of the loop to stop and causes the next iteration of the loop
to begin immediately. The continue statement may only occur inside for,
while, and do loops.

ex. Program that prints all odd numbers from 1 to 20

THE CONDITIONAL STATEMENTS/CONSTRUCTS 6


________________________________________

THE CONDITIONAL STATEMENTS/CONSTRUCTS 7


SYNTAX SWITCH STATEMENT

Scanf Syntax:

scanf(“%conversion-character”, &variable-name); switch(expression)


{ case constant expression:

Printf statement;

printf(“%conversion-character”, variable-name); break;


case constant expression:
IF-ELSE STATEMENT statement;
The general form is: break;
if(expression) case constant expression:
statement1 statement;
else break;
statement2 [default
statement;]
WHILE LOOP }

while(condition) FOR LOOP


{ for( initialization; condition; increment )
statement(s); {
} statements(s);
}
Syntax: 5. strchr(s1, ch);
DO…WHILE LOOP Returns a substring of string beginning at the first occurrence of character c up to the
end of string
do
{ 6. strrev(string)
statements(s); Reverses all characters except the null terminator in the string.
}
while(condition);
MATH FUNCTIONS

Syntax: pow
NESTED FOR LOOP double pow( double, double)

for ( init; condition; increment ) calling syntax


{ double x = pow(2, 4)
for ( init; condition; increment ) output
{ pow(2, 4) = 16
statement(s);
}
statements(s);
sqrt
// you can put more statements.
} double sqrt(double)

Calling syntax
double x = sqrt (25.00)
FUNCTIONS
Output
sqrt(25) = 5.00
1. strcpy(s1, s2);
Copies string s2 into string s1.
log
2. strcat(s1, s2);
Concatenates string s2 onto the end of string s1. double log(double)

3. strlen(s1); calling syntax


Returns the length of string s1. double x = log(1.35)
output
4. strcmps(s1, s2); log(1.35) = 0.300105
returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
floor
double floor(double)

calling syntax
double x = floor (6.24)
output
floor(6.24) = 6

ceil
double ceil(double)

Calling syntax
double x = ceil (6.64)
Output
ceil (6.64) = 7

abs
double abs(do+uble)

calling syntax
double x = abs (-512)
output
abs (-345) = 345
STRING/ARRAY 1. strcpy(s1, s2);
Copies string s2 into string s1.
- Strings are actually one-dimensional array of characters terminated by a null
character ‘\0’.
2. strcat(s1, s2);
- This a null-terminated string contains the characters that comprise the string followed
Concatenates string s2 onto the end of string s1.
by a null.
The following declaration and initialization create a string consisting of the word “Hello”. To 3. strlen(s1);
hold the null character at the end of the array, the size of the character array containing the Returns the length of string s1.
string is one more than the number of characters in the world “Hello.”
4. strcmps(s1, s2);
char greeting [6] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’ }; returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
if you follow the rule of array initialization then you can write the above statements as follows:
5. strchr(s1, ch);
char greeting [ ] = “Hello”; Returns a substring of string beginning at the first occurrence of character c up to the
end of string

6. strrev(string)
Reverses all characters except the null terminator in the string.

MATH FUNCTIONS
pow (Power)
- the pow function is used to calculate the power of the base raised to the power of
exponent.
- It accepts two double values as arguments which are the base and exponents
numbers and it returns a single double integer which is base to the power of
exponent.

double pow( double, double)


calling syntax
double x = pow(2, 4)
output
pow(2, 4) = 16

Sqrt (square root)


Sr.No. Function & Purpose
- sqrt function in C++ returns the square root of the double integer inside the ceil
parameter list.
- The ceil function is used to return the ceil value of the given double integer.
- The method accepts a double integer value as input find square root and returns a
- Ceil value means rounded up value.
double integer as output.
- The function accepts a double value as input and Returns double integer value
calculated using ceil().
double sqrt(double)
double ceil(double)
Calling syntax
double x = sqrt (25.00)
Calling syntax
Output
double x = ceil (6.64)
sqrt(25) = 5.00
Output
ceil (6.64) = 7
Log
- The log function is used to find the natural log of the given number.
abs
- This method accepts single double integer value finds logarithmic value and returns
a double integer result of log(). - The abs function returns the absolute value of the integer value.
- The functions accepts an integer value and returns an integer value that has the
double log(double) same magnitude but positive sign.

calling syntax double abs(double)


double x = log(1.35)
output calling syntax
log(1.35) = 0.300105 double x = abs (-512)
output
abs (-345) = 345
Floor
- The floor function is used to return the floor value of the given double integer.
- Floor value means rounded down value.
- The function accepts a double value as input and Returns double integer value
calculated using floor()

double floor(double)
calling syntax
double x = floor (6.24)
output
floor(6.24) = 6
FUNCTION A function definition in C programming consists of a function header and a function
body. Here are all the parts of a function –
- is a group of statements that together perform a task.
 Return Type – a function may return a value. The return_type is the data
- Every C program has at least one function, which is main(), and all the most trivial
type of the value the function returns. Some functions perform the desired
programs can define additional functions.
operations without returning a value. In this case, the return_type is the void.
- You can divide up your code into separate functions.
- Dividing the code is up to the programmer, but logically the division is such that each
 Function Name – this is the actual name of the function. The function name
function performs a specific task.
and the parameter list together constitute the function signature.
- A function can also be referred as a method or a sub-routine or a procedure

 Parameters – is like a placeholder. When a function is invoked, you pass a


THREE ELEMENTS OF FUNCTIONS value to the parameter. This value is referred to as actual parameter or
 Function Prototype (Declaration) argument. The parameter list refers to the type, order, and number of the
 Function Definition parameters of a function. Parameters are optional; that is, a function may
 Function Call contain no parameters.

 Function Body – contains a collection of statements that define what the


function does.
FUNCTION PROTOTYPE (Declaration)
- A function declaration tells the compiler about a function’s name, return type, and
parameters. (how to call the function)
- A function declaration has the following parts –
return_type function_name(parameter list);
int max(int num1, int num2);
int max(int, int);

FUNCTION DEFINITION
- A function definition provides the actual body of the function.
return_type function_name ( parameter list )
{
body of the function
}
FUNCTION CALL
- Function execution in the main program.
- To use a function, you will have to call that function to perform the defined task.
- When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
- To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned
value.

FUNCTION ARGUMENTS

 Formal Parameters
 Call Parameters
TWO TYPES OF FUNCTION BY DEFINITION

 Built-In Function or Pre-defined Function


FORMAL PARAMETERS
 User – Definition Function
- If a function is to use arguments, it must declare variables that accept the values of
the arguments
- Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.

TYPES OF PASSING ARGUMENTS TO FUNCTION


 Pass-by-Reference (Call-by Reference)
 Pass-by Value (Call-by Value)
PASS-BY VALUE (CALL-BY VALUE) VARIABLE SCOPE
- A scope in any programming is a region of the program where a defined variable can
- This method copies the actual value of an argument into the formal parameter of the
have its existence and beyond that variable it cannot be accessed.
function. In this case, changes made to the parameter inside the function have no
effect on the argument.
- Local Variable inside a function or a block
- Global Variable outside of all functions

LOCAL VARIABLE
- Variables are declared inside a function or block are called local variables. They
can be used only by statements that are inside that function or block of code.
- Local variables are not known to functions outside their own.

PASS-BY REFERENCE (CALL-BY REFERENCE)

- This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
C-RECURSION GLOBAL VARIABLES
- are defined outside a function, usually on top of the program.
Recursion is the process of repeating items in a self-similar way a function to call
- Global variables hold their values throughout the lifetime of your program and they
itself.
can be accessed inside any of the functions defined for the program.
- need to be careful to define an exit condition from the function, otherwise it will go
into an infinite loop.
- Can be accessed by any function. That is, global variable is available for use
throughout your entire program after its declaration.
ARRAY The General Form – One-dimensional array
- Is a fixed-size, sequenced collection of elements of the same data type. storage class data-type arrayname [expression];

Elements – refer to list of variables of the same data type that can be grouped into Example:
an array
int ccmit[5];
Ex. char bscs[30];
int a, b, c, d, e, f, g, h, i, j;  there are 10 variables of type integer that can be float bsit[20];
grouped into an array. double ITCS[12];

float a, b, c, d, e;  there are 5 variables of type float that can be grouped into an
array;

char a, b, c, d, e;  there are 5 variables of type character that can be grouped into
an array;
 that character array is also known as STRING

- array is a sequence of data items that are the same type, that are indexible, and
that are stored contiguously.

- Are data type that is used to represent a large number of homogenous values.

- A sequenced collection, we can refer to the elements in the array as the first
element, the second element, and so forth until we get to the last element.
Each data element is accessed using an index.
- Array use loops to read and write the elements. INDEX = x[0], x[1], x[2], x[3], x[4]

o use loops to add, subtract, multiply, and divide the elements.


o use loops for more complex processing such as calculating averages. ARRAY WITH INITIALIZATION
Consider the following array definition:
The results on an element by element basis are:
int x[4] = { 1, 2, 3};
x[0] = 1 y[0] = 1.0
float y[5] = { 1.0, 1.25, 1.5};
x[1] = 2 y[0] = 1.25

x[2] = 3 y[0] = 1.5

x[3] = 0 y[0] = 0

y[0] = 0
INPUTTING VALUES
int scores[10];
int i; …
for(i=0; i<10; i++)
scanf(“%d”, &scores[i]);

INPUTTING VALUES
for(i=0; i<10; i++)
scores[i] = i * 2;

REFERENCING ARRAY ELEMENTS

ACCESSING ELEMENTS IN ARRAYS


for(i=0; i<10; i++)
scores[i]…..;
SAMPLE PROGRAM #1 MULTIDIMENSIONAL ARRAYS
This is a program that sorts the values of the array num. - Multidimensional arrays are defined in much the same manner as one-dimensional
- A two-dimensional array requires two pairs of square brackets.
- Two-dimensional arrays are also called array of arrays
#include<stdio.h>
float IT[5][3];
#include<conio.h>
int CS[3][3];
void main()
int ccmit[3][3] = {1,2,3,4,5,6,7,8,9};
{
clrscr();
ccmit[0][0] = 1 ccmit[0][1] = 2 ccmit[0][2] = 3
int num[3] = {5, 3, 7};
ccmit[1][0] = 4 ccmit[1][1] = 2 ccmit[1][2] = 6
int h, i, temp;
ccmit[2][0] = 7 ccmit[2][1] = 8 ccmit[2][2] = 9
OUTPUT
for(h=0; h<3; ++h)
3
for(i=0; i<h; ++i)
5
{
7
If(num[i] > num[i + 1])
{
temp = num[i];
num[i] = num[i + 1];
num[i + 1] = temp;
}
}
for(i=0; i<3; i++)
printf(“%d \n”, num[i]);
getch();
}
EXAMPLE: EXAMPLE:

EXAMPLE:

EXAMPLE:
SEARCH Step 6: Print Element x Found at index i and go to step 8
- C program to implement search (searching algorithm), which is used to find whether Step 7: Print element not found
a number is present in an array and if it is present, then at what location it occurs.
Step 8: Exit
- It is also known as sequential search.

PSEUDOCODE
LINEAR SEARCH
procedure linear_search (list, value)
- Is a very simple search algorithm.
- A sequential search is made over all items one by one. for each item in the list
- Every item is checked and if a match is found then that particular item is returned,
otherwise the search continues till the end of the data collection. if match item == value
return the item’s location
end if
end for
end procedure

BINARY SEARCH
- Is a fast search algorithm with run-time complexity of O(log n).
- This search algorithm works on the principle of divide and conquer.
- For this algorithm to work properly, the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the collection.
- If a match occurs, then the index of item is returned.
ALGORITHM - If the middle item is greater than the item, then the item is searched in the sub-array
Linear Search (Array A, Value x) to the left of the middle item.
- Otherwise, the item is searched for in the sub-array to the right of the middle item.
Step 1; Set i to 1 - This process continues on the sub-array as well until the size of the subarray.
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: set i to i + 1
Step 5: Go to Step 2
HOW BINARY SEARCH WORKS?
- For a binary search to work, it is mandatory for the target array to be sorted. We shall
learn the process of binary search with a pictorial example.
- The following is our sorted array and let us assume that we need to search the
location of value 31 using binary search.

- First, we shall determine half of the array by using this formula

- mid = low + (high – low) / 2

You might also like