PROGRAMMING FUNDAMENTALS NOR HAMIZA BINTI GHAZALI NORAINI BINTI DESA
Politeknik Sultan Haji Ahmad Shah
Published by POLITEKNIK SULTAN HAJI AHMAD SHAH SEMAMBU 25350 KUANTAN
Copyright ©2021, by Politeknik Sultan Haji Ahmad Shah Materials published in this book under the copyright of Politeknik Sultan Haji Ahmad Shah. All rights reserved. No part of this publication may be reproduced or distributed in any form or by means, electronic, mechanical, photocopying, recording, or otherwise or stored in a database or retrieval system without the prior written permission of the publishers.
TABLE OF CONTENTS
ABSTRACT …………………………..……………………………………………………………………………..…….………. i CHAPTER 1 …………………………………………………………………………………………………………………………. 1 1.1 PROGRAMMING LANGUAGE …………………………………………………………………………..………. 2 1.2 EVOLUTION OF PROGRAMMING LANGUAGE ………………………………………………………….. 3 1.3 TYPES OF PROGRAMMING LANGUAGES …………………………………………………………………. 8 1.4 PROGRAM, PROGRAMMING AND PROGRAMMER ……………………………………………..…… 8 1.5 PROGRAMMING LANGUAGE APPLICATION IN REAL LIFE ……………………………….……….. 9 1.6 STRUCTURE OF PROGRAMMING METHODOLOGY ………………………………..………………… 9 1.7 INPUT PROCESS OUTPUT ……………………………………………………………..……………………….. 12 1.8 TYPES OF DESIGN TOOLS ………………………………………………………………………………………. 13 1.9 PROBLEM-SOLVING CONCEPT ……………………………………………………………….……………… 17 CHAPTER 2 ………………………….………………………………………….………………………………………………… 18 2.1 VARIABLES IN C PROGRAMMING ……………………………………..…………………………………… 19 2.2 VARIABLES ……………………………………………………………………………………………………………. 20 2.3 CONSTANT ………………………………………………..………………………………………………………….. 21 2.4 DATA TYPES ………………………………………………..……………………………………………………..…. 23 2.5 FUNDAMENTALS OF C PROGRAM …………………………..…………………………………………….. 25 2.6 TYPES OF OPERATORS …………………………………………………………………………………………… 27 2.7 HIERARCHY OF OPERATOR ………………………………………..………………………………………….. 33 CHAPTER 3 …………………………………………………………………..…………………………………………………… 34 3.1 PROGRAM CONTROL STATEMENT ………………………………….…………………………………….. 35 3.2 SEQUENCE STATEMENTS ………………………………………………………………………………………. 36 3.3 SELECTION STATEMENTS …………………………………………………….………………………………… 37 CHAPTER 4 …………………………………………………………………………………………….…………………………. 43 4.1 LOOPING STATEMENT …………………………………………………………………………………………… 44 4.2 THE for LOOP ………………………………………………………………………………..………………………. 45 4.3 THE while LOOP …………………………………………………………………………………………………….. 46 4.4 THE do-while LOOP ……………………………………………………………………………………..………… 47 4.5 BREAK, CONTINUE AND GOTO …………………………………………………….…………………..…... 48 CHAPTER 5 ……………………………………………………………………………………………..………………………… 50 5.1 FUNCTION …………………………………………………………………………….………………………………. 51 5.2 ARRAY …………………………………………………………………………………………………..………………. 55
PROGRAMMING FUNDAMENTALS
ABSTRACT
PROGRAMMING FUNDAMENTALS course provides the skills necessary for the effective of application of computation and computer programming in engineering applications. Students will develop their programming skills through a variety of assignments and labs and by reviewing case studies and example programs. The learning outcome is proficiency in writing small to medium programs in a procedural programming language.
i|Page
PROGRAMMING FUNDAMENTALS
CHAPTER 1
INTRODUCTORY TO PROGRAMMING
Objectives: At the end of this chapter, students should be able to: Remember programming language Remember definition and types of programming Understand types of programming and structure programming methodology Remember algorithm, flowchart and pseudocode Understand algorithm, flowchart and pseudocode Apply algorithm, flowchart, pseudocode and analyse problem
1|Page
PROGRAMMING FUNDAMENTALS 1.1
PROGRAMMING LANGUAGE Computer is an electronic device used to process data,
while computer system is a group of reference to all computer hardware related including processor, storage devices, input devices,
output
devices
and
communication
devices.
A computer program is a collection of instructions that performs a specific task when executed by a computer. A computer requires programs to function, and typically executes the program's instructions in a central processing unit. A computer program is usually written by a computer programmer in a programming language. From the program in its human-readable form of source code, a compiler can derive machine code—a form consisting of instructions that the computer can directly execute. Alternatively, a computer program may be executed with the aid of an interpreter.
Figure 1.0: Component of Computer System
2|Page
PROGRAMMING FUNDAMENTALS Programming language is a language that is used for writing programs or a set of rules and reserved words (keywords) that can be used to tell a computer what are the operations to be done. There are five generations of programming language: 1st Generation Language (Machine language (1950-1960)) 2nd Generation Language (Assembly Language (1950s) 3rd Generation Language (High-Level Language ((3GL, 4GL, 5GL) 1960s till now) 4th Generation Language (1980s) 5th Generation Language ((Natural Language) 1990s)
Figure 1.1: Evolution of Programming Language
1.2
EVOLUTION OF PROGRAMMING LANGUAGE
1.2.1 1st Generation Language (Machine language (1950-1960)) The lowest level of language. It represented data and program instructions as 1s and Os - binary digits corresponding to the on and off electrical states in the computer. Examples: 0 represents “off” and 1 represents “on”. The only language that the computer could understand (does not require a translator). Machine language is machine-dependent. Meaning, a written program for one computer generally cannot be executed on another. For example, a program written in Apple PC cannot be run on IBM PC. 3|Page
PROGRAMMING FUNDAMENTALS
Advantages:
o
The most efficient in terms of storage area and speed.
o
Allows the program to fully utilize the computer's potential for data processing.
Disadvantages:
o
The instruction and syntax in a program are not standardized. It depends on the type of computer used.
o
Program instruction executes only on the specific machine for which it was written.
Figure 1.2: Example of Machine Language
1.2.2 2nd Generation Language (Assembly Language (1950s) Known as a symbolic language. It was developed to replace "0" and "1" used in Machine Language. It uses mnemonic codes - a symbol chosen to help users to remember the significance of the symbol. For example, A represented ADD and S represented SUM. Computer does not understand the language so it needs an assembler to translate the program to machine language. Advantages: o The program can run faster. o Efficient use of the memory.
4|Page
PROGRAMMING FUNDAMENTALS Disadvantages: o Errors can be made easily - difficult to identify & correct errors. o It is difficult to understand. o It takes a long duration of time to write the program.
Figure 1.3: Example of Assembly Language
1.2.3 3rd Generation Language (High-Level Language ((3GL, 4GL, 5GL) 1960s till now)
Instruction is written as a series of English-like words.
Translator (Compiler/Interpreter) is needed to translate high-level language to machine language.
It is Machine-Independent. The program can be written and executed on any computer.
It can be classified into two categories: i. Non-procedural language A language that states task to be accomplished but does not state the steps needed to accomplish it. ii.
Procedural language. A language that represents a step-by-step process (procedure) for solving the problem.
5|Page
PROGRAMMING FUNDAMENTALS
Advantage: o Easy to be developed and maintained.
Figure 1.4: Example of High-Level Language (C Language)
1.2.4
4th Generation Language (1980s) Program is written in English-like statements. It is a short programming language where the operation needs a few lines instead of hundreds of lines. It is a non-procedural language. Known as a query language, which can be used to retrieve data from the database.
6|Page
PROGRAMMING FUNDAMENTALS Advantages: o Result-oriented where they emphasize what instead of how. o It is simpler and easier, so programmers and non-programmers can use this language with minimum training.
Figure 1.5: Example of PROLOG, FOCUS, LISP and SQL
1.2.5 5th Generation Language ((Natural Language) 1990s)
A programming language that resembles human language.
Known as knowledge-based language.
Translates human instructions into code (machine language) where a computer can understand.
The use of a natural language to access knowledge base is called knowledge-based system.
7|Page
PROGRAMMING FUNDAMENTALS 1.3
TYPES OF PROGRAMMING LANGUAGES A programming language is an artificial language used to write instructions that can be
translated into machine language and then executed by a computer. Three types of programming languages are low-level language, middle-level language, and high- level language. LOW-LEVEL LANGUAGE
MIDDLE-LEVEL LANGUAGE
HIGH-LEVEL LANGUAGE
Computers only understand binary language, that composed of 1’s and 0’s. Very hard to understand and very hard to program in. Also known as machine language. Example: 20101001 It uses mnemonics for machine language. Instruction is minimal but still hard for humans to understand. Example: ADD, ADC, MOV Each instruction composed of many low-level instructions, closer to English. It is easier to read and understand. Example: FORTRAN, Pascal, BASIC, C, C++, Java, etc.
Figure 1.6: Types of Programming Language 1.4
PROGRAM, PROGRAMMING AND PROGRAMMER To understand program design in application software, the user should know the definitions
of program, programming, and programmer.
Figure 1.7: Definition of Program, Programming and Programmer 8|Page
PROGRAMMING FUNDAMENTALS 1.5
PROGRAMMING LANGUAGE APPLICATION IN REAL LIFE Example of programming language in real life: ATM Machine (Money withdrawal transaction) a.
Get the card number from the user (Input)
b. Get the pin number from the user (Input) c.
Process the input data (Process)
d. Get the transaction chosen by the user (Input) e.
Get the account type from the user (Input)
f.
Process the transaction as wanted by the user (Process)
g.
Withdraw amount of money required by the user (Output)
h. Print receipt for the user (Output)
1.6
STRUCTURE OF PROGRAMMING METHODOLOGY Three types of programming are structured programming, modular programming and
object-oriented programming.
Structured Programming • Structured programming tells the program what to do, step by step. • Easy to modify. • Three types of logic structures are sequence structure, selection structure and iteration/ repetition structure.
Modular Programming
Object- Oriented Programming
• Can be used to break up a large program into manageable units, or to create code that can be easily re-used. • Consists of a main module and one or more auxiliary modules. • A module is a set of statements that performs a task or computes a value
• Creates several objects (like a button on the screen, a file, or a text box, etc..) that have properties, events and methods.
Figure 1.8: Types of Programming
9|Page
PROGRAMMING FUNDAMENTALS 1.6.1 Structured Programming Structured programming takes on the top-to-bottom approach and based around data structures and subroutines. This programming splits the tasks into modular forms and makes the program simpler and easier to read with fewer lines and codes. A structured program is one consisting entirely of three types of logic structures; sequence structure, selection structure and iteration/ repetition structure. The example of sequence structure is as below.
Figure 1.9: Example of Structured Programming and Output
1.6.2 Modular Programming Modular programming is a software design technique that increases the extent to which software is composed from separate parts, called modules. Execution of a program begins in the main function, and the main function can call other functions: a. Functions defined in the same file. b. Function defined in other files or libraries.
10 | P a g e
PROGRAMMING FUNDAMENTALS
Figure 1.10: Example of the Modular Structure
1.6.3 Object-oriented Programming Object-oriented programming refers to a special type of programming approach that combines data with functions to create objects and these objects have relationships with one another. One of the earliest OOP languages is Smalltalk and the examples of popular OOP languages are Java, Visual Basic and C++. It uses sections in a program to perform certain tasks. and splits the program into objects (small programs) that can be reused in other programs. Each object or module has the data and the instruction of what to do with the data in it. This can be reused in other software decomposed into a network of collaborating objects.
11 | P a g e
PROGRAMMING FUNDAMENTALS 1.7
INPUT PROCESS OUTPUT Three steps that a program typically performs: i) Gather input data: a. from keyboard b. from files on disk drives ii) Process the input data iii) Display the results as output: a. send it to the screen b. write to a file
Figure 1.11: Input, Process and Output
12 | P a g e
PROGRAMMING FUNDAMENTALS 1.8
TYPES OF DESIGN TOOLS
Design tools are the tools used to develop a program. Three types of design tools are algorithm, pseudocode and flowchart.
1.8.1 Algorithm
A specific set of instructions for carrying out a procedure or solving a problem.
Usually with the requirement that the procedure terminate at some point.
Specific algorithms sometimes also go by the name method, procedure, or technique.
Step by step procedure designed to perform an operation, and which (like a map or flowchart) will lead to the sought result if followed correctly.
Algorithms have a definite beginning and a definite end, and a finite number of steps.
Below is an example of an algorithm and based on the problem statement.
PROBLEM STATEMENT
Step 1 Step 2 Step 3 Step 4
Write an algorithm to add two numbers entered by user.
: Start : Declare variables NUM1, NUM2 and TOTAL : Read values NUM1 and NUM2 : Add num1 and num2 and assign the result to sum TOTAL = NUM1 + NUM2
Step 5 : Display TOTAL Step 6 : Stop
“Algorithm is not the computer code. Algorithm are just the instructions which gives clear idea to write the computer code”
13 | P a g e
PROGRAMMING FUNDAMENTALS 1.8.2 Pseudocode
Pseudo code is an abbreviated version of actual computer code.
When the pseudo code is completed it can be easily translated into any computer language.
Artificial and informal language
Helps programmer to plan algorithm
Not an actual programming language
Each line of code represents a step/process.
Below is the example of pseudocode.
PROBLEM STATEMENT
The pseudo code below is to find the volume of a box if the length, width and height are given. Write the program based on the pseudo code below.
START INPUT length of the box INPUT width of the box INPUT height of the box Volume = Length X Width X Height DISPLAY volume of the box END
Figure 1.11: Example of the Program using Pseudocode 14 | P a g e
PROGRAMMING FUNDAMENTALS 1.8.3 Flowchart
Graphic representation of algorithm is known as a flowchart which consists of geometric symbols.
The symbols are connected by a line of arrows called flow lines.
The shape of the symbol indicates the type of operation that is to occur.
Flow from the top of the page to the bottom.
Figure 1.12: Flowchart Symbol and Function
15 | P a g e
PROGRAMMING FUNDAMENTALS
PROBLEM STATEMENT
Create a flowchart to add 2 numbers together and then display the result.
Step 1 - Describe the input, output information and formula Input : 2 numbers Process : Sum = A + B Output : Result sum of two numbers
2. Step 2 - Develop logical sequence of steps to solve problem
Figure 1.13: Flowchart of Problem Statement
16 | P a g e
PROGRAMMING FUNDAMENTALS 1.9
PROBLEM-SOLVING CONCEPT Problem-solving refers to the entire process of taking the statement of a problem and
developing a computer program that solves that problem.
Figure 1.14: Process of Problem-solving Concept
17 | P a g e
PROGRAMMING FUNDAMENTALS
CHAPTER 2
FUNDAMENTALS OF C LANGUAGE
Objectives:
At the end of this chapter, students should be able to:
Remember Variables, Constants and Data Types
Understand fundamentals of C Programme
Apply fundamentals of C Programming
18 | P a g e
PROGRAMMING FUNDAMENTALS 2.1
VARIABLES IN C PROGRAMMING 2.1.1 Data and Information
Figure 2.0: Data and Information
19 | P a g e
PROGRAMMING FUNDAMENTALS 2.2
VARIABLES Variable is a named location in a memory where a program can manipulate the data This location is used to hold the value of the variable. This value may change in the program. “In short, a variable is a place to store a piece of information. Just as you might store a friend’s phone number in your own memory.”
Variables should be declared in the C program before being used.
Memory space is not allocated for a variable while declaration. It happens only on the variable definition.
Syntax: data_type variable_name;
Example command to declare variable: int marks;
Figure 2.1: Example of Data Types and Variables
Variable initialization means assigning a value to the variable.
Syntax: data_type variable_name = value;
20 | P a g e
PROGRAMMING FUNDAMENTALS
Example: int x = 5; char alphabet = ‘Z’;
2.3
CONSTANT
Constant is the value that do not change during program execution.
Types of constant: 1) Integer Constant 2) Character & String Constant
The name of the constant or variable are also called Identifiers
To declare a constant, use keyword const.
Syntax: const data_type constant_name = value;
Example: const int days_of_week=7; const char alphabet= ‘G’; const string Answer = “Yes”;
Figure 2.2: Differentiation between Identifier, Variable and Constant
21 | P a g e
PROGRAMMING FUNDAMENTALS 2.3.1 Rules for Naming Constants and Variables In programming, a variable is a storage area to hold data. To indicate the storage area, each variable should be given a unique name (identifier). Variable names are just the symbolic representation of a memory location.
RULES FOR NAMING CONSTANTS AND VARIABLES
Must consists only of combining letters (uppercase A-Z and lowercase a-z), digits and underscore. First character must be a letter. Blank character is not permitted in an identifier.
The identifier cannot duplicate a reserved word. Identifiers can be of any length although in practice they seldom exceed 31 characters. Lower & uppercase letter in identifiers are treated as different characters. Figure 2.3: Rules for Naming Constants and Variables
22 | P a g e
PROGRAMMING FUNDAMENTALS 2.4
DATA TYPES C language has some predefined set of data types to handle various kinds of data that we can
use in our program. Data types specify what type of data we enter and how we enter data into our programs. Different data types have different storage capacities. Furthermore, data type determines the type of data a variable will hold. If a variable x is declared as int, it means x can hold only integer values. Every variable which is used in the program must be declared as what data type it is. C language supports two different types of data, primary data types and derived data types. Primary data types are fundamental data types in C namely integer(int), floating point(float), character(char) and void, while derived data types are primary data types grouped together like array, structure, union and pointer.
Figure 2.4: Primary Data Type
23 | P a g e
PROGRAMMING FUNDAMENTALS 2.4.1 Integer Data Type
Integer data type is used to store whole numbers.
Size and range of integer type on 16-bit machine are as in table below.
Table 2.1: Integer Data Type TYPE
SIZE(BYTES)
RANGE
int or signed int
2
-32,768 to 32767
unsigned int
2
0 to 65535
short int or signed short int
1
-128 to 127
unsigned short int
1
0 to 255
long int or signed long int
4
-2,147,483,648 to 2,147,483,647
unsigned long int
4
0 to 4,294,967,295
2.4.2 Floating Data Type
Floating point data type is used to store real numbers.
Size and range of floating-point data type on 16-bit machine are as in the table below. Table 2.2: Floating Data Type TYPE
SIZE(BYTES)
float
4
3.4E-38 to 3.4E+38
double
8
1.7E-308 to 1.7E+308
long double
10
3.4E-4932 to 1.1E+4932
2.4.3 Character Data Type 24 | P a g e
RANGE
PROGRAMMING FUNDAMENTALS
Character type - used to store characters value.
Size and range of character data type on 16-bit machine are as in the table below. Table 2.3: Character Data Type TYPE
2.5
SIZE(BYTES)
char or signed char
1
unsigned char
1
RANGE -128 to 127 0 to 255
FUNDAMENTALS OF C PROGRAM 2.5.1 Structure of C Program C++ program consists of objects, functions, variables, and other components. There are a few program structures that are very important for to understand why the program must be written in such way.
Figure 2.5: Structure of C Program
25 | P a g e
PROGRAMMING FUNDAMENTALS 2.5.2 Comments
A line starting with /* and ending with */ is a comment.
The purpose of a comment is to document and understand the program.
It can be used to tell what is the purpose of using variables or functions.
It also enables your program to be easily understood by others.
Comment will not be executed by the compiler.
2.5.3 Main function and functions
In programming, function refers to a segment that groups code to perform a specific task.
Depending on whether a function is predefined or created by programmer; there are two types of function: a)
Library Function
b)
User-defined Function
a)
Library Function
C Standard library functions or simply C Library functions are inbuilt functions
in C programming.
The prototype and data definitions of these functions are present in their
respective header files. To use these functions, we need to include the header file in our program. For example,
Figure 2.6: Function in C Program
26 | P a g e
PROGRAMMING FUNDAMENTALS b)
User-defined Function
C allows programmer to define their own function.
A user-defined function groups code to perform a specific task and that group of code is given a name(identifier).
When the function is invoked from any part of program, it all executes the codes defined in the body of function.
2.5.4
Pre-processor Commands
The C pre-processor or cpp is the macro pre-processor for the C and C++ computer programming languages.
The pre-processor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control.
In many C implementations, it is a separate program invoked by the compiler as the first part of translation.
The language of pre-processor directives is only weakly related to the grammar of C, and so is sometimes used to process other kinds of text files.
2.6
TYPES OF OPERATORS An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators.
a)
Assignment operators
b)
Arithmetic operators
c)
Relational Operators
d)
Logical Operators
e)
Unary Operators
f)
Increment Operators
g)
Decrement Operators
27 | P a g e
PROGRAMMING FUNDAMENTALS 2.6.1 Assignment Operators C provides several assignment operators for abbreviating assignment expressions. For example, the statement c = c + 3; can be abbreviated with the addition assignment operator += as c += 3; the += operator adds the value of expression on the right of the operator to the value of the variable on the left of the operator and stores the result in the variable on the left of the operator. Any statement of the form Variable = variable operator expression; Where operator is one of the binary operators +, -, *, / or %, can be written in the form Variable operator = expression; Thus, the assignment c += 3 adds 3 to c. Table shows the arithmetic assignment operators, sample expressions using these operators and explanations. Table 2.4: Assignment Operators ASSIGNMENT OPERATOR
SAMPLE EXPRESSION
EXPLANATION
ASSIGNS
Assume: int c = 3, d = 5, e = 4, f = 6, g = 13
28 | P a g e
+=
c += 7
c=c+7
10 to c
-=
d -= 4
d=d–4
1 to d
*=
e *= 5
e=e*5
20 to e
/=
f /= 3
f=f/3
2 to f
%=
g %= 9
g=g%9
4 to g
PROGRAMMING FUNDAMENTALS 2.6.2
Arithmetic operators All the basic arithmetic operations can be carried out in C. All the operators have
almost the same meaning as in other languages. Both unary and binary operations are available in C language. Table below shows the arithmetic operation and their meanings.
Table 2.5: Arithmetic Operator OPERATOR
2.6.3
MEANING
+
Addition or Unary Plus
–
Subtraction or Unary Minus
*
Multiplication
/
Division
%
Modulus Operator
Relational Operators Often it is required to compare the relationship between operands and bring out a
decision and program accordingly. This is when the relational operator come into picture. C supports the following relational operators.
Table 2.6: Relational Operator OPERATOR
29 | P a g e
MEANING
<
is less than
<=
is less than or equal to
>
is greater than
>=
is greater than or equal to
==
is equal to
!=
is not equal to
PROGRAMMING FUNDAMENTALS 2.6.4 Logical Operators C has the following logical operators; they compare or evaluate logical and relational expressions. Table 2.7: Logical Operator
i.
OPERATOR
MEANING
&&
AND
||
OR
!
NOT
Logical AND (&&)
This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true. Example: a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10.
ii.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true. Example: a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n.
30 | P a g e
PROGRAMMING FUNDAMENTALS
iii. Logical NOT (!) The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words, it just reverses the value of the expression. Example: ! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y.
Table 2.8: Result of logical operation on a and b are summarized as below: VARIABLE
EXPRESSION
A
B
A && B
A || B
!A
T
T
T
T
F
T
F
F
T
F
F
T
F
T
T
F
F
F
F
T
2.6.5 Unary Operators A unary operator is an operator used to operate on a single operand to return a new value. It is an operator that updates the value of an operand or expression's value by using the appropriate unary operator. This operator has equal priority from right to left side associativity. Following are the types of the unary operators in the C programming language. i.
Unary Minus (-)
ii.
Unary Plus (+)
iii.
Increment (++)
iv.
Decrement (--)
v.
Logical Negation (!)
vi.
Address Operator (&)
vii.
Size of ( ) operator
31 | P a g e
PROGRAMMING FUNDAMENTALS 2.6.6 Increment/Decrement Operators Increment operators are used to increase the value of the variable by one and decrement operators are used to decrease the value of the variable by one in C programs.
Syntax: Increment operator: ++var_name; (or) var_name++; Decrement operator: – -var_name; (or) var_name – -;
Example: Increment operator: ++ i ; i ++ ; Decrement operator: – – i ; i – – ;
Table 2.9: Increment/ Decrement Operators OPERATOR SAMPLE EXPRESSION
EXPLANATION Increment a by 1 then use the new value of a
++
++a
in the expression in which a resides Use the current value of a in the expression in
++
a++
which a resides, the increment a by 1 (Still remain same number) Decrement b by 1 the use the new value of b
--
--b
in the expression in which b resides
Use the current value of b in the expression in --
b--
which b resides, then decrement b by 1 (Still remain same number)
32 | P a g e
PROGRAMMING FUNDAMENTALS 2.7
HIERARCHY OF OPERATOR The hierarchy of operator precedence from highest to lowest is summarized below:
Table 2.10: Hierarchy of Operator OPERATOR CATEGORY Unary Arithmetic multiply, divide, remainder Arithmetic add and subtract Relational operators Equality operators
33 | P a g e
OPERATOR -
-- ++ * / % + -
< <= > >= == !=
Logical AND
&&
Logical OR
||
PROGRAMMING FUNDAMENTALS
CHAPTER 3
SELECTION STATEMENTS
Objectives:
At the end of this chapter, students should be able to:
Remember selection statement and types of control statement
Understand selection statement between if, if-else, nested if-else and switch statement
34 | P a g e
Apply selection statement
PROGRAMMING FUNDAMENTALS 3.1
PROGRAM CONTROL STATEMENT Control statements or known as logical structure or control structure refer to the order of
execution of instructions in a program. In all examples, the instructions were executed sequentially one by one, from top downwards. Most real-life problems require decision making, comparing values, and based on the comparison certain action will be taken. C provides structure that will allow the non-sequential execution of program instructions such as, instructions can be executed, repeated, or skipped.
Figure 3.0: Program Control Statement
35 | P a g e
a
whole block
of
PROGRAMMING FUNDAMENTALS 3.2
SEQUENCE STATEMENTS The sequence control structure is the simplest of all the structures. The program
instructions are executed one by one, starting from the first instruction and ending in the last instruction as in the program segment. Below are the examples of flowchart and program for sequence statement.
Figure 3.1: Flowchart of the Sequence Statement
#include<stdio.h> void main() { int x
=
5;
int y
=
10;
int Total; Total
=
x * y;
printf("\nTotal =%d\n",Total); } Figure 3.2: Flowchart of the Sequence Statement
36 | P a g e
PROGRAMMING FUNDAMENTALS 3.3
SELECTION STATEMENTS This type of control structure is usually used in structured programming. This control
structure will execute an instruction based on result of a condition or comparison. A condition will result either TRUE or FALSE. If the condition result is true, the control program will execute the instruction within the TRUE loop operation. Otherwise, it will execute the next instruction or the instruction within the FALSE loop operation. There are four types of selection or decision control which are if, if-else, nested if and switch-case.
3.3.1 if Statement The basic form of the if statement is: if (condition) { statement; } Figure 3.3: Basic Form of if Statement
In this form, the expression is first evaluated. If the expression evaluates to non-zero (meaning TRUE), the statement is executed; if it evaluates to zero (meaning FALSE), the statement following the if statement is executed. Again, it has one entry point and one exit point.
Figure 3.4: Flowchart of if Statement
37 | P a g e
PROGRAMMING FUNDAMENTALS 3.3.2 if…else (double alternative) Statement The basic form of the if…else statement is: if (condition) { statement 1; } else { statement 2; } Figure 3.5: Basic Form of if…else Statement In this form, the expression is first evaluated. If it evaluates to non-zero, statement1 is executed, otherwise (i.e, if it evaluates to zero) statement 2 is executed. The execution of the statements is mutually exclusive, meaning, either statement 1 is executed or statement 2, but not both. The statement can take the form of blocks.
Figure 3.6: Flowchart of if…else Statement
38 | P a g e
PROGRAMMING FUNDAMENTALS 3.3.3 if…else (multiple alternative) Statement The basic form of the if…else (multiple alternative) statement is: if (condition 1) { statement 1; } else if (condition 2) { statement 2; } else { statement 3; } Figure 3.7: Basic Form of if…else (multiple alternative) Statement
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
3.3.4 Nested if Statement The basic form of the nested if statement is: if (condition 1) if (condition 2) if (condition 3) statement 1; else statement 2; else statement 3; else statement 4; Figure 3.8: Basic Form of nested if Statement
In this nested form, condition 1 is evaluated. If it is zero, statement 4 is executed and the entire nested if statement is terminated; if not, control goes to the second if and condition 2 is
39 | P a g e
PROGRAMMING FUNDAMENTALS evaluated. If it is zero, statement 3 is executed; if not, control goes to the third if and condition 3 is evaluated. If it is zero, statement 2 is executed; if not, statement 1 is executed.
Figure 3.9: Flowchart of nested if Statement
3.3.5 Switch-case Statement Switch-case statement tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
40 | P a g e
PROGRAMMING FUNDAMENTALS The basic form of the switch-case statement is: switch(variable) { case value 1: Statement 1; break; case value 2: Statement 2; break; default: Statement 3; } Figure 3.10: Basic Form of switch-case Statement
Switch
Case
Main Components
Break
Default
Figure 3.11: Basic Form of switch-case Statement
41 | P a g e
PROGRAMMING FUNDAMENTALS The rules in switch-case statement: The keyword case must followed by variable, and colon :
Variable must be an integer or character.
Must be use break and default.
“Break is to stop the program. If not, every statement in the case will be implemented. Default is to implement the statement where there is no similarity to the input.”
42 | P a g e
PROGRAMMING FUNDAMENTALS
CHAPTER 4
LOOPING STATEMENTS
Objectives:
At the end of this chapter, students should be able to:
Remember looping statement and types of looping statement
Understand looping statement between for, while and do-while statement
Apply looping statement
43 | P a g e
PROGRAMMING FUNDAMENTALS 4.1
LOOPING STATEMENT The repetition (or iteration) structure permits a sequence of the instructions to be executed
repeatedly until certain condition is reached. Looping statement are used to execute a set of statement repeatedly based on condition. Three types of looping are as below:
for
while
• loops from one number to another number and increases by a specific value each time
• can be used if you don’t know how many times a loop must run
do-while • do something first and then test if we have to continue. The result is that the loop always runs once
Figure 4.0: Types of Looping Statement
Each loop must consist of initialization, condition and counter.
Initialization
The initialization is an assignment statement that is used to set the loop control variable Condition The condition is a relational expression that determines when the loop exists Counter The increment defines how the loop control variable changes each time the loop is repeated Figure 4.1: Initialization, Condition and Counter
44 | P a g e
PROGRAMMING FUNDAMENTALS 4.2
THE for LOOP The basic form of the for loop statement is: for(initialization;condition;counter) { statements; } Figure 4.2: Basic Form of for Loop Statement
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop. After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.
Figure 4.3: Flowchart of for Loop Statement 45 | P a g e
PROGRAMMING FUNDAMENTALS 4.3
THE while LOOP The basic form of the while loop statement is:
int initialization; while (condition) { statements; expression; } Figure 4.4: Basic Form of while Loop Statement
Statement for the while loop may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop. A while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Figure 4.5: Flowchart of while Loop Statement
46 | P a g e
PROGRAMMING FUNDAMENTALS 4.4
THE do-while LOOP The basic form of the do-while loop statement is: int initialization; do { statement; expression; } while (condition) Figure 4.6: Basic Form of do-while Loop Statement Unlike for and while loops, which test the loop condition at the top of the loop, the dowhile loop in C programming checks its condition at the bottom of the loop. A do-while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time. Notice that the conditional expression appears at the end of the loop, so the statement in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement in the loop executes again. This process repeats until the given condition becomes false.
Figure 4.7: Flowchart of do-while Loop Statement
47 | P a g e
PROGRAMMING FUNDAMENTALS 4.5
BREAK, CONTINUE AND GOTO 4.5.1
BREAK Break is used to exit a loop at any time or to stop running a loop. For example below,
the do-while loop will run, as long as i>0. If an ‘IF statement’ states that i=6, the do-while loop must stop (break).
Figure 4.8: Example Program and Output of Break Statement 4.5.2
CONTINUE With continue, it is possible to skip the rest of the commands in the current loop and
start from the top again. The loop variable must still be incremented.
Figure 4.9: Example Program and Output of Continue Statement 48 | P a g e
PROGRAMMING FUNDAMENTALS 4.5.2
GOTO A goto statement in C programming language provides an unconditional jump from
the goto to a labelled statement in the same function.
Figure 4.10: Example Program of Goto Statement
49 | P a g e
PROGRAMMING FUNDAMENTALS
CHAPTER 5
FUNCTION AND ARRAY
Objectives:
At the end of this chapter, students should be able to:
Remember function and array statement
Understand function statement between call by value and call by reference
Understand array statement
Apply function and array statement
50 | P a g e
PROGRAMMING FUNDAMENTALS 5.1
FUNCTION A function is a block of code that performs a particular task. There are times when we need
to
write a particular block of code for more than once in our program. This may lead to bugs and irritation for the programmer. C language provides an approach in which you need to declare and define a group of statements once and that can be called and used whenever required. This saves both time and space. C functions can be classified into two categories; predefined functions and user-defined functions.
5.1.1 Category of Function Already have a definition in header files (.h files like stdio.h), so we just call them whenever there is a need to use them. Example: puts(), gets(), printf(), scanf()
• User customize functions • Made for code reusability and for saving time and space.
PRE-DEFINED FUNCTION
USER-DEFINED FUNCTION
5.1.2 Objectives of The Function
To improve the reusability of the code. Debugging of the code would be easier if you use functions, as error are easy to be traced. Reduces the size of the code, duplicate set of statements are replaced by function calls.
51 | P a g e
PROGRAMMING FUNDAMENTALS 5.1.3 Syntax of The Function return_type function_name (argument list) { Set of statements – Block of code } Figure 5.0: Syntax of the Function
return_type: Return type can be of any data type such as int, double, char, void, short etc. function_name: It can be anything, however it is advised to have a meaningful name for the functions so that it would be easy to understand the purpose of function just by seeing it’s name.
argument list: Argument list contains variables names along with their data types. These arguments are kind of inputs for the function. For example – A function which is used to add two integer variables, will be having two integer argument.
Block of code: Set of C statements, which will be executed whenever a call will be made to the function. 5.1.4 Creating a User-Defined Function
Figure 5.1: Example of Creating a User-Defined Function Program 52 | P a g e
PROGRAMMING FUNDAMENTALS
“Notes regarding functions in C: 1. main() in C program is also a function. 2. Each C program must have at least one function, which is main(). 3. There is no limit on number of functions; A C program can have any number of functions. 4. A function can call itself and it is known as “Recursion“.”
5.1.4 More Functions in C
Function – Call by value method The actual arguments are copied to the formal arguments, hence any operation performed by function on arguments doesn’t affect actual parameters. Function – Call by reference method Address of actual arguments (or parameters) is passed to the formal parameters, which means any operation performed on formal parameters affects the value of actual parameters. Figure 5.2: Types of Function
5.1.5 Function Call by Value When we pass the actual parameters while calling a function then this is known as function call by value. In this case the values of actual parameters are copied to the formal parameters. Thus, operations performed on the formal parameters don’t reflect in the actual parameters. In the call by value, the actual arguments are copied to the formal arguments, hence any operation performed by function on arguments doesn’t affect actual parameters. 53 | P a g e
PROGRAMMING FUNDAMENTALS
Figure 5.3: Example of Function Call by Value Program 5.1.6 Function Call by Reference When we call a function by passing the addresses of actual parameters then this way of calling the function is known as call by reference. In call by reference, the operation performed on formal parameters, affects the value of actual parameters because all the operations performed on the value stored in the address of actual parameters.
Figure 5.4: Example of Function Call by Reference Program 54 | P a g e
PROGRAMMING FUNDAMENTALS 5.2
ARRAY An array is a collection of data that holds fixed number of values of same type. For example:
if you want to store marks of 100 students, you can create an array for it. float marks[100]; The size and type of arrays cannot be changed after its declaration. an int array holds the elements of int types while a float array holds the elements of float types. Example of array in C program as below:
Figure 5.5: Example of Array Program
5.2.1
55 | P a g e
Various Ways to Initialize an Array i.
int arr[5] = {1, 2, 3, 4 ,5};
ii.
int arr[ ] = {1, 2, 3, 4, 5};
PROGRAMMING FUNDAMENTALS 5.2.2
2D Array in C Programming An array of arrays is known as 2D array. The two-dimensional (2D) array in C
programming is also known as matrix. A matrix can be represented as a table of rows and columns. The following program demonstrates how to store the elements entered by user in a 2D array and how to display the elements of a two-dimensional array.
Figure 5.6: Example of Array Program
56 | P a g e
PROGRAMMING FUNDAMENTALS
REFERENCES
1.
Jeff Szuhay (2020) Learn C Programming, Packt Publishing.
2.
Scott Sanderson (2014) C Programming: C Programming Language Guide for Beginners, CreateSpace Independent Publishing Platform.
3.
https://www.programiz.com/c-programming
4.
https://www.tutorialspoint.com
56 | P a g e