Ebook ProgrammingFundamental 2021
Ebook ProgrammingFundamental 2021
I|Page
PROGRAMMING FUNDAMENTALS
I|Page
Published and printed by:
Department of Electrical Engineering
Politeknik Kota Bharu
KM. 24, Kok Lanas, 16450 Ketereh, Kelantan.
Programming Fundamentals
All rights reserved. No part of publication may be reproduced, stored in any form or by
any means, electronic, mechanical, photocopying, recording or otherwise without prior
written permission of the copyright holder.
B.C Chung
Programming Fundamentals/ B.C.Chung
II | P a g e
PREFACE
Apart from our efforts, the success of any book writing project depends largely on the
encouragement and guidelines of many others. We would like to take this opportunity
to express our sincere gratitude to the people who have been instrumental in the
successful completion of this book. Finally Programming Fundamentals book was
successfully published after working hard preparing this book since June 2020. This
book is written and published as a guide or reference to all engineering students in
polytechnic about the fundamental programming. This book will expose students to
the application of C programming. C Programming is a general-purpose programming
language that is extremely popular, simple and flexible. It is machine-independent,
structured programming language which is used extensively in various applications.
I would like to express appreciation to committee member Nik Rahaya Binti Nik Ishak
and linguist Melissa Khor Suan Chin for her effort in completing this book. Hopefully
this book can preferably utilized by all lecturers and students. Thank you.
III | P a g e
SYNOPSIS
This book contains a description of the basic concepts needed in learning fundamental
programming. Each chapter has an example of a program. Apart from that, this book
also has exercises that allow you to use it yourself with the topics described. This book
contains several chapters namely the contents of the Introductory to Programming,
Fundamentals of C Language, Selection Statements, Looping Statements, Function
and Array.
IV | P a g e
About the Authors
V|Page
CONTENTS
CHAPTER TITLE PAGES
1.0 INTRODUCTORY TO PROGRAMMING
1.1 Programming Language 1
1.2 Types Of Programming 3
CHAPTER 1.3 Types Of Programming Languages 4
1.4 Algorithm, Flowchart And Pseudocode 4
1 1.5 Apply algorithm, flowchart, pseudocode and analyse 8
problem
1.6 Tutorials 10
2.0 FUNDAMENTALS OF C LANGUAGE
2.1 Variables, Constants And Data Types 13
CHAPTER 2.2 Understand Fundamentals Of C Programme 16
2.3 Apply Fundamentals Of C Programming 24
2 2.4 Tutorials 28
2.5 Practical Activities 31
3.0 SELECTION
3.1 Remember SELECTION Programmes 34
CHAPTER 3.2 Understand SELECTION Programmes 40
3.3 Apply SELECTION Programmes 42
3 3.4 Tutorials 46
3.5 Practical Activities 48
4.0 LOOPING
4.1 LOOPING Programmes 53
CHAPTER 4.2 Understand LOOPING Programmes 60
4.3 Apply LOOPING statements 62
4 4.4 Tutorials 68
4.5 Practical Activities 71
5.0 FUNCTION
5.1 FUNCTION Programmes 73
5.2 Remember FUNCTION Programmes 73
CHAPTER
5.2 Understand FUNCTION Programmes 76
5.3 Apply FUNCTION Programmes 78
5
5.4 Tutorials 81
5.5 Practical Activities 82
6.0 ARRAYS
6.1 ARRAYS Programmes 85
CHAPTER 6.2 Understand ARRAYS Programmes 90
6.3 Apply ARRAYS Programmes 98
6 6.4 Tutorials 101
6.5 Practical Activities 102
7.0 DEMONSTRATE THE I/O OPERATION 106
REFERENCES 126
VI | P a g e
1.0 INTRODUCTORY TO PROGRAMMING
INTRODUCTION
The word computer was derived from the word compute, which means to calculate. Computers
were introduced to perform fast and accurate calculations. Today, computers are widely used
in almost all fields. Computers, however, have to be instructed by humans to perform any task.
The instructions are given in the form of programs. In this unit, you will learn the different types
of programming languages and the various programming techniques involved in writing
programs.
Note
1.1 PROGRAMMING LANGUAGE
Computer needs human to provide it with instructions to make it perform tasks. These
instructions must be provided in a language that the computer understands. This language
through which humans communicate with computers is known as programming language.
1.1.1 C programming
C is a computer programming language which can use to create lists of instructions
for a computer to follow. C is a compiled language which means it must run through
a C compiler to turn the program into an executable that the computer can run
(execute). The C program is the human-readable form, while the executable that
comes out of the compiler is the machine-readable and executable form.
1 | Page
language named B. C is portable, powerful and flexible. Because of these features, C
is used for both system and application level programming. C is reliable, simple and
easy to use. It is easier to learn newer languages once you are familiar with C
language.
2 | Page
1.2 TYPES OF PROGRAMMING
a. Low-Level Languages
Low-level languages are programming languages in which programs are written
based on the internal architecture (design) of machines. Low-level languages are
further divided into two types:
i. Machine language
Machine language is the only language that computers can understand and
all the instructions in this language are in the form of 1s and 0s.
ii. Assembly language
Assembly language is a programming language that use symbolic instructions
called mnemonics or names.
b. High-Level Language
High-level languages are programming languages that use English words and
mathematical symbols to represent instructions in programs.
Advantages:
i. Programs written in high-level languages are almost machine- independent.
ii. Programmer need not know about computer hardware to write programs in
high-level languages.
3 | Page
iii. It is easier to learn and write programs in high-level languages than low-level
languages.
4 | Page
Characteristics of Algorithms
a. Flowchart Symbols
Table 1.4.2 shows the basic flowchart symbols used for representing the
different types of instructions.
Symbol Name
This symbol is used to represent the starting and
ending point in the program logic flow. Every
Terminal
flowchart should have only one start and one
end terminal symbol
This symbol is used to either accept the input or
Input/Output to display the output data.
5 | Page
This symbol is used to represent the flow of the
algorithm. The exact sequence in which the
Flow Lines
instructions are executed is represented using
this symbol.
This symbol is used to join a flowchart that is
drawn in many pages. A pair of identically
Connectors
labelled connector symbol is used to indicate a
continued flow of the flowchart
Table 1.4.2: Flowchart Symbols
b. Flowchart Examples
Start
Mark1? Mark2?
Total=mark1+mark2
Total
End
c. Advantages
● A flowchart is easy to understand since it is a graphical representation of the
problem.
● If any errors occur in the program at a later stage, a programmer can easily
identify the reason for the error by looking at the flowchart.
● A flowchart helps the programmer to avoid forgetting any steps while writing a
program.
● It is easier to write programs after drawing the flowchart.
d. Disadvantage
● It is very difficult to draw the flowchart for programs that contain complex
branches and loops.
6 | Page
1.4.3 Pseudocode in programming
Pseudocode is a detailed description of what a computer program or algorithm must
perform. It is an outline of program that can be converted into programming
instruction. Pseudocode use special reserved words for expressing the logic of
programs.
a. Pseudocode keyword
Table 1.4.3 lists the keywords that are used in a pseudocode.
Keyword Description
// Refers to a comment entry. It is used to give additional
information about the program. It can be used anywhere
inside the pseudocode.
begin Specifies the block of statements that performs a specific task.
--- The first statement is the begin statement and the last
statement is the end statement. The other instructions are
end given between these two statements.
Accept Accepts the input values.
Display Displays the output.
Set Initialises the value of variables.
if --- else Specifies the condition and the block of statements that are
executed based on the condition.
for Specifies the conditions and number of times the block has to
be executed based on the condition.
Table 1.4.3 : Keywords Used in Pseudocode
b. Pseudocode Examples
begin
accept the mark1 and mark2 obtained by the student
add mark1 and mark2 into the running total
display total
end
c. Advantages
● It enables even a non-programmer to understand the working of programs.
● The time taken to write pseudocode is less compared to drawing a
flowchart.
● It is easier to modify the pseudocode compared to modifying flowcharts.
7 | Page
● A pseudocode can easily be converted into a program by replacing the
pseudocode instructions with equivalent program statements.
a. Sequence structure
b. Selection structure
c. Looping structure
1.5.3 Sequence structure
8 | Page
In a sequence structure, all the instructions in the program must run one after
another. There is no skipping of any instruction; no task is skipped in the sequence.
Here, the instructions are executed one by one, or in sequence.
a. Sequential structure
Figure 1.5.3 shows the flowchart for sequential execution of instructions.
a. Selection structure.
Statement 1 Statement 2
a. Looping structure
False
Condition
?
True
Process
Tutorial
a) List THREE (3) types of programming
b) Define the following terms
c) Draw the flowchart to calculate the average of three numbers
d) Define the programming language and list TWO (2) types of programming languages.
e) Sketch the flowchart by referring the pseudocode below :
Start
10 | Page
f) Write a pseudocode based on flowchart below :
Start
Enter radius
Calculate area of the circle = pi X radius X radius
Display area
End
11 | Page
2.0 FUNDAMENTALS OF C LANGUAGE
INTRODUCTION
Before you start writing programs, it is very important to understand the basic elements that
are used in constructing simple C statements. These are C character set, variables, constants,
data types and keywords as shown in Figure 2.0.
12 | Page
Note
2.1 VARIABLES, CONSTANTS AND DATA TYPES
The type of data for the variables and constants determines the type of information to
be stored in the allocated memory space in C programming.
Programming languages require the programmer to declare the data type of every
data object used in the program.
C supports several different types of data. The following are the basic data types
available in C:
13 | Page
Integer A whole number, a number that has no fractional part.
Character A single character or a group of characters (string).
Floating-point A number with a decimal point.
Byte a group of binary digits or bits (usually eight) operated on as a unit.
Long A word is a fixed-sized piece of data handled as a unit by the instruction
set or the hardware of the processor.
Double A word is a fixed-sized piece of data handled as a unit by the instruction
set or the hardware of the processor.
String A word is a fixed-sized piece of data handled as a unit by the instruction
set or the hardware of the processor.
Word A word is a fixed-sized piece of data handled as a unit by the instruction
set or the hardware of the processor.
Table 2.1.2: Data types available in C
2.1.3 Keywords in C
Definition: Keywords are reserved words for which the meaning is already defined
to the compiler.
C has special reserved words that cannot be used as identifiers. These are keywords.
There are 32 keywords in C language. They are listed in Table 2.1.3.
Types Keywords
Data types, modifiers and void, int, char, float, double, signed,
storage class specifiers unsigned, long, short, auto, const,
extern, static, volatile, register and
typedef
User defined data types struct, union, enum and sizeof
and type related
Conditional if, else, switch, case and default
Flow control for, while, do, break, continue, goto and
return
Table 2.1.3: Keywords in C Language
14 | Page
Computer stores data in the computer memory in a specific location. To use the
data, you must know the address of the memory location, where the data is stored.
The name given to this memory location is called a variable. The data of a variable
changes during the execution of the program.
Any variable used in a program must be declared in the beginning. This is to specify
the variable data type to the compiler. Table 2.1.5 lists some of the declarations
used in C language.
15 | Page
a. Variable declaration : Example 1
char student_name;
Data type is character student_name is a variable
int mark;
Data type is integer. mark is a
variable..
▪ age is a variable, which can take integer value.
float mark2;
Data type is float. Mark2 is a variable.
.
▪ mark is a variable, which can take integer value.
16 | Page
2.2.2 Structure of a function in the main function
main() is the function where the program is written. Any C program will have one
or more functions and the most important function, which must be present in all
the programs, is the main() function. A program can have only one main() function.
2.2.3 C Preprocessor
#include <stdio.h> is a preprocessor directive statement. This statement directs the
preprocessor to include the standard input and output header file.
The symbol hash (#) will invoke the preprocessor directives. Preprocessor directives
are the instructions given to the compiler. The keyword include will direct the
preprocessor to include the specified header file into the program. A header file
contains definition for all the functions that could be shared by several other
programs.
Syntax
#include <filename>
Example
#include <stdio.h>
17 | Page
2.2.5 Differentiate constants and variables in C
Difference between variables and constants.
Variables Constants
Variable is the name given to the Constant is a location in the memory that
memory location where the data is stores data that never changes during the
stored. This value keeps changing execution of the program.
during the program execution.
Example: Example:
a, grade and mark 10, 'A' and 78.90
Table 2.2.5: Difference Between Variables And Constants
a. Input Statement
Definition: Input statements are used for accepting data from the user.
scanf( )
scanf( )
Definition: scanf()is a function, used as a statement, to get the value from
the user.
Example
The scanf()function has two parameters: the format specifier and the variable.
These parameters have to be separated by the delimiter comma (,). In the example,
scanf statement will request the user to enter the age. The variable age is of an
integer data type.
18 | Page
The symbol ampersand (&) refers to the address of a variable in the memory. The
input data has to be stored in the memory addressed by that variable.
Syntax
Format Specifiers
Definition: Format specifier defines the data type of the variable to the compiler.
To accept a value, you must specify the type of data expected. Consider the example
given for scanf(). As the variable age is integer type, the format specifier, %d, is used.
It indicates that the variable age is of integer type.
Some of the commonly used format specifiers are listed in Table 2.2.6.
b. Output Statement
Definition: Output statements are used for displaying the processed data on
the screen.
printf( )
Example 1
printf("Welcome");
Output
Welcome
Welcome
Output
My age is 16
In example 2, age is a variable of integer data type. Assume that the user enters the
value 21 for the variable age. To display the value of a variable on the screen, the
relevant format specifier must be specified within double quotes.
Syntax
Definition: Escape sequences are nonprinting characters that are used for
formatting the output.
20 | Page
Definition: An operator is a symbol that instructs C to perform some operation, or
action.
In a program, for adding two numbers you need to use the addition (+) operator.
Similarly, for comparing two numbers you need to use a comparison operator. It is
therefore necessary to use the appropriate operators to perform these calculations.
For example, + is an operator that represents addition.
Example
c=a+b
In this code line, + is an operator and a, b and c are called operands. Operands are
the variables/constants on which the operators operate.
a. Assignment operators
Definition: Assignment operator (=) is used to assign a value to a variable.
Example1
In a C statement, the right side of the operator can be any expression, and the left
side must be a variable name. Thus, the form is as follows:
Variable = expression;
Example2
x = y + z;
21 | Page
b. Mathematical Operators
Definition: Mathematical operators are used for performing simple
mathematical calculations such as addition, subtraction, multiplication and
division.
c. Relational Operators
Definition: Relational operators are used to compare two operands.
The output of the expression will be a Boolean value, which is either 0 (false) or 1
(true). The various relational operators are listed in Table 2.2.7c.
22 | Page
Symbol Description Example
> Greater than a>b
< Lesser than a<b
>= Greater than or equal to a>=b
<= Less than or equal to a<=b
!= Not equal to a!=b
== Equal to a==b
Table 2.2.7c: Relational Operators
d. Logical Operators
Definition: Logical operators are used to combine two simple statements into a
compound statement.
Using logical operators, you can simulate Boolean algebra in C. The various logical
operators are listed in Table 2.2.7d.
Minus sign (-) is used for substraction as a binary operator and for negotiation as an
unary operator.
result = -x * y;
23 | Page
f. Increment Operators
Definition: Increment operators are used to increase the value of the variable by
one in C programs.
Syntax
++var_name; (or) var_name++;
g. Decrement Operators
Definition: Decrement operators are used to decrease the value of the variable by
one in C programs.
Syntax
--var_name;
(or)
var_name--;
1. #include <stdio.h>
2. main()
3. {
4. printf(" WELCOME ")
5. }
24 | Page
Step 2: Save the program.
Step 3: output.
1. #include <stdio.h>
2. main()
3. {
4. int age;
5. char grade;
6. float mark;
7. printf("\n Enter the age : ");
8. scanf("%d",&age);
9. printf("\n Enter the grade : ");
10. scanf("%c",&age);
11. printf("\n Enter the mark : ");
12. scanf("%f",&mark);
13. return 0;
14. }
1. #include <stdio.h>
2. main()
3. {
4. int age;
5. char grade;
6. float mark;
7. printf("\n Enter the age : ");
8. scanf("%d",&age);
9. printf("\n Enter the grade : ");
25 | Page
10. scanf("%c",&age);
11. printf("\n Enter the mark : ");
12. scanf("%f",&mark);
13. printf("\n The age :%d ",age);
14. printf("\n The grade :%c ",grade);
15. printf("\n The mark :%f ",mark);
16. return 0;
17. }
1. #include <stdio.h>
2. main()
3. {
4. int mark1, mark2;
5. float total;
6. printf("\n Enter the mark1 : ");
7. scanf("%d",&mark1);
8. printf("\n Enter the mark2 : ");
9. scanf("%d",&mark2);
26 | Page
10. total=mark1+mark2;
11. printf("\n %d + %d = %.2f",mark1,mark2,total);
12. return 0;
13. }
Step 2: Save the program.
2.3.8 Implement mathematical calculations using the function in the main function
1. #include <stdio.h>
2. int addition(int var1, int var2)
3. {
4. int sum;
5. sum = var1+var2;
6. return sum;
7. }
8. int main()
9. {
10. int num1, num2;
11. printf("Enter number 1: ");
12. scanf("%d",&num1);
13. printf("Enter number 2: ");
14. scanf("%d",&num2);
15. int total = addition(num1, num2);
16. printf ("Output: %d", total);
17. return 0;
18. }
27 | Page
Tutorial
a) List THREE (3) types of operator used in C programming
b) Recognize the listed keyword in the table B1 as reserved word OR not reserves word C
Programming, then complete below:
c) Observe every line and list the errors found on the following program below:
/?Compute volume of a Cone program?
#<include>stdio.h
#default PI 3.142
main()
{
double rad, Volume, height;
28 | Page
e) Rewrite the following manes to be valid identifier
i. 4th value
ii. Order-no
iii. Error flag
iv. Break
v. @google.com
Start
Read user height as float
Read user weight as float
Calculate BMI = weight (kg)
height2(m2)
Display BMI
End
29 | Page
j) Describe the function of each basic symbols in the table below that commonly used in
flowchart:
Symbol Function
i.
ii.
iii.
iv.
v.
#include<stdo.h>
main();
{
int x,y;
x = 10;
y = x++;
printf("%f", x);
printf("%d", &y);
}
l) Pak Ali, a durian seller’s wants to use a computer in his selling. He is using the scale in
pounds, but the selling is done in kg.
Use a C language to write a program to help him change each weight of durian from
pound to kg.
(1kg = 2.205 pound @ 1 pound = 0.404kg)
30 | Page
Practical Activities
Program 1
#include<stdio.h>
main()
{
char name[20];
int staff_no;
printf("Enter your name:");
scanf("%s",&name);
printf("Enter your Staff No:");
scanf("%d",&staff_no);
printf("Mr/Ms %s, your Staff No is %d",name,staff_no);
return 0;
}
Program 2
#include<stdio.h>
main()
{
int num1, num2;
float num3,num4,num5;
char cha, name[20];
printf("Input from user\n");
printf("Enter a Character\n");
scanf("%c",&cha);
printf("Enter a your name\n");
scanf("%s",&name);
printf("Enter 2 integer numbers number\n");
scanf("%d %d",&num1,&num2);
printf("\nEnter 3 floating point number\n");
scanf("%f %f %f",&num3,&num4,&num5);
printf("\n Output to user");
printf("\nThe two numbers You have entered are %d and %d", num1, num2);
printf("\nThe float or fraction that you have entered is %.1f, %.2f and %.3f.",
num3,num4,num5);
printf("\nThe character that you have entered is %c", cha);
printf("\nThe character that you have entered is %s", name);
return 0;
}
31 | Page
Program 3
#include <stdio.h>
main()
{
int A,B,C,jumlah1,jumlah2,jumlah3;
float purata;
printf("input statement\n");
printf ( "sila masukan nilai A=");
scanf("%d",&A);
printf ( "sila masukan nilai B=");
scanf("%d",&B);
printf ( "sila masukan nilai C=");
scanf("%d",&C);
printf("\noutput statement");
jumlah1=A+B+C;
printf("\n jumlah %d + %d +%d = %d ",A,B,C,jumlah1);
jumlah2=A-B-C;
printf("\n jumlah %d - %d -%d = %d ",A,B,C,jumlah2);
jumlah3=A*B*C;
printf("\n jumlah %d X %d X %d = %d ",A,B,C,jumlah3);
purata=(A+B+C)/3;
printf("\n purata (%d + %d + %d)/3 = %d ",A,B,C,purata);
return 0;
}
Program 4
#include <stdio.h>
int main()
{
double firstNumber, secondNumber, product1,product2;
printf("Enter two numbers: ");
scanf("%lf %lf", &firstNumber, &secondNumber);
product1 = firstNumber * secondNumber;
printf(" \n Product = %.2lf", product1);
Program 5
#include <stdio.h>
int main()
{
float r1,r2,r3,rt;
32 | Page
printf("Enter the value of resistor 1:");
scanf("%f",&r1);
printf("Enter the value of resistor 2:");
scanf("%f",&r2);
printf("Enter the value of resistor 3:");
scanf("%f",&r3);
rt=r1+r2+r3;
printf("Total resistance in series:%.2f\n",rt);
return 0;
}
Program 6
#include <stdio.h>
int main()
{
float v,i,r;
printf("Enter the value of current flow through the circuit:");
scanf("%f",&i);
printf("Enter the value of total resistance in the circuit:");
scanf("%f",&r);
v=i*r;
printf("The voltage value of the circuit:%.2f\n",v);
return 0;
}
Program 7
#include<stdio.h>
#include<math.h>
main()
{
int p,t;
float r,Simple_Interest,amount,Compound_Interest;
printf("Please enter principal,time and rate of interest\n");
scanf("%d%d%f",&p,&t,&r);
Simple_Interest=p*t*r/100;
printf("\nSimple interest = %.2f",Simple_Interest);
amount=p*pow((1 +r/100),t);
Compound_Interest=amount-p;
printf("\nCompound interest = %.3f",Compound_Interest);
return 0;
}
33 | Page
3.0 Selection Statements
INTRODUCTION
Selection statements to make programs more user-interactive and flexible is to make the
program able to handle more than one case. By using of selection statements allow a
program to test several conditions, and execute instructions based on which condition is
true. That is why selection statements are also referred to as conditional statements.
Note
When it comes to computer programs, there is always a trade-off between the program's
flexibility and the ease of using the program. Generally, the simpler a program is, the less
flexible (and less powerful) the program will be. Programs that are very easy to use are
usually not very flexible and often only work for a narrow range of problems. Having
selection statements in a program make the program more flexible.
Selection statements are used to evaluate expression and direct the execution of
the program, depending on the result of the evaluation.
a. if
b. if-else
c. nested if else
d. switch
3.1.3 Define IF, IF-ELSE, NESTED IF ELSE and SWITCH statements
34 | Page
b. The if-else statement is used to execute set of statements based on the
condition.
c. The nested if else statement is present inside the body of another “if” or “else”
statement.
d. The switch statement is used when you choose from a number of choices.
3.1.5 Describe structure of simple IF, IF-ELSE, Nested IF-ELSE and SWITCH statements
First, the if statement will evaluate the condition. If the condition evaluates to true,
the conditional statements are executed. If the condition evaluates to false, the
conditional statements are not executed. The execution of conditional statement
depends on the result of the condition.
35 | Page
if (<Conditional expression>)
{
<Conditional statements>; Body
b. structure of if-else:
The if-else statement will first check the condition. When the condition is fulfilled,
conditional statements1 will be executed. When the condition not fulfilled,
conditional statements2 will be executed.
36 | Page
if (<Conditional expression>)
{ True-
Condition
<Conditional statements1>; Fulfilled
}
else
{
False -
<Conditional statements2>; Condition Not
} Fulfilled
else
else
The nested if-else statement will first check the condition 1. When the condition is
fulfilled, the nested statement will check again the condition 2. When the condition
2 is fulfilled conditional statements1 will be executed. If not statement 2 will be
executed. If condition 1 not fulfilled conditional statements 3 will be executed.
37 | Page
The syntax for the if-else statement is:
True-
Condition
if (<Conditional expression 1>)
1 Fulfilled
{
True-
if (<Conditional expression 2>)
Condition 2
Fulfilled
<Conditional statements1>;
else
False -
<Conditional statements2>; Condition Not
Fulfilled
}
else
False -
{ Condition Not
<Conditional statements3>; Fulfilled
d. structure of switch:
38 | Page
The syntax for switch statement is:
switch (<expression>)
{
case <condition 1>:
<Statements 1>;
break;
case <condition 2>:
<Statements 2>;
break;
...
case <condition n>:
<Statements n>;
break;
default:
<default Statements >;
}
The expression following the keyword switch can either be an integer expression or
a character expression. An integer or a character constant follows the keyword case.
Based on the value returned by the expression, the respective case is executed. The
expression is first evaluated and this value is then matched against the constants in
each case. When a match is found, the statements following that particular case
statement are executed. If no match is found, the statements following the default
case are executed.
The keyword break must be included in each case. A break statement will enable
you to skip all the cases following the current case and transfer the control outside
the switch statement.
39 | Page
3.2 Understand and apply selection statements
3.2.1 Differentiate programs simple IF, IF-ELSE, Nested IF-ELSE and SWITCH statements
a. Program IF
#include <stdio.h>
void main()
{
int day;
printf("Number of days in December : ");
scanf("%d",&day); // Accepts the input from the user and stores it in the variable days.
if (day == 31) // This expression will check whether the value of days is equal to 31.
{
printf(" You are correct. "); // This statement will be executed when days is equal to 31.
}
printf(" \n You are out of if branch. ");
}
b. Program IF-ELSE
SAMPLE if-else statement. This program accepts two integers from the user and
finds the greater of the two.
40 | Page
#include <stdio.h>
main()
{
int x,y;
printf("Enter X and Y values : ");
scanf("%d %d",&x,&y);
if (x > y) // This expression will check whether the value of x is greater than the value of y.
{
printf(" X is greater than Y"); // This statement will be executed when x is greater than y.
}
else // If x not greater than the value of y.
{
if (x==y) // This expression will check whether the value of x is equal to value of y.
{
printf(" Y is equal to X"); // This statement will be executed when x is equal to y.
}
else
{
printf(" Y is greater than X"); // This statement will be executed when y is greater than x.
}
}
}
d. Program Switch
#include <stdio.h>
void main()
{
int x;
printf("\n Enter the value for X (1,2 or 3) : ");
scanf("%d",&x);
switch (x) // The value of x will be checked against each case and the corresponding statements will
be executed.
{
case 1: // This case is executed when the value of x is 1.
printf(" You have entered One ");
break;
case 2: // This case is executed when the value of x is 2.
printf(" You have entered Two ");
break;
case 3: // This case is executed when the value of x is 2
printf(" You have entered Three ");
break;
default: // This case is executed when the value of x is not equal to 1, 2 or 3.
printf(" Wrong Entry ");
}
}
41 | Page
3.3 Apply selection statements
3.3.1 Construct programs simple IF, IF-ELSE, Nested IF-ELSE and SWITCH statements
a. Sample program IF
Series
illustrate the working of IF statements to calculate the total resistance for series
circuit and get the output
Program:
#include <stdio.h>
main()
{
int selection;
float series, parallel;
float R1=100,R2=300, R3=500;
printf("1: Series Circuit\n");
printf("Please Select your choice \n ");
scanf("%d", &selection);
if (selection==1)
{
series = R1+R2+R3;
printf(" Total resistance = %.2f Ohm\n",series);
}
return 0;
}
Series Parallel
42 | Page
Illustrate the working of IF-ELSE statements to calculate the total resistance for
series and parallel circuit and get the output.
#include <stdio.h>
main()
{
int selection;
float series, parallel;
float R1=100,R2=300, R3=500;
printf("1: Series Circuit\n");
printf("2. Parallel Circuit \n");
printf("Please Select your choice \n ");
scanf("%d", &selection);
if (selection==1)
{
series = R1+R2+R3;
printf(" Total resistance = %.2f Ohm\n",series);
}
else if (selection==2)
{
parallel = 1/(1/R1 +1/R2+1/R3) ;
printf(" Total resistance = %.6f Ohm\n",parallel);
}
else
{
printf(" wrong choice \n ");
}
return 0;
}
Series Parallel
Illustrate the working of Nested IF-ELSE statements to calculate the total resistance
for series and parallel circuit and get the output.
43 | Page
#include <stdio.h>
main()
{
int selection1,selection2;
float series, parallel;
float R1=100,R2=300, R3=500;
printf("1:You want to do the calculation\n");
scanf("%d", &selection1);
if (selection1==1)
{
printf("1: Series Circuit\n");
printf("2. Parallel Circuit \n");
printf("Please Select your choice \n ");
scanf("%d", &selection2);
if (selection2==1)
{
series = R1+R2+R3;
printf(" Total resistance = %.2f Ohm\n",series);
}
else
{
parallel = 1/(1/R1 +1/R2+1/R3) ;
printf(" Total resistance = %.6f Ohm\n",parallel);
}
}
else
{
printf(" wrong choice \n ");
}
return 0;
}
RT = R1 + R2 + R3
Series Parallel
Illustrate the working of SWITCH statements to calculate the total resistance for
series and parallel circuit and get the output.
44 | Page
#include <stdio.h>
main()
{
int selection;
float series, parallel,C1,C2,C3;
printf("******************************************");
printf("\nEnter the value of C1= ");
scanf("%f",&C1);
printf("\nEnter the value of C2= ");
scanf("%f",&C2);
printf("\nEnter the value of C2= ");
scanf("%f",&C3);
printf("******************************************");
printf("\n1: Series Circuit");
printf("\n2. Parallel Circuit ");
printf("\nPlease Select your choice ");
printf("******************************************");
scanf("%d",&selection);
switch(selection)
{
case 1:
series = 1/(1/C1 +1/C2+1/C3) ;
printf(" Total series capacitance = %.6f Farad\n",series);
break;
case 2:
parallel = C1+C2+C3;
printf(" Total parallel capacitance = %.2f Farad\n",parallel);
break;
default:
printf(" wrong choice \n ");
}
return 0;
}
45 | Page
Tutorial
a) Explain switch statements
b) Write a program that request two integer number as input from user to test both input
is non zero or not. Use if-else statement and AND logical operators.
c) Draw flowchart for if-else statement and switch-case statement.
d) Carry out a program that ask user to enter the total of 100 marks and then display the
letter grade and wish based on diagram below:
h) Produce C language to display the examination result status and grade point when a
mark is entered by user using if statement. The grading classification is shown in the
table below:
46 | Page
Mark Grade Status
75-100 A PASS
60-74 B PASS
47-59 C PASS
40-46 D FAIL
20-39 E FAIL
0-19 F FAIL
Request an input price for one item. Next, quantity of such item should also be entered.
Calculate the total price of the items using the formula : (price * quantity = total). If the
to tal price exceeds RM100, the rebate of 15% will be offered, but no deduction is
granted if otherwise.
l) Use C language to write a program that accept values of 2 numbers from the user,
compare their size and display the result on the screen. The output as follows:
Option 1 Option 2
Enter value for first number : 4 Enter value for first number : 6
Enter value for secondnumber : 3 Enter value for secondnumber : 8
First number is larger number than Second number is larger number than
second number first number
m) Use C language to write a program to calculate the total income of salesperson if the
commission is given based on the table below:
switch (color) {
Practical Activities
Program 1:
#include<stdio.h>
main()
{
int number;
printf("Please enter a number:\n");
scanf("%d",&number);
if(number < 500)
printf("Number is less than 500!\n");
return 0;
}
Program 2:
#include<stdio.h>
main()
{
int number;
printf("Please enter a number:\n");
scanf("%d",&number);
if(number < 500)
48 | Page
printf("Number is less than 500!\n");
else
printf("Number is greater than 500!\n");
return 0;
}
Program 3:
#include<stdio.h>
main()
{
int number;
printf("Please enter a number:\n");
scanf("%d",&number);
if(number < 500)
printf("Number is less than 500!\n");
else if(number == 500)
printf("Number is 500!\n");
else
printf("Number is greater than 500!\n");
return 0;
}
Program 4:
#include <stdio.h>
main()
{
int selection;
float series, parallel,R1,R2,R3;
printf("******************************************");
printf("\nEnter the value of R1= ");
scanf("%f",&R1);
printf("\nEnter the value of R1= ");
scanf("%f",&R2);
printf("\nEnter the value of R1= ");
scanf("%f",&R3);
printf("******************************************\n");
printf("1: Series Circuit\n");
printf("2. Parallel Circuit \n");
printf("Please Select your choice \n ");
scanf("%d", &selection);
if (selection==1)
{
series = R1+R2+R3;
printf("series = R1+R2+R3;");
printf("\n Total resistance = %.2f Ohm\n",series);
}
else if (selection==2)
49 | Page
{
parallel = 1/(1/R1 +1/R2+1/R3) ;
printf("parallel = 1/(1/R1 +1/R2+1/R3) ;");
printf(" \nTotal resistance = %.6f Ohm\n",parallel);
}
else
{
printf(" wrong choice \n ");
}
return 0;
}
Program 5:
#include <stdio.h>
main()
{
int selection;
float series, parallel,R1,R2,R3;
printf("******************************************");
printf("\nEnter the value of R1= ");
scanf("%f",&R1);
printf("\nEnter the value of R1= ");
scanf("%f",&R2);
printf("\nEnter the value of R1= ");
scanf("%f",&R3);
printf("******************************************");
printf("\n1: Series Circuit");
printf("\n2. Parallel Circuit ");
printf("\nPlease Select your choice ");
printf("\n******************************************\n");
scanf("%d",&selection);
switch(selection)
{
case 1:
series = R1+R2+R3;
printf("series = R1+R2+R3;");
printf("\nTotal resistance = %.2f Ohm\n",series);
break;
case 2:
parallel = 1/(1/R1 +1/R2+1/R3) ;
printf("parallel = 1/(1/R1 +1/R2+1/R3) ;");
printf("\nTotal resistance = %.6f Ohm\n",parallel);
break;
default:
printf(" wrong choice \n ");
}
return 0;
}
50 | Page
Program 6:
#include <stdio.h>
main()
{
int selection;
float series, parallel,R1,R2,R3,E,Rtotal,I,VR3,IR1,VR1;
printf("******************************************");
printf("\nEnter the value of R1= ");
scanf("%f",&R1);
printf("\nEnter the value of R2= ");
scanf("%f",&R2);
printf("\nEnter the value of R2= ");
scanf("%f",&R3);
printf("\nEnter the value of E= ");
scanf("%f",&E);
printf("\n******************************************");
printf("\n1: Total Resistance (Rtotal)");
printf("\n2. Current I (I) ");
printf("\n3: Voltage drop across resistor R3 (VR3)");
printf("\n4. Current through esistor R1 (IR1)");
printf("\nPlease Select your choice ");
printf("\n******************************************\n");
scanf("%d",&selection);
if (selection==1)
{
51 | Page
IR1 = VR1/R1 ;
printf(" VR1=E & IR1 = VR1/R1 \n ");
printf(" Current through Resistor R1 = %.4f Ampere\n",IR1);
}
else
{
printf(" wrong choice \n ");
}
return 0;
}
52 | Page
4.0 LOOPING
4.0 INTRODUCTION
Selection statements are used when you need to perform an action once only, based on the
condition specified. You may, however need to repeat a particular action in some situations
again and again. Refer Figure 4.5.1. Consider the action of cycling to reach a destination.
You will repeat the process of pedalling till you reach the destination. This can be compared
to the concept of looping in programming languages. The mechanism of executing a set of
statements repeatedly as long as the specified condition is satisfied is called looping. The
statements that are executed repeatedly are termed as looping statements.
Note
4.1 Looping statements
4.1.1 Define Looping statement
Looping statements are used to execute a set of statements repeatedly based on the
condition.
▪ for loop
▪ while loop
▪ do-while loop
4.1.3 Define FOR, WHILE, DO-WHILE loop statements
FOR: The for loop is a looping statement that enables you to repeat a set of instructions
based on the condition. It is used when the number of loops is known before the first
loop.
WHILE: The while loop is a looping statement that enables you to repeat a set of
instructions based on a condition. It is used when the number of loops is not known
before the first loop
53 | Page
DO-WHILE: The do-while loop is a looping statement that enables you to repeat a set of
instructions based on the condition. In a do-while loop, the body of the loop of executed
at least once before the condition is checked.
Definition: The break statement will transfer the control to the statement outside the
loop.
It is often necessary to transfer control out of a loop without getting back to the condition
check. The break statement is used for this purpose. During execution, when the keyword
break is encountered within a loop, the control is immediately transferred to the first
statement outside the loop. A break statement is usually used along with an if statement.
Definition: The continue statement will transfer the control to the beginning of the loop.
You can use the continue statement when you want the control to return to the beginning
of the loop without executing the rest of the statements in the loop. When the keyword
continue is encountered during the execution of the loop, the control is passed to the
beginning of the loop bypassing the rest of the statements in the loop.
Definition: The goto statement will transfer the control to the specified label.
During execution, goto statement is used to transfer the control to the specified label
within the program. A label is a name that refers to a particular line in the program. A
program can have any number of labels, but each label name must be unique. A label
must be followed by a colon (:) before the C statement.
4.1.5 Describe structure of FOR, nested FOR, WHILE, DO-WHILE loop statements
FOR Loop
In a for loop, the first step is to assign the value of the initial counter. Next the condition
is checked in the test counter. Based on the condition, body of the loop is executed. The
54 | Page
value of the counter is then incremented as specified in the increment counter. The
condition is checked again and the body of the loop is executed.
The body of the loop will be executed as long as the test condition is satisfied. When the
condition fails, the control is passed to the first statement outside the loop.
i=1
False
i <= 5
i=i+1
In Code Segment 4.1.5, i=1 is the initial counter, i<=5 is the condition and i=i+1 is the
increment counter. The following steps explain the execution of Code Segment 4.1.5:
1. When the control enters the loop for the first time, the value of i is initialised to 1 by
the initial counter.
2. Next, the condition is checked. If the value of i is less than or equal to 5, the control
is passed to the body of the loop.
3. The body of the loop is executed. Here, the value of i is displayed on the screen.
4. When the control reaches the closing brackets of the loop, the value of i is
incremented by 1.
6. When the test condition fails, the control comes out of the loop and the rest of the
program statements are executed.
Table 4.5.1 gives the details of the dry run for Code Segment 4.1.5:
56 | Page
Dry run is the process of executing a program by hand. This is done by writing values of
variables and other run-time data on paper, in order to check its operation.
WHILE loop
The while loop is similar to the for loop and is used to perform certain tasks repeatedly.
Use the while loop when the number of loops is not known before the first loop. This
will be known only during the run time, based on the input given by the user. Figure
4.1.6 represents the flowchart for the while loop.
Flowchart
True
In a while loop, the condition is initially checked. Based on this the statements below the
while statement are executed. The general syntax for a while loop is:
57 | Page
Syntax
...
<Increment loop counter>;
}
As shown in the syntax, the keyword while is followed by a conditional expression. The
condition is enclosed within a pair of brackets ( ). The while statement is followed by a
pair of curly brackets { } within which the statements, that are to be executed, are written.
You will notice that the counter value is initialised before the while statement. This
counter value is incremented within the body of the loop. Do not terminate the while
statement with a semicolon(;).
Code Segment 4.1.6 explains how a while loop can be used to print the numbers from 1
to 5:
58 | Page
Output:
1
2
3
4
5
DO-WHILE loop
The do-while loop is a variation of the while loop, with the only difference being the
location where the condition is checked, as shown in Figure 4.1.7.
In a while loop, first the condition is checked, followed by and then the body of the loop
is executed. In a do-while loop, however, the body of the loop is first executed and the
condition is checked subsequently. In a do-while loop, the loop is executed at least once
59 | Page
even if the condition is not satisfied. In the flowchart, notice that the condition is checked
after the execution of the statements within the body of the loop.
Syntax
do
{
Statement1;
Body of the
Statement2; Loop
...
...
...
}while( <conditional expression> );
Table 4.2.1 represents the difference between the various looping structures.
It is often necessary to transfer control out of a loop without getting back to the
condition check. The break statement is used for this purpose. During execution, when
the keyword break is encountered within a loop, the control is immediately transferred
60 | Page
to the first statement outside the loop. A break statement is usually used along with if
statement.
Flowchart for the execution of Code Sample 4.2.2 is given in the Figure 4.2.2.
61 | Page
Figure 4.2.2: Flowchart
Consider the program given in Code Sample 4.5.6. In this example, when the user
enters 0, the control is transferred to the statement outside the for loop.
4.3.1 Construct program(s) that use FOR, nested FOR, WHILE, DO-WHILE loop
statements
#include <stdio.h>
main()
{
int i;
for( i=1; i<=5; i=i+1)
{
printf("\n %d",i);
}
printf("\n\n You are out of the for loop");
}
62 | Page
OUTPUT:
1
2
3
4
5
You are out of the for loop
#include <stdio.h>
main()
{
int i;
for( i=10; i>=1; i=i-2)
{
printf("\n %d",i);
}
printf("\n\n You are out of the for loop");
}
OUTPUT:
10
8
6
4
2
You are out of the for loop
#include <stdio.h>
main()
{
int i,j;
for( i=1; i<=5; i=i+1)
{
for( j=10; j>=1; j=j-2)
{
printf("\n i=%d j=%d",i ,j);
}
printf("\n End of loop %d",i);
}
63 | Page
OUTPUT:
i=1 j=10
i=1 j=8
i=1 j=6
i=1 j=4
i=1 j=2
End of loop 1
i=2 j=10
i=2 j=8
i=2 j=6
i=2 j=4
i=2 j=2
End of loop 2
i=3 j=10
i=3 j=8
i=3 j=6
i=3 j=4
i=3 j=2
End of loop 3
i=4 j=10
i=4 j=8
i=4 j=6
i=4 j=4
i=4 j=2
End of loop 4
i=5 j=10
i=5 j=8
i=5 j=6
i=5 j=4
i=5 j=2
End of loop 5
You are out of the for loop
#include <stdio.h>
main()
{
int i;
i=1;
while (i <= 5)
{
printf("\n %d",i);
i++;
}
printf("\n\n You are out of while loop");
}
64 | Page
OUTPUT:
1
2
3
4
5
#include <stdio.h>
main()
{
int i;
i=10;
while (i >= 1)
{
printf("\n %d",i);
i=i-2;
}
printf("\n\n You are out of while loop");
}
OUTPUT:
10
8
6
4
2
#include <stdio.h>
main()
{
int i=1;
do
{
printf("Value of variable i is: %d\n", i);
i=i+1;
}while (i<=5);
printf("\n You are out of do-while loop");
return 0;
}
65 | Page
OUTPUT:
Value of variable i is:1
Value of variable i is:2
Value of variable i is:3
Value of variable i is:4
Value of variable i is:5
You are out of the do-while loop
#include <stdio.h>
main()
{
int i=10;
do
{
printf("Value of variable i is: %d\n", i);
i=i-2;
}while (i>=1);
printf("\n You are out of do-while loop");
return 0;
}
OUTPUT:
Value of variable i is:10
Value of variable i is:8
Value of variable i is:6
Value of variable i is:4
Value of variable i is:2
You are out of the do-while loop
#include <stdio.h>
main()
{
int i;
for( i=1; i<=6; i++)
{
printf("\n Value of variable i is: %d",i);
}
printf("\n The control is out of the for loop");
}
66 | Page
OUTPUT:
Value of variable i is:1
Value of variable i is:2
Value of variable i is:3
Value of variable i is:4
Value of variable i is:5
Value of variable i is:6
#include <stdio.h>
main()
{
int i;
for( i=1; i<=6; i++)
{
printf("\n Value of variable i is: %d",i);
if (i == 3)
break;
}
printf("\n The control is out of the for loop");
}
OUTPUT:
Value of variable i is:1
Value of variable i is:2
Value of variable i is:3
The control is out of the for loop
67 | Page
4.3.4 Construct program(s) that use GOTO statements
#include <stdio.h>
int main()
{
int sum=0;
for(int i = 0; i<=10; i++)
{
printf("\n Value of variable i is: %d",i);
sum = sum+i;
if(i==5)
{
goto addition;
}
}
addition:
printf("\n The sum of i=%d", sum);
return 0;
}
OUTPUT:
Value of variable i is:0
Value of variable i is:1
Value of variable i is:2
Value of variable i is:3
Value of variable i is:4
Value of variable i is:5
The sum of i=15
Tutorial
a) List THREE(3) types of looping statements
b) The program below contains FIVE (5) errors. Find the errors and rewrite this program
with the correct code.
#include <stdio.x>
int main{}
{
int i=0, sum=0;
while (i <=5)
{
sum +=i;
printf('sum [%d]=%d\n",1, sum);
i++;)
return 0;
}
68 | Page
c) Write a program which displays the following output by using do-while statements.
Output:
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
d) The loop statements consist of for, while and do-while. Program below uses for loop
statement to calculate the average of 5 numbers that entered by user. However the
program had some errors. Solve the errors and write the correct program. Then change
the program to do-while loop statement.
#include <studio.h>
void main()
{
Int no=1, total=0, Avg=0, num;
for (no=1;no<=5;no++)
{
scanf("%c", &num);
total=total+ Num;
}
avg=total/5;
printf(" Average=%d",avg);
return 0;
}
#include <stdio.h>
main()
{
int a, jum;
for (a=1;a<10;a+=2)
{
jum=jum+a;
printf("%d\n",a);
}
printf(" Jumlah ialah %d\n",jum);
return 0;
69 | Page
}
g) Apply C language to write a program to print 10 times of the below statemen using for.
h) Produce C program to display multiplication table using while looping statement and
draw the flowchart. The example of a output as follows :
1X3=3
2X3=6
3X3=9
12 X 3 = 36
Value of a : 10
Value of a : 11
Value of a : 12
Value of a : 13
Value of a : 14
Value of a : 15
Value of a : 16
Value of a : 17
Value of a : 18
Value of a : 19
70 | Page
Practical Activities
Program 1
#include <stdio.h>
main()
{
int j;
for ( j=5; j<=50; j=j+3)
{
printf( "Value of variable j is: %d\n",j );
}
return 0;
}
Program 2
#include <stdio.h>
main()
{
int j;
for ( j=50; j>=5; j=j-3)
{
printf( "Value of variable j is: %d\n",j );
}
return 0;
}
Program 3
#include <stdio.h>
main()
{
int I,V;
I=1;
while (I <= 9)
{
V= I* 150;
printf("\n Current at V%d = %d",I,V);
I++;
}
printf("\n\n You are out of while loop");
return 0;
}
71 | Page
Program 4
#include <stdio.h>
main()
{
int I,V;
I=9;
while (I >= 1)
{
V= I* 150;
printf("\n Current at V%d = %d",I,V);
I--;
}
printf("\n\n You are out of while loop");
return 0;
}
Program 5
#include <stdio.h>
int main()
{
int I,V;
I=1;
do
{
V= I* 150;
printf("\n Current at V%d = %d",I,V);
I++;
}while (I<=10);
printf("\n\n You are out of while loop");
return 0;
}
Program 5
#include <stdio.h>
int main()
{
int I,V;
I=10;
do
{
V= I* 150;
printf("\n Current at V%d = %d",I,V);
I--;
}while (I>=1);
printf("\n\n You are out of while loop");
return 0;
}
72 | Page
5.0 FUNCTION
5.1 INTRODUCTION
In your daily life, you depend on many appliances to complete your work. For example,
you might be using a washing machine to wash clothes, an oven to cook food and a
toaster to toast bread. These electronic appliances are used to accomplish specific
tasks quickly and easily. Programs too depend on elements such as functions to
perform specific tasks. C language offers various built-in functions. In this unit, you will
learn to use these built-in functions in the programs. You will also learn to define your
own functions according to the need.
Note
5.2 Remember FUNCTION statements
5.2.1 Define FUNCTION statement
Definition: A function is a block of statements that perform a specific task.
Functions divide the code and modularize the program for better and effective
results. A larger program is divided into various subprograms which are called as
functions
3. Modularity - You can break down large programs into simple functions. This will
make the program readable.
73 | Page
4. Easy to Debug - Since functions make programs more readable, you can easily
debug programs.
5. Easy to Modify and Extend: As you can easily add or remove functions in
programs, the capability of programs can be easily extended.
Specify the name of a function that we are going to use in our program like a
variable declaration. We cannot use a function unless it is declared in a program. A
function declaration is also called function prototype.
#include <stdio.h>
/*Function declaration*/
int add (int x,y);
/*End of Function declaration*/
main() {
74 | Page
Function Definition
Function definition means just writing the body of a function. A body of a function
consists of statements which are going to perform a specific task. A function body
consists of a single or a block of statements. It is also a mandatory part of a function.
● Return Type - The type of the value that the function will return. The return
type can be of any data type. The default return type is integer.
● Function Name - Any valid name can be given as the function name. Rules
for naming a function name are same as that of a variable name.
● Arguments - The values or variables that the function requires along with
their data types. Arguments can also be referred to as parameters.
● Local Variable Declaration - The variables that are declared within the
functions.
Example
75 | Page
Return Statement
The main function will call the user-defined function to perform the specified
action. Thus, main() is the calling function and the user-defined function is the
called function. The calling function is the function that calls the user-defined
function. The called function is the function that is being called by the calling
function.
When the main function calls another function, the control passes from main() to
the called function. After execution of the statements in the called function, the
control returns to main(). The called function may or may not return a value to
main(). The function will return a value to the calling function with the use of the
return statement. When the return statement is executed, the function execution
will be terminated and the control is passed back to the calling function.
Example 1
void main()
{
int func(int,int); // Function Prototype
…
…
…
}
Example 2
int func(int,int); // Function Prototype
void main()
{
…
…
…
}
1. Mention the return type of the function. If the function is not returning any
value, the return type must be declared as void.
77 | Page
They are:
▪ Call by value
▪ Call by reference
Call by value refers to passing values as arguments to the function. Call by reference
refers to passing the address of the variables as argument to the function. In this
unit you will learn about call by value.
It is possible to pass values from one function to another function for performing
calculations. This type of a function call is referred to as call by value.
The call by value method of passing arguments to a function copies the actual value
of an argument into the formal parameter of the function. In this case, changes
made to the parameter inside the function have no effect on the argument.
#include <stdio.h>
main()
{
void func1();
printf("\n\n Control is in main function ");
func1();
printf("\n\n Control is back in main function ");
}
void func1()
{
printf("\n\n Control is in function1 ");
}
78 | Page
OUTPUT:
#include <stdio.h>
int sum(int a, int b)
{
int c=a+b;
return c;
}
main()
{
int num1,num2,num3;
num1 =10;
num2 = 20;
printf(" \n Value of num1 is: %d", num1);
printf(" \n Value of num2 is: %d", num2);
num3 = sum(num1, num2);
printf("\n sum of num1 & num2 = %d", num3);
return 0;
}
OUTPUT:
#include <stdio.h>
int increment(int var)
{
var = var+20;
return var;
}
main()
{
int num1,num2;
num1=20;
num2 = increment(num1);
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d", num2);
return 0;
}
79 | Page
OUTPUT:
#include <stdio.h>
void increment(int *var)
{
*var = *var+10;
}
main()
{
int num=1;
increment(&num);
printf("Value of num is: %d", num);
return 0;
}
OUTPUT:
/*calling function*/
func_num( &num1, &num2 );
printf("\nAfter function:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
return 0;
80 | Page
OUTPUT:
Tutorial
i. int func(void);
ii. char func(char a, char b);
iii. void func(void);
iv. void func(int a, char b);
v. float func(int a);
vi. A function called change that will accept an integer value and return a float
value.
vii. A function called calc that will accept two float values but does not return any
value.
viii. A function called sample that will accept three integer values and return an
integer value.
ix. A function called convert that will accept an integer value and two float values
and return a float value.
x. A function called getdata that will not accept or return any value.
c) Write a program to find the sum of two numbers using functions. The function should
have no arguments and no return value.
d) Write a program to accept the number of books from the user in the main function. Write
a function to accept the book's name and their price. Write another function to display
these details.
Practical Activities
Program 1:
#include <stdio.h>
int addition(int Rr1, int Rr2)
{
int TotalR;
TotalR = Rr1+Rr2;
return TotalR;
}
int main()
{
int R1, R2;
printf("Enter value of R1: ");
scanf("%d",&R1);
printf("Enter value of R2: ");
scanf("%d",&R2);
int Total = addition(R1, R2);
printf ("Output: %d", Total);
return 0;
}
Program 2:
#include <stdio.h>
int kira()
{
int R1, R2, Total;
printf("Enter value of R1: ");
82 | Page
scanf("%d",&R1);
printf("Enter value of R2: ");
scanf("%d",&R2);
Total = R1+R2;
printf ("Output: %d", Total);
}
int main()
{
kira();
return 0;
}
Program 3:
#include <stdio.h>
void increment(int *Total)
{
}
int main()
{
int num=20;
increment(&num);
printf("Value of num is: %d", num);
return 0;
}
Program 4:
#include <stdio.h>
int addNumbers(int a, int b); int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
83 | Page
int addNumbers(int a, int b)
{
int result;
result = a+b;
return result;
}
84 | Page
6.0 ARRAY
INTRODUCTION
An array is a collection of data items, all of the same type, accessed using a common
name. A one-dimensional array is like a list; A two dimensional array is like a table; The C
language places no limits on the number of dimensions in an array, though specific
implementations may.
Note
Single-dimensional arrays will have only one subscript. Subscript refers to the dimension
of the array.
When you declare a single-dimensional array as x[7], it means that the array has one row
and seven columns, as shown in Figure 6.1.3.a. This array can thus hold up to seven values.
85 | Page
X[0] X[1] X[2] X[3] X[4] X[5] X[6]
Row
1 2 3 4 5 6 7
Columns
Figure 6.1.3.a: Representation of a Single-Dimensional Array
Declaring an Array
Syntax
<Data type> <Variable name>[Size of the array];
Example
int x[3];
Data type variable Saiz of the array
int x [3]
Here x is an array variable that can hold three values. Each value is referred as an element.
This array, therefore, will have three elements of integer data type. Notice that the array
size is specified within the square brackets [ ] as shown in Figure 6.1.3.b.
Example
x[0] = 15;
x[1] = 26;
x[2] = 37;
86 | Page
Refer to Figure 6.1.4.a, x[0], x[1] and x[2] refers to the first, second and third elements,
respectively. The first element will always have the array index as 0 as shown in Figure
6.1.4.b. Array index refers to the location of the values in an array.
In the Figure 6.1.4.c, you will notice that the values in an array are stored in consecutive
memory locations.
15 26 37
You can initialise the array at the time of declaration in the following manner:
int x[3] = {15,26,37};
When initialising an array, the values are enclosed within the curly brackets { }.
You will be able to access the array elements through the array index. For example, if
you need to print the second element of the array, the code will be:
printf(" %d",x[1]);
87 | Page
Program to declare and initialise an array
#include <stdio.h>
main()
{
int x[3]={15,26,37};
printf("\n x[0] (1st element) : %d",x[0]); // Displays the 1st element.
printf("\n x[1] (2nd element) : %d",x[1]); // Displays the 2nd element.
printf("\n x[2] (3rd element) : %d",x[2]);// Displays the 3rd element.
}
Output
x[0] (1st element) : 15
x[1] (2nd element) : 26
x[2] (3rd element) : 37
1. Initially the value of i is initialised to 0. Now, x[i] becomes x[0], which is the first
element in the array.
2. The condition (i<=9) is now checked and if the condition is true, the next step is
executed.
3. Now, the scanf statement will accept the value from the user.
88 | Page
5. Step 2, 3 and 4 is repeated till the condition fails. Once the condition fails, the control
comes out of the for loop.
As the array has to accept ten values, the array index is specified only till 9. x[9] is the 10th
element in the array, as the index starts from zero .
Table 6.1.5 gives the details for the dry run for Code Segment 6.1.5.
Value of i
Condition x[ i ] Element
[ Array index]
0 True x[0] 1st
1 True x[1] 2nd
2 True x[2] 3rd
3 True x[3] 4th
4 True x[4] 5th
5 True x[5] 6th
6 True x[6] 7th
7 True x[7] 8th
8 True x[8] 9th
9 True x[9] 10th
10 False - -
1. Initially the value of i is initialised to 0. Now, x[i] becomes x[0], which is the first element
in the array.
89 | Page
2. The condition (i<=9) is now checked and if the condition is true, the next step is
executed.
3. Now the printf statement will print the value on the screen.
5. Step 2, 3 and 4 is repeated till the condition fails. Once the condition fails, the control
comes out of the for loop.
Program to accept 10 values from the user and to print the values on the screen.
/* Program to accept 10 values from the user and to print them on the screen */
#include <stdio.h>
void main()
{
int x[10],i;
printf("\n Enter the array values : \n\n");
for( i=0; i<10; i++) // Array index starts with 0 - 9
{
printf("\t x[%d] = ",i);
scanf("%d",&x[i]);
}
printf("\n The array values are : \n");
for( i=0; i<10; i++)
printf("\n\t x[%d] = %d ",i,x[i]);
}
Code Sample 6.1.6
Output
6.2.1 Differentiate the one, two and three Dimensional ARRAY in C language
Multidimensional arrays are arrays with more than one dimension. Multidimensional
arrays are used to represent data in terms of rows and columns. A multidimensional array
90 | Page
that has two subscripts is called two-dimensional array (also known as 2-D arrays). A two-
dimensional array is an array of single-dimensional arrays. Similarly, a three-dimensional
array (also called a 3-D array) is an array of two-dimensional arrays. In other words, an n-
dimensional array is an array of (n-1) dimensional arrays.
syntax
<Data type> <Variable name> [Array index] ;
syntax
<Data type> <Variable name>[Number of rows][Number of columns];
syntax
<Data type> <Variable name>[N1][N2][N3];
Single-dimensional array stores the simple list of values in a linear fashion. A two-
dimensional array will have n number of rows and m number of columns.
A two-dimensional array is also referred as matrix, which is the combination of rows and
columns. Figure 6.2.3b illustrates the arrangement of rows and columns in a two
91 | Page
dimensional array. The array always starts with 1st row and 1st column and the array
0 1 2 3 4
Row 1 0
Row 2 1
Row 3
2
Row 4
3
Row 5
4
Column 1
Column 2
Column 3
Column 4
Column 5
index for which will be 0 (represents first row), 0 (represents first column).
Syntax
<Data type> <Variable name>[Number of rows][Number of columns];
Example
int x[5][5];
Here, x is an array variable, which has five rows and five columns, as shown in Figure 6.2.3.
This array can hold twenty five values (5*5).
92 | Page
6.2.4 Initialising a Two-Dimensional Array
Syntax
Example
int x[5][5]={ {40,50,87,66,45},
{54,72,24,36,77},
{88,66,76,76,77},
{22,56,89,33,44},
{78,65,56,87,95} };
Figure 6.2.4.a clearly shows the array index of the various elements of the array. Notice
that the first element in the array has the index 0,0. Figure 6.2.4.b and 6.2.4.c represents
the elements of the array x arranged in rows and columns.
93 | Page
Figure 6.2.4.b: Elements of a Two-Dimensional Array
Refer to Figure 6.2.4.d and 6.2.4.e to understand how array elements and array indexes
are represented.
94 | Page
6.2.5 Accessing Array Elements
You can access the array elements by using the array index. For example, if you want to
print the element in the third column of the second row of an array, use the following
code:
To enter data into a two-dimensional array, you need to specify the row and the
column number. In a single-dimensional array, you used a single for loop to enter data
into the columns of the single row. In a two-dimensional array, you will use two for
loops to enter data into the array. One for loop will be used for specifying the row
number and the other for loop will be used for specifying column number.
You can nest the for loops in the same way as you nest the if statements. Nesting
for loops refers to using a for loop within a for loop. You can have any number loops
within a loop. The general syntax of nested for loop is as follows:
Syntax
for(... ; ... ; ...)
{
for(... ; ... ; ...)
{
Inner Loop Outer Loop
...
...
...
}
}
In a nested for loop, the control begins from the outer loop. The control then passes to
the inner loop. The inner loop will be executed until the condition specified in the inner
95 | Page
loop fails. After executing the inner loop completely, the control passes to the outer loop
to execute the next iteration of the outer loop. To understand the working of a nested for
loop clearly, examine Code program 6.2.6:
#include<stdio.h>
main ()
{
int i,j;
for(i=2;i<=3;i++)
{
for(j=10;j<=11;j++)
{
printf("\n %d %d",i,j);
}
}
}
Output
The flowchart for the execution of Code Segment 6.2.6 is shown in the Figure 6.2.6.
96 | Page
Figure 6.2.6: Flowchart
2. The test condition is executed and if the condition is true, that is if the value is less
than or equal to 3, the control moves to the inner loop.
4. Test condition for the inner loop is checked. If the condition is true, which happens
when the value of j is less than or equal to 11, the control moves to the body of the
inner loop.
6. The control again moves to the inner for loop statement and the value of j is
incremented.
7. Steps 4, 5 and 6 are executed until the test condition in the inner loop is true.
8. When the test condition in the inner loop is false, the control passes to the outer loop.
10. Steps 2 to 9 are executed as long as the test condition in the outer loop is true.
97 | Page
11. When the test condition is not satisfied, the control comes out of the loop and the rest
of the program statements are executed.
Table 6.2.6 gives the details of the dry run for Code Segment 6.2.6.
#include <stdio.h>
main()
{
int i,j;
98 | Page
Output
You can read the data entered into an array. You can use a nested for loop with a single
printf statement to display all the values of a two-dimensional array on the screen.
1. The value of i is initialised to 0. This value is used to refer to the 1st row.
2. The condition for i is then checked. If the condition is true, that is if the value of i is less
than or equal to 2 the control is passed to the inner loop.
3. The value of j is initialised to 0. This value is used to refer to the 1st column.
4. The condition for j is checked. If the condition is true, that is if the value of j is less
than or equal to 2, the control is passed to the body of the loop.
6. The control is again passed to the inner for loop and the value of j is incremented by 1.
7. Steps 4,5 and 6 are executed till the condition for j is faise.
8. When the condition for j fails, the control is passed to the outer loop. Here, the value
of i is incremented by 1.
99 | Page
9. Steps 2 to 9 are executed till the condition for i is false.
10. When the condition fails, the control comes out of the for loop.
6.3.3 Hands-On!
The following program will accept integer values from the user; store it in a two-
dimensional array and display the values on the screen.
#include <stdio.h>
main()
{
int x[3][3],i,j;
printf("\n Enter the array : \n");
for ( i=0; i<=2; i++)
{
printf("\n");
for( j=0; j<=2; j++)
{
printf("\t X[%d][%d] = ",i,j);
scanf("%d",&x[i][j]);
}
}
printf("\nThe array is : \n");
printf("\nThe array is : \n");
printf("\n\t\t Column 1 \t Column 2 \t Column 3\n");
for( i=0; i<=2; i++)
{
printf("\n");
printf(" Row %d ",i+1);
for( j=0; j<=2; j++)
{
printf("\t X[%d][%d] = %d ",i,j,x[i][j]);
}
}
}
Code Sample 6.3.3
Output
100 | Page
Tutorial
a. What is an array? List the types of array in C language.
b. Define a single-dimensional integer array called arr1 with 5 elements. Assign the
values 15,24,33,55 and 100 to the array elements.
c. Declare and initialise an array that can hold the values 3, 5 and 7.
d. Explain the need for arrays with an example.
e. Write a program to accept ten numbers and find their average.
f. Write short notes on single-dimensional array. How will you declare and initialise a
single-dimensional array?
g. Write a program to accept ten numbers and arrange the elements in the ascending
order.
h. Write a program to accept two arrays (4 elements each). Find the sum of two
arrays.
i. Write a program to accept five elements of an array. Decrement the value of each
element by two and display the array.
j. Write a program to accept the array size from the user. Accept the array elements
from the user and display the same on the screen.
k. Write a program to accept 15 elements of an array. Find the sum of the elements.
l. Write a program to accept 10 numbers from the user. Find the number of positive
and negative numbers.
m. Write a program to accept 6 elements of an array and display the array in reverse
order.
n. The following figure represents the data stored in a two-dimensional array.
102 | Page
Practical Activities
Program 1:
#include <stdio.h>
main()
{
int array[10] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
printf(" array[10] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ");
printf("\n array [0]=%d ", array[0]);
printf("\n array [3]=%d ", array[3]);
printf("\n array [5]=%d ", array[5]);
printf("\n array [6]=%d ", array[6]);
printf("\n array [2]=%d ", array[2]);
printf("\n array [9]=%d ", array[9]);
return 0;
}
Program 2:
#include <stdio.h>
main()
{
int x, array[10] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
printf(" array[10] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}");
for(x = 0; x < 10; x++)
printf("\n array [%d] = %d ", x,array[x]);
return 0;
}
Program 3:
#include <stdio.h>
main()
{
int x, array[10];
printf(" array[10] \n");
for(x = 0; x < 10; x++)
{
printf("array [%d] = ", x);
scanf ("%d",&array[x]);
}
for(x = 0; x < 10; x++)
printf("\n array [%d] = %d ", x,array[x]);
return 0;
}
103 | Page
Program 4:
#include <stdio.h>
main()
{
int array[2][5] = {{1,2,3,4,5},{6,7,8,9,10}};
printf(" array[2][5] = {1,2,3,4,5},{6,7,8,9,10} ");
printf("\n array [0][0]=%d ", array[0][0]);
printf("\n array [1][3]=%d ", array[1][3]);
printf("\n array [0][4]=%d ", array[0][4]);
printf("\n array [0][2]=%d ", array[0][2]);
printf("\n array [1][4]=%d ", array[1][4]);
printf("\n array [1][1]=%d ", array[1][1]);
return 0;
}
Program 5:
#include <stdio.h>
main()
{
int array[4][4] ={{0,1,2,3},{4,5,6,7},{8,9,10,11},{12,13,14,15}};
printf(" array[4][4] ={{0,1,2,3},{4,5,6,7},{8,9,10,11},{12,13,14,15} ");
printf("\n array [0][0]=%d ", array[0][0]);
printf("\n array [1][1]=%d ", array[1][1]);
printf("\n array [2][2]=%d ", array[2][2]);
printf("\n array [3][3]=%d ", array[3][3]);
printf("\n array [0][3]=%d ", array[0][3]);
printf("\n array [3][0]=%d ", array[3][0]);
return 0;
}
Program 6:
#include <stdio.h>
main()
{
int x,y, array[4][4] ={{0,1,2,3},{4,5,6,7},{8,9,10,11},{12,13,14,15}};
printf(" array[4][4] ={{0,1,2,3},{4,5,6,7},{8,9,10,11},{12,13,14,15} ");
for(x = 0; x < 4; x++)
{
for(y = 0; y < 4; y++)
printf("\n array [%d][%d] = %d ", x,y,array[x][y]);
}
return 0;
}
104 | Page
Program 7:
#include <stdio.h>
main()
{
int x,y, array[2][2];
printf(" for array[2][2] \n ");
for(x = 0; x < 2; x++)
{
for(y = 0; y < 2; y++)
{
printf("array [%d][%d] = ", x,y);
scanf ("%d",&array[x][y]);
}
}
for(x = 0; x < 2; x++)
{
for(y = 0; y < 2; y++)
printf("\n array [%d][%d] = %d ", x,y,array[x][y]);
}
return 0;
}
Program 8:
#include <stdio.h>
main()
{
int x,y, array[5][5];
printf(" for array[5][5] \n ");
105 | Page
7.0 DEMONSTRATE THE I/O OPERATION
ARDUINO
1. Introduction of Auduino
a. Arduino is a tool for making computers that can sense and control more of the
physical world than your desktop computer. It's an open-source physical
computing platform based on a simple microcontroller board, and a
development environment for writing software for the board.
a. Arduino can be used to develop interactive objects, taking inputs from a
variety of switches or sensors, and controlling a variety of lights, motors, and
other physical outputs.
a. Arduino projects can be stand-alone, or they can be communicate with
software running on your computer (e.g. Flash, Processing, MaxMSP.) The
boards can be assembled by hand or purchased pre-assembled; the open-
source IDE can be downloaded for free.
a. The Arduino programming language is an implementation of Wiring, a similar
physical computing platform, which is based on the Processing multimedia
programming environment.
106 | Page
1. LED Blinking with Arduino Uno
// The setup function runs when you press reset or power the board
void setup()
{
// initialize digital pin 0 as an output.
pinMode(0, OUTPUT);
}
// the loop function runs over and over again forever
void loop()
{
digitalWrite(0, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a second
digitalWrite(0, LOW); // turn the LED off by making the voltage LOW
delay(500); // wait for a second
}
107 | Page
2. LED Blinking with Arduino Uno
Step 1: Introduction
In this lesson , we build the first external circuit and control it from Arduino. We use
digitalWrite command to turn LED on and off.
Step 2 : Materials
2 x LED
Arduino
1 x USB cable
Breadboard
Jumper Wires
Step 3 : Circuit Diagram
Step 4 : Diagram
108 | Page
Step 5 : The Code
int led1=1;
int led2=2;
void setup() {
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
}
void loop() {
digitalWrite ( led1, HIGH);
delay (500);
digitalWrite ( led1, LOW);
delay (500);
digitalWrite ( led2, HIGH);
delay (500);
digitalWrite ( led2, LOW);
delay (500);
}
Step 1 : Introduction
In this lesson, we build the first external circuit and control it from Arduino. We use
digitalWrite command to turn LED on and off.
Step 2 : Materials
4 x LED
Arduino
1 x USB cable
Breadboard
Jumper Wires
Step 3 : Circuit Diagram
109 | Page
Step 4 : Diagram
110 | Page
4. Multiple Blink LED
Step 1 : Introduction
In this lesson , we build the first external circuit and control it from Arduino. We use
digitalWrite command to turn LED on and off.
Step 2 : Materials
8 x LED
Arduino
1 x USB cable
Breadboard
Jumper Wires
Step 4 : Diagram
112 | Page
5. Model Traffic Signal
Step 1 : Introduction
So now we know how to set a digital pin to be an input, we can build a project for
model traffic signals using red, yellow, and green LEDs. Every time we press the
button, the traffic signal will go to the next step in the sequence. In the UK, the
sequence of such traffic signals is red, red and amber together, green, amber, and
then back to red. As a bonus, if we hold the button down, the lights will change in
sequence by themselves with a delay between each step.
Step 2 : Components And Equipment
Arduino UNO
4x 220 ohm resistor
hook-up wires
breadboard
red LED
yellow LED
green LED
1x push switch
R1
G
Y
R
R1
R1
R1
Step 4 : Diagram
113 | Page
Step 5 : The Code
int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;
int state = 0;
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop()
{
if (digitalRead(buttonPin))
{
if (state == 0)
{
setLights(HIGH, LOW, LOW);
state = 1;
}
else if (state == 1)
{
setLights(LOW, HIGH, LOW);
state = 2;
}
else if (state == 2)
{
setLights(LOW, LOW, HIGH);
state = 3;
}
else if (state == 3)
{
setLights(LOW, HIGH, LOW);
state = 0;
}
delay(1000);
}
}
void setLights(int red, int yellow,
int green)
{
digitalWrite(redPin, red);
digitalWrite(yellowPin, yellow);
digitalWrite(greenPin, green);
}
114 | Page
6. Model Traffic Signal (auto)
Step 1 : Introduction
So now we know how to set a digital pin to be an input, we can build a project for
model traffic signals using red, yellow, and green LEDs. Every time we press the
button, the traffic signal will go to the next step in the sequence. In the UK, the
sequence of such traffic signals is red, red and amber together, green, amber, and
then back to red. As a bonus, if we hold the button down, the lights will change in
sequence by themselves with a delay between each step.
Step 2 : Components And Equipment
Arduino UNO
3x 220 ohm resistor
hook-up wires
breadboard
red LED
yellow LED
green LED
Step 4 : Diagram
115 | Page
Step 5 : The Code
int red = 2;
int yellow = 3;
int green = 4;
int x;
void setup()
{
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
}
void loop()
{
digitalWrite (red, HIGH);
digitalWrite (yellow, LOW);
digitalWrite (green, LOW);
delay(500);
digitalWrite (red, LOW);
for(x=1; x<=4;x++)
{
digitalWrite (yellow, LOW);
delay(500);
digitalWrite (yellow, HIGH);
delay(500);
}
}
116 | Page
Step 1 : Introduction
So now we know how to set a digital pin to be an input, we can build a project for
model traffic signals using red, yellow, and green LEDs. Every time we press the
button, the traffic signal will go to the next step in the sequence. In the UK, the
sequence of such traffic signals is red, red and amber together, green, amber, and
then back to red. As a bonus, if we hold the button down, the lights will change in
sequence by themselves with a delay between each step.
Step 2 : Components And Equipment
Arduino UNO
2x 220 ohm resistor
hook-up wires
breadboard
2x red LED
2x yellow LED
2x green LED
Step 4 : Diagram
117 | Page
int yellow = 3;
int green = 4;
int red2 = 5;
int yellow2 = 6;
int green2 = 7;
int x;
void setup()
{
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
pinMode(red2, OUTPUT);
pinMode(yellow2, OUTPUT);
pinMode(green2, OUTPUT);
}
void loop()
{
digitalWrite (red, HIGH);
digitalWrite (yellow, LOW);
digitalWrite (green, LOW);
digitalWrite (red2, HIGH);
digitalWrite (yellow2, LOW);
delay(1000);
digitalWrite (red2, LOW);
digitalWrite (green2, HIGH);
delay(5000);
digitalWrite (green2, LOW);
for(x=1; x<=5;x++)
{
digitalWrite (yellow2, LOW);
delay(500);
digitalWrite (yellow2, HIGH);
delay(500);
}
digitalWrite (red2, HIGH);
digitalWrite (yellow2, LOW);
digitalWrite (green2, LOW);
digitalWrite (red, HIGH);
digitalWrite (yellow, LOW);
delay(1000);
digitalWrite (red, LOW);
digitalWrite (green,HIGH);
delay(5000);
digitalWrite (green,LOW);
for(x=1; x<=5;x++)
{
digitalWrite (yellow, LOW);
118 | Page
delay(500);
digitalWrite (yellow, HIGH);
delay(500);
}
}
So now we know how to set a digital pin to be an input, we can build a project for
model traffic signals using red, yellow, and green LEDs. Every time we press the
button, the traffic signal will go to the next step in the sequence. In the UK, the
sequence of such traffic signals is red, red and amber together, green, amber, and
then back to red. As a bonus, if we hold the button down, the lights will change in
sequence by themselves with a delay between each step.
Step 2 : Components And Equipment
Arduino UNO
3x 220 ohm resistor
hook-up wires
breadboard
3x red LED
3x yellow LED
3x green LED
119 | Page
Step 4 : Diagram
int red = 1;
int yellow = 2;
int green = 3;
int red2 = 4;
int yellow2 = 5;
int green2 = 6;
int red3 = 7;
int yellow3 = 8;
int green3 = 9;
int x;
void setup()
{
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
pinMode(red2, OUTPUT);
pinMode(yellow2, OUTPUT);
pinMode(green2, OUTPUT);
pinMode(red3, OUTPUT);
pinMode(yellow3, OUTPUT);
pinMode(green3, OUTPUT);
}
void loop()
{
digitalWrite (red, HIGH);
digitalWrite (yellow, LOW);
digitalWrite (green, LOW);
digitalWrite (red3, HIGH);
digitalWrite (yellow3, LOW);
digitalWrite (green3, LOW);
digitalWrite (red2, HIGH);
digitalWrite (yellow2, LOW);
120 | Page
delay(1000);
digitalWrite (red2, LOW);
digitalWrite (green2, HIGH);
delay(5000);
digitalWrite (green2, LOW);
//side ke 2
for(x=1; x<=5;x++)
{
digitalWrite (yellow2, LOW);
delay(500);
digitalWrite (yellow2, HIGH);
delay(500);
}
digitalWrite (red2, HIGH);
digitalWrite (yellow2, LOW);
digitalWrite (green2, LOW);
digitalWrite (red, HIGH);
digitalWrite (yellow, LOW);
digitalWrite (green, LOW);
digitalWrite (red3, HIGH);
digitalWrite (yellow3, LOW);
delay(1000);
digitalWrite (red3, LOW);
digitalWrite (green3,HIGH);
delay(5000);
digitalWrite (green3,LOW);
//side ke 3
for(x=1; x<=5;x++)
{
digitalWrite (yellow3, LOW);
delay(500);
digitalWrite (yellow3, HIGH);
delay(500);
}
Step 1 : Introduction
So now we know how to set a digital pin to be an input, we can build a project for
model traffic signals using red, yellow, and green LEDs. Every time we press the
button, the traffic signal will go to the next step in the sequence. In the UK, the
sequence of such traffic signals is red, red and amber together, green, amber, and
then back to red. As a bonus, if we hold the button down, the lights will change in
sequence by themselves with a delay between each step.
Step 2 : Components And Equipment
Arduino UNO
4x 220 ohm resistor
hook-up wires
breadboard
4x red LED
4x yellow LED
4x green LED
122 | Page
Step 4 : Diagram
int red = 1;
int yellow = 2;
int green = 3;
int red2 = 4;
int yellow2 = 5;
int green2 = 6;
int red3 = 7;
int yellow3 = 8;
int green3 = 9;
int x;
void setup()
{
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
pinMode(red2, OUTPUT);
pinMode(yellow2, OUTPUT);
pinMode(green2, OUTPUT);
pinMode(red3, OUTPUT);
pinMode(yellow3, OUTPUT);
pinMode(green3, OUTPUT);
pinMode(red4, OUTPUT);
pinMode(yellow4, OUTPUT);
pinMode(green4, OUTPUT);
123 | Page
}
void loop()
{
// side yg pertama
digitalWrite (red, HIGH);
digitalWrite (yellow, LOW);
digitalWrite (green, LOW);
digitalWrite (red3, HIGH);
digitalWrite (yellow3, LOW);
digitalWrite (green3, LOW);
digitalWrite (red4, HIGH);
digitalWrite (yellow4, LOW);
digitalWrite (green4, LOW);
digitalWrite (red2, HIGH);
digitalWrite (yellow2, LOW);
delay(1000);
digitalWrite (red2, LOW);
digitalWrite (green2, HIGH);
delay(5000);
digitalWrite (green2, LOW);
//side ke 2
for(x=1; x<=5;x++)
{
digitalWrite (yellow2, LOW);
delay(500);
digitalWrite (yellow2, HIGH);
delay(500);
}
digitalWrite (red2, HIGH);
digitalWrite (yellow2, LOW);
digitalWrite (green2, LOW);
digitalWrite (red, HIGH);
digitalWrite (yellow, LOW);
digitalWrite (green, LOW);
digitalWrite (red4, HIGH);
digitalWrite (yellow4, LOW);
digitalWrite (green4, LOW);
digitalWrite (red3, HIGH);
digitalWrite (yellow3, LOW);
delay(1000);
digitalWrite (red3, LOW);
digitalWrite (green3,HIGH);
delay(5000);
digitalWrite (green3,LOW);
//side ke 3
for(x=1; x<=5;x++)
{
digitalWrite (yellow3, LOW);
delay(500);
124 | Page
digitalWrite (yellow3, HIGH);
delay(500);
}
digitalWrite (red3, HIGH);
digitalWrite (yellow3, LOW);
digitalWrite (red4, HIGH);
delay(1000);
digitalWrite (red4, LOW);
digitalWrite (green4,HIGH);
delay(5000);
digitalWrite (green4,LOW);
//side ke 3
for(x=1; x<=5;x++)
{
digitalWrite (yellow4, LOW);
delay(500);
digitalWrite (yellow4, HIGH);
delay(500);
}
digitalWrite (red4, HIGH);
digitalWrite (yellow4, LOW);
digitalWrite (green4, LOW);
digitalWrite (red3, HIGH);
digitalWrite (yellow3, LOW);
digitalWrite (green3, LOW);
digitalWrite (red2, HIGH);
digitalWrite (yellow2, LOW);
digitalWrite (green2, LOW);
digitalWrite (red, HIGH);
digitalWrite (yellow, LOW);
delay(1000);
digitalWrite (red, LOW);
digitalWrite (green,HIGH);
delay(5000);
digitalWrite (green,LOW);
for(x=1; x<=5;x++)
{
digitalWrite (yellow, LOW);
delay(500);
digitalWrite (yellow, HIGH);
delay(500);
}
}
125 | Page
References
David, G & Dawn, G. (2012). Head First C: A Brain-Friendly Guide 1st Edition. O'Reilly Media.
Kernighan, Brian W.; Ritchie, Dennis M. (February 1978). The C Programming Language (1st ed.).
Englewood Cliffs, NJ: Prentice Hall. ISBN 0-13-110163-3.
Knuth, D. (1998). The art of computer programming Volume 2 2nd edition. In Reading MA.
McGrath,M. (2018). C Programming in easy steps, 5th Edition. In Easy Steps Limited.
Perry,G.& Miller,D. (2015). C Programming Absolute Beginner's Guide 3rd Edition. Pearson
Education.
Ritchie, Dennis M. (1993). "The Development of the C Language". History of Programming
Languages, 2nd Edition. Retrieved 2018-11-11.
Schildt, H. ( 2018).The Complete Reference, 4th Edition. McGraw-Hill.
126 | Page
1