You are on page 1of 203

2nd Semester: Programming (C Language) – 3rd Edition 2020

THE

C PROGRAMMING LANGUAGE

Student Name: __________________________________________

Class : __________________________________________

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Table of Conteprints
1. Introduction to Programming ............................................................................................................. 7
1.1 Definition of Computer Program..................................................................................................... 7
1.2 Differentiate Between of 5 Generation of Programming Language ................................................ 7
Summary Generation Programming Language ..................................................................................... 13
1.3 Language Translators .................................................................................................................... 14
1.3.1 Assembler.......................................................................................................................... 16
1.3.2 Compiler ............................................................................................................................ 17
1.3.3 Interpreter......................................................................................................................... 18
1.3.4 Compiler VS Interpreter .................................................................................................... 19
2. Fundamental of C Programming Language ....................................................................................... 20
2.1 C Program ....................................................................................................................................... 20
2.1.1 The C Program Development Environment .............................................................................. 21
2.1.2 Type of Programming Errors .................................................................................................... 23
2.1.3 Structure of a C Program .......................................................................................................... 25
2.1.4 Special Commands on C Preprocessor Directive ...................................................................... 27
Description ........................................................................................................................................... 28
Syntax ................................................................................................................................................... 28
Header Files .......................................................................................................................................... 28
Description............................................................................................................................................ 29
Syntax ................................................................................................................................................... 29
Note ...................................................................................................................................................... 30
Example ................................................................................................................................................ 30
1. Number ..................................................................................................................................... 30
2. String ......................................................................................................................................... 30
3. Expression ................................................................................................................................. 31
Library Functions ...................................................................................................................................... 40
2.1.5 C Language Reserved Words .................................................................................................... 42
2.1.6 Tutorial 1: Creating and Editing a Basic Program ..................................................................... 45
2.2 Basic Data Types ........................................................................................................................... 46
2.2.1 Data types in C Language ............................................................................................................. 46
C Programming Strings ............................................................................................................................. 48

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

• Declaration of strings ................................................................................................................... 48


• Using arrays .............................................................................................................................. 48
• Initialization of strings.................................................................................................................. 48
• Using arrays .............................................................................................................................. 48
• Reading Strings from user ............................................................................................................ 48
• Reading words from user ......................................................................................................... 49
• Example #1: Using scanf () to read a string .............................................................................. 49
• Reading a line of text................................................................................................................ 49
• Example #1: Using getchar () to read a line of text ................................................................... 49
• Example #2: Using standard library function to read a line of text ........................................... 50
• Passing Strings to Functions ......................................................................................................... 50
C – Variable .............................................................................................................................................. 57
2.2.2 Tutorial 2 ............................................................................................................................... 63
2.3 Input and Output ............................................................................................................................ 66
2.3.1 Printing String .......................................................................................................................... 67
2.3.2 Printing Characters ................................................................................................................... 68
2.3.3 Printing Integers and Floating Point Numbers ......................................................................... 69
2.3.4 Displaying Several Values at Once ............................................................................................ 70
2.3.5 The scanf( ) Function ................................................................................................................ 71
2.3.6 Other Functions for Input/Output Purposes ............................................................................ 72
2.3.7 Excercise 1 : Data Type – Character and String ........................................................................ 75
2.4 Expressions and Operators ........................................................................................................... 76
2.4.1 Operators ................................................................................................................................. 76
2.4.2 Operators Precedence in C....................................................................................................... 84
2.4.3 Exercise 2: Expression and Operator ........................................................................................ 85
2.4.2 Tutorial 3: Expression and Operator ........................................................................................ 86
3. Problem Solving in Programming ...................................................................................................... 92
3.1 Programming Steps ............................................................................................................... 92
3.2 Algorithm .................................................................................................................................... 93
Qualities of a good algorithm................................................................................................................ 93
Method Algorithm ................................................................................................................................ 93

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Understanding Pseudocode .................................................................................................................. 94


Examples of Pseudocode ...................................................................................................................... 94
Symbols Used in Flowchart .................................................................................................................. 96
Examples of flowcharts in programming ......................................................................................... 97
3.3 Exercise 2: Algorithm ............................................................................................................ 97
4. Control Structures ............................................................................................................................. 98
4.1 Sequence: ....................................................................................................................................... 99
4.2 Selection ....................................................................................................................................... 100
4.2.3 Tutorial 4: Control /Conditional Statements .......................................................................... 106
4.3 Repetition / Looping ................................................................................................................... 112
3.4.1 while loop .............................................................................................................................. 113
• Syntax ........................................................................................................................................... 113
• Flow Diagram ................................................................................................................................. 113
• Example ........................................................................................................................................ 114
4.3.1 for loop............................................................................................................................ 115
• Syntax ........................................................................................................................................... 115
• Flow Diagram ................................................................................................................................. 115
• Example ........................................................................................................................................ 116
4.3.2 do...while loop................................................................................................................. 117
• Syntax ........................................................................................................................................... 117
• Flow Diagram ................................................................................................................................. 117
• Example ........................................................................................................................................ 118
4.3.3 nested loop ..................................................................................................................... 119
• Example of Nested while loop ................................................................................................. 125
• Example of Nested do-while loop ........................................................................................... 126
4.3.5 Tutorial 5: Repetition/Loop Statements ................................................................................. 127
4.4 Jumping Statement ....................................................................................................................... 132
What are jumping statements? .......................................................................................................... 132
1. break jumping statements. ............................................................................................................. 132
2. continue jumping statements.......................................................................................................... 133
3. goto jumping statements. ............................................................................................................... 133

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.5 Tutorial 6: Algorithm ..................................................................................................................... 135


4.5.1 Pengenalan ............................................................................................................................ 135
4.5.2 Objektif .................................................................................................................................. 135
4.5.3 Bahagian 1: Sequential Structure ........................................................................................... 135
4.5.4 Bahagian 2: Selection Structure ............................................................................................. 137
4.5.5 Bahagian 3: Repeatition Structure ......................................................................................... 138
5. Functions ............................................................................................................................................ 142
5.1 Type of Function ........................................................................................................................... 142
5.2 Benefits of Using Functions ........................................................................................................... 143
5.3 Function declaration / Function Prototypes ................................................................................. 143
5.4 Function definition Syntax ............................................................................................................ 143
5.4.1 return-type ............................................................................................................................. 143
5.4.2 function-name........................................................................................................................ 143
5.4.3 parameter-list ........................................................................................................................ 144
5.4.4 function-body......................................................................................................................... 144
5.5 Functions and Arguments ............................................................................................................. 144
5.5.1 Example: Function that return some value ............................................................................ 145
5.5.2 Nesting of Functions .............................................................................................................. 145
5.5.3 Recursion ............................................................................................................................... 146
5.6 Tutorial 7: Function ...................................................................................................................... 147
5.7 Tutorial 8: Algorithm for Function............................................................................................... 157
5.8 Quiz Function ................................................................................................................................ 163
6. Data Structures ............................................................................................................................... 164
6.1 Arrays ............................................................................................................................................ 164
6.1.1 One-dimensional Arrays ......................................................................................................... 165
6.1.2 Two-dimensional Arrays......................................................................................................... 174
6.2 Sorting an Array ............................................................................................................................ 177
6.2.1 Bubble Sort ............................................................................................................................ 177
6.2.2 Insertion Sort......................................................................................................................... 182
Summary ......................................................................................................................................... 183
6.2.3 Tutorial 13: Multi dimensional Array ..................................................................................... 184
6.3 Passing Arrays as Function Arguments ...................................................................................... 185

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.3 Structures ...................................................................................................................................... 191


6.31 Difference between C Variable, C Array and C Structure ........................................................ 191
6.3.2 Table Explains Following Concepts in C Structure .................................................................. 192
6.3.3 Example of Structure .............................................................................................................. 193
6.3.4 Tutorial 15: Structure ............................................................................................................. 197
7. References ...................................................................................................................................... 203

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

1. Introduction to Programming

1.1 Definition of Computer Program


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.

1.2 Differentiate Between of 5 Generation of Programming


Language

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

1GL
Machine Language

The Colossus Mark 2 was the world's first electronic digital programmable computer.
Operators had to write the machine code directly by setting switches.

Features / Characteristics / Advantages / Benefit Disadvantages / Weaknesses


Description
Lowest level of programming Machine language makes All operation codes have to
language fast and efficient use of the be remembered
computer
first programming language All memory addresses have
It requires no translator to to be remembered
Use machine code, binary translate the code. It is
digits (bits) 0 and 1. directly understood by the Code is difficult to edit and
computer update
The symbol 0 stands for the
absence and the 1 stands for Code cannot be ported to
the presence of an electric other systems and has to
pulse. be rewritten

It is hard to amend or find


errors in a program written
in the machine language

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2GL
Assembly Language

Assembly Code Object Code

LDA A 000100110100
ADD #5 001000000101
-> Assembler ->
STA A 001100110100
010000000011
JMP #3

Features / Characteristics / Advantages / Benefit Disadvantages / Weaknesses


Description
Lowest level of programming Assembly language is easier Like machine language, it
language to understand and use as is also machine
compared to machine dependent/specific
These alphanumeric symbols language
are known as mnemonic codes Since it is machine
Code can be fast and dependent, the
The assembly language is efficient programmer also needs to
converted to machine codes by understand the hardware
a language translator and then It is easy to locate and
they are executed by the correct errors
computer.
It is easily modified

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3GL
C | C++ | Java | PASCAL FORTRAN | BASIC | COBOL

Features / Characteristics / Advantages / Benefit Disadvantages /


Description Weaknesses
"High-level" programming To relieve the programmer A high-level language
language of the detailed and tedious has to be translated into
task of writing programs in the machine language
Procedural language uses a machine language and by a translator, which
series of English-like words, assembly languages takes up time
that are closer to human
language, to write instructions To provide programs that The object code
can be used on more than generated by a
Procedural languages, because one type of machine with translator might be
the program instructions very few changes inefficient compared to
comprise lists of steps, an equivalent assembly
procedures, that tell the To allow the programmer language program
computer not only what to do more time to focus on
but how to do it understanding the user’s
needs and designing the
A language translator is software required meeting
required to convert a high-level those needs
language program into machine
language The programmer spends less
time developing software
Two types of language with a high-level language
translators: than with assembly or
compilers and machine language because
interpreters fewer instructions have to
be created

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4GL
Structure Query Language (SQL)

Features / Characteristics / Advantages / Benefit Disadvantages / Weaknesses


Description
Fourth-generation languages Simplified the programming Less flexible that other
attempt to make communicating process languages
with computers as much like the
processes of thinking and talking Use nonprocedural Programs written in 4GLs
to other people as possible. languages that encourage are generally far less
users and programmers to efficient during program
The problem is that the computer specify the results they execution that programs
still only understands zeros and want, while the computers in high-level languages.
ones, so a compiler and interpreter determine the sequence of Therefore, their use is
must still convert the source code instructions that will limited to projects that
into the machine code that the accomplish those results do not call for such
computer can understand. efficiency.
Use natural languages that
Fourth-generation languages impose no rigid
typically consist of English-like grammatical rules
words and phrases.

Many fourth-generation languages


use Structured Query Language
(SQL) as the basis for operations.

SQL was developed at IBM to


develop information stored in
relational databases

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5GL
PROLOG

Features / Characteristics / Description Advantages / Benefit Disadvantages /


Weaknesses
The fifth-generation programming Logic based languages It can be very difficult to
language or visual programming are able to represent the design a database that
language is also known as natural real world more accurately represents
language accurately relationships

Provides a visual or graphical Prolog is able to derive Prolog is not best suited
interface, called a visual new rules from the to solving complex
programming environment, for existing rules contained arithmetical
creating source codes within the knowledge computations
base
Prolog programs are not
Fifth generation programming best suited to the
allows people to interact with current PC architecture
computers without needing any (sequential execution)
specialized knowledge and are best optimised
on parallel architectures
People can talk to computers and (fifth generation
the voice recognition systems can computers)
convert spoken sounds into written
words

Prolog and Mercury are the best-


known fifth-generation languages

PROLOG, an artificial intelligence


language that applies rules to data to
arrive at solutions

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Summary Generation Programming Language

Generation First Second Third Fourth

1010101001100010
Code LDA 34 x=x+1 body.top { color : red;
example 1001101010000001
1111111110100010 ADD #1 font-style : italic
STO 34 }

Language (LOW) Machine Code (LOW) (HIGH) Visual (HIGH) SQL, CSS, Haskell etc.
Assembly Code Basic, C, pytho
n etc.
Relation to -- one to one one to many one to many
Object Code
(generally)

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

1.3 Language Translators

A computer will not understand any program written in a language, other than its machine language.
The programs written in other languages must be translated into the machine language. Such
translation is performed with the help of software.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Language Translators /
Program Translator

Assembler Compiler Interpreter

1.3.1 Assembler

What is Assembler?

An assembler is a program that takes basic computer instructions and converts them into a
pattern of bits that the computer's processor can use to perform its basic operations.
Some people call these instructions assembler language and others use the term assembly
language.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

1.3.2 Compiler

What is Compiler?

It is a program which translates a high-level language program into a machine language


program.
A compiler is more intelligent than an assembler.
It checks all kinds of limits, ranges, errors etc.
But its program run time is more and occupies a larger part of the memory.
It has slow speed. Because a compiler goes through the entire program and then translates
the entire program into machine codes.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

1.3.3 Interpreter

What is Interpreter?

An interpreter is a program which translates statements of a program into machine code.


It translates only one statement of the program at a time.
It reads only one statement of program, translates it and executes it.
Then it reads the next statement of the program again translates it and executes it.
In this way it proceeds further till all the statements are translated and executed.
On the other hand, a compiler goes through the entire program and then translates the
entire program into machine codes.
A compiler is 5 to 25 times faster than an interpreter.
By the compiler, the machine codes are saved permanently for future reference.
On the other hand, the machine codes produced by interpreter are not saved.
An interpreter is a small program as compared to compiler.
It occupies less memory space, so it can be used in a smaller system which has limited
memory space.
They’re portable, which means they can run on different operating systems and platforms.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

1.3.4 Compiler VS Interpreter

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2. Fundamental of C Programming Language

2.1 C Program

What is C?
C is a ‘programming language’.
That is, it a language that allows you to specify exactly what you want your computer to do
and explan clearly for other people what you are doing.
C is a high level multi-purpose programming language that can be run across a number of
different platforms.Fpr example, it can run on:
• MS DOS
• Windows
• Unix
A high-level programming language uses keywords and symbols that human familiar with.
High level programming languages were developing to make easier for human to program
computers.
Remember all the information inside a computer is in binary form, including the program
instruction. It would be tedious for human be tedious for humans to enter this so-called
low-level code, so different high-level programming languages were developed, for
example PASCAL and C.
A high-level language cannot run directly on your computer, it must be compiled
(converted) into a set of simple instruction that a computer can use.
Each instruction is used to instruct the computer to perform a specific operation.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.1.1 The C Program Development Environment

C is program language of many different “dialects” because there are so many compilers.
Each compiler is a little different.
The library function of one will have all of ANSI C, the standard, but will also contain additional
functions.

An Editor
✓ This is basic text editors, which allow the user to write C code any text editor
can be used.
✓ The C program is called to C source code and is saved as source file (*.c or
*.cpp).

A Compiler
✓ C is a high-level language and in order for it to run on a PC, a C program
must be broken down in to a set of machine code instructions which can be
processed.
✓ This is the first part of the process of making an executable program.
✓ It is takes in a source file (*.c or *.cpp) and it produces object code which is
stored in an object file (*.obj).

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

A Link Editor
✓ As part of writing a program, code that has been written by other
developers can be inserted into a set of machine code instructions which
can be processed.
✓ A simple example of this is the stdio.h file which contain input and output
functions like printf () and scanf (), that are used to print text to the
computer monitor or received input type from the keyboard.
✓ The ouput of the link editor is an executable file(*.exe).

A Loader
✓ Part of the OS that brings an executable file residing on disk into memory
and starts it running

A Debugger
✓ This is used to debug problems in the code that has been written.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Summary: The C Environment


Edit:
Create / modify
source code Source file
(myprog.c)

Compile:
Generates machine
instruction

Yes
Error? Object file
(myprog.obj)
No

Link:
Link library files

Yes
Error? Object file
(myprog.exe)

No

Execute:
Run the program

No
Yes
Error?

No

Success!

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.1.2 Type of Programming Errors

Three types of errors

There are basically three types of errors that you must contend with when writing computer programs:

Programing
Errors

Syntax Runtime Logic

Syntax errors
In effect, syntax errors represent grammar errors in the use of the programming language. Common
examples are:
Misspelled variable and function names
Missing semicolons
Improperly matches parentheses, square brackets, and curly braces
Incorrect format in selection and loop statements

Runtime errors
Runtime errors occur when a program with no syntax errors asks the computer to do something that
the computer is unable to reliably do. Common examples are:
Trying to divide by a variable that contains a value of zero
Trying to open a file that doesn't exist

There is no way for the compiler to know about these kinds of errors when the program is compiled.
Incorrect format in selection and loop statements

Logic errors
Logic errors occur when there is a design flaw in your program. Common examples are:
Multiplying when you should be dividing
Adding when you should be subtracting
Opening and using data from the wrong file
Displaying the wrong message

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.1.3 Structure of a C Program

A C program basically consists of the following parts −

1. Preprocessor Commands
2. Functions
3. Variables
4. Statements & Expressions
5. Comments

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Example program:

1.

2.

What did it all mean?

In C programs are organized into blocks, called ‘function’.


A C function is similar to a mathematical function: it typically takes arguments; it
performs an operation on these, and typically returns a result.
For example, the additions of two numbers, a computer takes two numbers and
performs the addition operation on them and then return the result of the
operation.
In C, the function called ‘main’ is where the program execution starts.
In the case of a very simple program, the lines which make a ‘main function’ look
like:

main ()
{

However, this function doesn’t do anything until instructions are put inside the
squiggly brackets.
In the example program 1, above, there is one instruction inside:
printf (“\n Hello World”);

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

This is in fact an invocation of another function, printf ().


The printf function is provided with the compiling or operating system.
In this example, it takes a single operand, which is a ‘quoted string’ (“\n Hello
world”) and display this on the PC monitor.
Now look at the first line of code:
#include<stdio.h>
The # indicate that this is a pre-processor directive, which is an instruction to the
compiler to do something before compiling the source code.
If the main function is to call another function, in this case ‘printf’, the pre-
processor directive should instruct the compiler to ‘include’ in the program the file
stdio.h.
This file is called a header file, because it is usually included at the head of a
program.
It defines information about functions provided by a standard C libarary.
The stdio.h header file contains declarations for the standard input and output
functions available and must be included in the program to allow the use of the
printf () function.

2.1.4 Special Commands on C Preprocessor Directive

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process.
In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler
to do require pre-processing before the actual compilation.
We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#).
It must be the first nonblank character, and for readability, a preprocessor directive should
begin in the first column.
The following section lists down all the important preprocessor directives

Directive Description

#include Inserts a particular header from another file.

#define Substitutes a preprocessor macro.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.1.4.1 #include Directive

This C tutorial explains how to use the #include preprocessor directive in the C language.

Description
In the C Programming Language, the #include directive tells the preprocessor to insert the
contents of another file into the source code at the point where the #include directive is found.
Include directives are typically used to include the C header files for C functions that are held
out site of the current source file.

Syntax
The syntax for the #include directive in the C language is:
#include <header_file>
header_file

The name of the header file that you wish to include. A header file is a C file that typically ends
in ".h" and contains declarations and macro definitions which can be shared between several
source files.

Header Files

This is a list of the header files that you can include in your program if you want to use the functions
available in the C standard library:

Header File Type of Functions

<assert.h> Diagnostics Functions

<ctype.h> Character Handling Functions

<locale.h> Localization Functions

<math.h> Mathematics Functions

<setjmp.h> Nonlocal Jump Functions

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Header File Type of Functions

<signal.h> Signal Handling Functions

<stdarg.h> Variable Argument List Functions

<stdio.h> Input/Output Functions

<stdlib.h> General Utility Functions

<string.h> String Functions

<time.h> Date and Time Functions

2. 1.4.2 #define Directive (macro definition)

This C tutorial explains how to use the #define preprocessor directive in the C language.

Description

In the C Programming Language, the #define directive allows the definition of macros within
your source code.
These macro definitions allow constant values to be declared for use throughout your code.
Macro definitions are not variables and cannot be changed by your program code like
variables.
You generally use this syntax when creating constants that represent numbers, strings or
expressions.

Syntax

The syntax for creating a constant using #define in the C language is:
#define CNAME value
or
#define CNAME (expression)

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

✓ CNAME
The name of the constant. Most C programmers define their constant names in
uppercase, but it is not a requirement of the C Language.

✓ value
The value of the constant.

✓ expression
Expression whose value is assigned to the constant. The expression must be enclosed in
parentheses if it contains operators.

Note

Do NOT put a semicolon character at the end of #define statements. This is a common mistake.

Example

Let's look at how to use #define directives with numbers, strings, and expressions.

1. Number
The following is an example of how you use the #define directive to define a numeric
constant: #define AGE 17
In this example, the constant named AGE would contain the value of 17.

2. String
You can use the #define directive to define a string constant.
For example:
#define Name “Nelofa”
In this example, the constant called NAME would contain the value of "Nelofa"
Below is an example C program where we define these two constants:

#include <stdio.h>
#define NAME “Nelofa”
#define AGE 17
Int main ()
{
printf (“%s age in 2016 was %d years old.\n”, NAME, AGE);
return 0;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

This C program would print / display / output the following:

Nelofa age in 2016 was 17 years old.

3. Expression
You can use the #define directive to define a constant using an expression.
For example: #define AGE (34/2)
In this example, the constant named AGE would also contain the value of 17.
Below is an example C program where we use an expression to define the constant:

#include <stdio.h>
#define NAME “Nelofa”
#define AGE (34/2)
Int main ()
{
printf (“%s age in 2016 was %d years old.\n”, NAME, AGE);
return 0;
}

This C program would print / display / output the following:

Nelofa age in 2016 was 17 years old.

2.1.4.3 Header File

2.1.4.3.1 stdio.h library functions

All C inbuilt functions which are declared in stdio.h header file are given below. The source code for
stdio.h header file is also given below for your reference.

List of Inbuilt C Functions in stdio.h File:

Function Description
printf () This function is used to print the character, string, float, integer, octal
and hexadecimal values onto the output screen
scanf () This function is used to read a character, string, numeric data from keyboard.
getc () It reads character from file

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

gets () It reads line from keyboard


getchar () It reads character from keyboard
puts () It writes line to o/p screen
putchar () It writes a character to screen
clearerr () This function clears the error indicators
f open () All file handling functions are defined in stdio.h header file
f close () closes an opened file
getw () reads an integer from file
putw () writes an integer to file
f getc () reads a character from file
putc () writes a character to file
f putc () writes a character to file
f gets () reads string from a file, one line at a time
f puts () writes string to a file
f eof () finds end of file
f getchar reads a character from keyboard
f getc () reads a character from file
f printf () writes formatted data to a file
f scanf () reads formatted data from a file
f getchar reads a character from keyboard
f putchar writes a character from keyboard
f seeks () moves file pointer position to given location
SEEK_SET moves file pointer position to the beginning of the file
SEEK_CUR moves file pointer position to given location
SEEK_END moves file pointer position to the end of file.
f tells () gives current position of file pointer
rewind () moves file pointer position to the beginning of the file
putc () writes a character to file
sprint () writes formatted output to string
sscanf () Reads formatted input from a string
remove () deletes a file
fflush () flushes a file

2.1.4.3.2 math.h library functions

All C inbuilt functions which are declared in math.h header file are given below. The source code for
math.h header file is also given below for your reference.

List of Inbuilt C Functions In math.h File:

• “math.h” header file supports all the mathematical related functions in C language. All the
arithmetic functions used in C language are given below.
• Click on each function name below for detail description and example programs.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Function Description
floor () This function returns the nearest integer which is less than or equal to the
argument passed to this function.
round () This function returns the nearest integer value of the float/double/long
double argument passed to this function. If decimal value is from “.1 to .5”, it
returns integer value less than the argument. If decimal value is from “.6 to .9”, it
returns the integer value greater than the argument.
ceil () This function returns nearest integer value which is greater than or equal to the
argument passed to this function.
sin () This function is used to calculate sine value.
cos () This function is used to calculate cosine.
cosh () This function is used to calculate hyperbolic cosine.
exp () This function is used to calculate the exponential “e” to the x th power.
tan () This function is used to calculate tangent.
tanh () This function is used to calculate hyperbolic tangent.
sinh () This function is used to calculate hyperbolic sine.
log () This function is used to calculates natural logarithm.
log10 () This function is used to calculates base 10 logarithm.
sqrt () This function is used to find square root of the argument passed to this function.
pow () This is used to find the power of the given number.
trunc () This function truncates the decimal value from floating point value and returns
integer value.

Example Program for sqrt () Function In C:

1 #include <stdio.h>
2 #include <math.h>
3
4 int main ()
5{
6 printf ("sqrt of 16 = %f\n", sqrt (16));
7 printf ("sqrt of 2 = %f\n", sqrt (2));
8 return 0;
9}
Output:
sqrt of 16 = 4.000000
sqrt of 2 = 1.414214

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Example Program for pow () Function in C:

1 #include <stdio.h>
2 #include <math.h>
3
4 int main ()
5{
6 printf ("2 power 4 = %f\n", pow (2.0, 4.0));
7 printf ("5 power 3 = %f\n", pow (5, 3));
8 return 0;
9}

Output:
2 power 4 = 16.000000
5 power 3 = 125.000000

2.1.4.3.3 String Manipulations in C Programming Using Library Functions

In this article, you'll learn to manipulate strings in C using library functions such as gets (), puts,
strlen () and more. You'll learn to get string from the user and perform operations on the string.
You need to often manipulate strings according to the need of a problem. Most, if not all, of the
time string manipulation can be done manually but, this makes programming complex and large.

To solve this, C supports a large number of string handling functions in the standard library
"string.h".

Few commonly used string handling functions are discussed below:

Function Work of Function


strcpy () Copies a string to another string
strcat () Concatenates(joins) two strings
strcmp () Compares two string
strlwr () Converts string to lowercase
strupr () Converts string to uppercase

Strings handling functions are defined under "string.h" header file, i.e, you have to include the
code below to run string handling functions.

#include <string.h>

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

strlen function: size_t strlen (const char *str)

size_t represents unsigned short


It returns the length of the string without including end character (terminating char ‘\0’).

Example:

#include <stdio.h>
#include <string.h>
int main ()
{
char str1[20] = "BeginnersBook";
printf ("Length of string str1: %d", strlen(str1));
return 0;
}

Output:
Length of string str1: 13

strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof returns the total
allocated size assigned to the array. So, if I consider the above example again then the following
statements would return the below values.

strlen(str1) returned value 13.


sizeof(str1) would return value 20 as the array size is 20 (see the first statement in main
function).

strnlen function: size_t strnlen (const char *str, size_t maxlen)

size_t represents unsigned short


It returns length of the string if it is less than the value specified for maxlen (maximum length)
otherwise it returns maxlen value.

Example:

#include <stdio.h>
#include <string.h>
int main ()
{
char str1[20] = "BeginnersBook";
printf ("Length of string str1 when maxlen is 30: %d", strnlen (str1, 30));
printf ("Length of string str1 when maxlen is 10: %d", strnlen (str1, 10));
return 0;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10

Have you noticed the output of second printf statement, even though the string length was 13 it
returned only 10 because the maxlen was 10.

strcmp function: int strcmp (const char *str1, const char *str2)

It compares the two strings and returns an integer value. If both the strings are same (equal)
then this function would return 0 otherwise it may return a negative or positive value based on
the comparison.

If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If
string1 > string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for compare strings.

Example:

#include <stdio.h>
#include <string.h>
int main ()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp (s1, s2) ==0)
{
printf ("string 1 and string 2 are equal");
} else
{
printf ("string 1 and 2 are different");
}
return 0;
}

Output:
string 1 and 2 are different

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

strncmp function: int strncmp (const char *str1, const char *str2, size_t n)

size_t is for unassigned short


It compares both the string till n characters or in other words it compares first n characters of
both the strings.

Example:

#include <stdio.h>
#include <string.h>
int main ()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp (s1, s2, 8) ==0)
{
printf ("string 1 and string 2 are equal");
} else
{
printf ("string 1 and 2 are different");
}
return 0;
}

Output:
string1 and string 2 are equal

strcat function: char *strcat (char *str1, char *str2)

It concatenates two strings and returns the combined one string.

Example:

#include <stdio.h>
#include <string.h>
int main ()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat (s1, s2);
printf ("Output string after concatenation: %s", s1);
return 0;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Output:
Output string after concatenation: HelloWorld

strncat function: char *strncat (char *str1, char *str2, int n)

It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will always be
appended at the end of the concatenated string.

Example:

#include <stdio.h>
#include <string.h>
int main ()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat (s1, s2, 3);
printf ("Concatenation using strncat: %s", s1);
return 0;
}
Output:
Concatenation using strncat: HelloWor

strcpy function: char *strcpy (char *str1, char *str2)

It copies the string str2 into string str1, including the end character (terminator char ‘\0’).

Example:

#include <stdio.h>
#include <string.h>
int main ()
{
char s1[30] = "string 1";
char s2[30] = "string 2: I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy (s1, s2);
printf ("String s1 is: %s", s1);
return 0;
}
Output:
String s1 is: string 2: I’m gonna copied into s1

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.1.4.3.4 gets () and puts ()

Functions gets () and puts () are two string functions to take string input from the user and display it
respectively as mentioned in the previous chapter.

#include<stdio.h>
int main ()
{
char name [30];
printf ("Enter name: ");
gets(name); //Function to read string from user.
printf ("Name: ");
puts(name); //Function to display string.
return 0;
}

Note: Though, gets () and puts () function handle strings, both these functions are defined in "stdio.h"
header file.

2.1.4.3.5 conio.h library functions

All C inbuilt functions which are declared in conio.h header file are given below. The source code for
conio.h header file is also given below for your reference.

List of Inbuilt C Functions in conio.h File:

Functions Description
clrscr () This function is used to clear the output screen.
getch () It reads character from keyboard
getche () It reads character from keyboard and echoes to
o/p screen
textcolor () This function is used to change the text color
textbackground () This function is used to change text background

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.1.4.3.6 C Library - <ctype.h>


The ctype.h header file of the C Standard Library declares several functions that are useful for
testing and mapping characters.
All the functions accept int as a parameter, whose value must be EOF or representable as an
unsigned char.
All the functions return non-zero (true) if the argument c satisfies the condition described, and
zero(false) if not.

Library Functions
Following are the functions defined in the header ctype.h: -

No Function & Description

int isalnum (int c)


1
This function checks whether the passed character is alphanumeric.
int isalpha (int c)
2
This function checks whether the passed character is alphabetic.
int iscntrl (int c)
3
This function checks whether the passed character is control character.
int isdigit (int c)
4
This function checks whether the passed character is decimal digit.
int isgraph (int c)
5 This function checks whether the passed character has graphical representation
using locale.
int islower (int c)
6
This function checks whether the passed character is lowercase letter.
int isprint (int c)
7
This function checks whether the passed character is printable.
int ispunct (int c)
8
This function checks whether the passed character is a punctuation character.
int isspace (int c)
9
This function checks whether the passed character is white-space.
int isupper (int c)
10
This function checks whether the passed character is an uppercase letter.
int isxdigit (int c)
11
This function checks whether the passed character is a hexadecimal digit.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

The library also contains two conversion functions that accepts and returns an "int".

No Function & Description

int tolower (int c)


1
This function converts uppercase letters to lowercase.
int toupper (int c)
2
This function converts lowercase letters to uppercase.

Example

The following example shows the usage of islower () function.

#include <stdio.h>
#include <ctype.h>

int main ()
{
int var1 = 'Q';
int var2 = 'q';
int var3 = '3';

if(islower(var1))
{
printf ("var1 = |%c| is lowercase character\n", var1);
}
else
{
printf ("var1 = |%c| is not lowercase character\n", var1);
}

if(islower(var2))
{
printf ("var2 = |%c| is lowercase character\n", var2);
}
else
{
printf ("var2 = |%c| is not lowercase character\n", var2 );
}

if(islower(var3))
{
printf ("var3 = |%c| is lowercase character\n", var3);
}
else
{

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

printf ("var3 = |%c| is not lowercase character\n", var3);


}

return (0);
}

Let us compile and run the above program to produce the following result −

var1 = |Q| is not lowercase character


var2 = |q| is lowercase character

var3 = |3| is not lowercase character

2.1.5 C Language Reserved Words

Keywords
C programs are constructed from a set of reserved words which provide control and from libraries
which perform special functions. The basic instructions are built up using a reserved set of words, such
as main, for, if, while, default, double, extern, for, and int, etc., C demands that they are used only for
giving commands or making statements. You cannot use default, for example, as the name of a
variable. An attempt to do so will result in a compilation error.

Keywords have standard, predefined meanings in C. These keywords can be used only for their
intended purpose; they cannot be used as programmer-defined identifiers. Keywords are an essential
part of a language definition. They implement specific features of the language. Every C word is
classified as either a keyword or an identifier. A keyword is a sequence of characters that the C
compiler readily accepts and recognizes while being used in a program. Note that the keywords are all
lowercase. Since uppercase and lowercase characters are not equivalent, it is possible to utilize an
uppercase keyword as an identifier.

• The keywords are also called Reserved words.


• Keywords are the words whose meaning has already been explained to the C compiler and
their meanings cannot be changed.
• Keywords serve as basic building blocks for program statements.
• Keywords can be used only for their intended purpose.
• Keywords cannot be used as user-defined variables.
• All keywords must be written in lowercase.
• 32 keywords available in C.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Data User- Storage


Qualifiers Loop
types defined Classes
• int • signed • typedef • auto • for
• char • unsigned • enum • extern • while
• float • short • register • do
• double • long • static

Other Decision Jump Derived Function


• const • if • goto • auto • void
• volatile • else • continue • extern • return
• sizeof • switch • break • register
• case • static
• default

Restrictions apply to keywords


• Keywords are the words whose meaning has already been explained to the C compiler and
their meanings cannot be changed.
• Keywords can be used only for their intended purpose.
• Keywords cannot be used as user-defined variables.
• All keywords must be written in lowercase.

Data type Keywords

int Specifies the integer type of value a variable will hold


char Specifies the character type of value a variable will hold
float Specifies the single-precision floating-point of value a variable will hold
double Specifies the double-precision floating-point type of value a variable will

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Qualifier Keywords

signed Specifies a variable can hold positive and negative integer type of data
unsigned Specifies a variable can hold only the positive integer type of data
short Specifies a variable can hold fairly small integer type of data
long Specifies a variable can hold fairly large integer type of data

Loop Control Structure Keywords

For Loop is used when the number of passes is known in advance


While Loop is used when the number of passes is not known in advance
Do Loop is used to handle menu-driven programs

User-defined type Keywords

typedef Used to define a new name for an existing data type


Enum Gives an opportunity to invent own data type and define what values the variable of this
data type can take

Jumping Control Keywords

Break Used to force immediate termination of a loop, bypassing the conditional expression and
any remaining code in the body of the loop
continue Used to take the control to the beginning of the loop bypassing the statements inside the
loop
Goto Used to take the control to required place in the program

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.1.6 Tutorial 1: Creating and Editing a Basic Program

Exercise 1: Example C Program

1. Create a directory on your disk to store your C program:


C:\Librararies\Documents\Programming C\Tutorial1\
2. Start the C programming environment.
3. Type in the following program code exactly as written below:
//Exercise 1.1 – Hello World

#include<stdio.h>
/* This program prints the text Hello World on the PC Monitor.
Let try! */
main ()
{
printf (“Hello World”);
}

4. Save the file as Ex1.c


5. Compile the file using the compile to obj option.
6. Link the code using compile/link exe option.
7. Execute the file using the run option.
8. From the OS shell print out files in your C:\Librararies\Documents\Programming C\Tutorial1\
directory. There should now be 3 files; ed ex1.c, ex1.obj and ex1.exe.

Exercise 2: Example C Program

1. Open the file Ex1.c


2. Add the following line after the printf statement
printf (“\n means New Line \t”);
printf (“\t means Tab\n”);
3. Save as the file Ex2.c
4. Compile, link and run the file.
5. What is display on the screen?

Exercise 2: Example C Program

1. Create a new file called Ex3.c which prints the following text on the PC monitor:
My name is Nora Danish
Have A Good Day!!
2. Save, compile, link and run the file.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.2 Basic Data Types

2.2.1 Data types in C Language

Data types specify how we enter data into our programs and what type of data we enter. C
language has some predefined set of data types to handle various kinds of data that we use in
our program. These datatypes have different storage capacities.
C language supports 2 different types of data types,

Primary data types


These are fundamental data types in C namely integer (int), floating (float), character (char)
and void.

Derived data types


Derived data types are like arrays, functions, structures and pointers. These are discussed in
detail later.

Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine

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
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

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Floating type
Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range


Float 4 with six digits of 3.4E-38 to 3.4E+38
double precision
8 with ten digits of 1.7E-308 to 1.7E+308
precision10
long double 3.4E-4932 to 1.1E+4932

Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

void type
void type means no value. This is usually used to specify the type of functions.

Example declare and initialise for data type:


char c = 'A';

int i = 2015;

float f = 11.243567;

double d = 11676.2435676542;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

C Programming Strings

In C programming, array of characters is called a string. A string is terminated by a null


character /0. For example:

"c string tutorial"

Here, "c string tutorial" is a string. When, compiler encounter strings, it appends a null
character /0 at the end of string.

Declaration of strings

• Before we actually work with strings, we need to declare them first.


• Strings are declared in a similar manner as arrays. Only difference is that, strings are
of char type.

Using arrays
char s [5];

Initialization of strings

• In C, string can be initialized in a number of different ways.


• For convenience and ease, both initialization and declaration are done in the same step.

Using arrays

char c [] = "abcd";
OR,
char c [50] = "abcd";
OR,
char c [] = {'a', 'b', 'c', 'd', '\0'};
OR,
char c [5] = {'a', 'b', 'c', 'd', '\0'};

Reading Strings from user

• You can use the scanf () function to read a string like any other data types.
• However, the scanf () function only takes the first entered word. The function terminates
when it encounters a white space (or just space).

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Reading words from user

char c [20];

scanf ("%s", c);

Example #1: Using scanf () to read a string

• Write a C program to illustrate how to read string from terminal.

#include <stdio.h>
int main ()
{
char name [20];
printf ("Enter name: ");
scanf ("%s", name);
printf ("Your name is %s.", name);
return 0;
}

Output
Enter name: Dennis Ritchie
Your name is Dennis.

• Here, program ignores Ritchie because, scanf () function takes only a single string before the
white space, i.e. Dennis.

Reading a line of text

• An approach to reading a full line of text is to read and store each character one by one.
• Example #1: Using getchar () to read a line of text

1. C program to read line of text character by character.

#include <stdio.h>
int main ()
{
char name [30], ch;
int i = 0;
printf ("Enter name: ");
while (ch! = '\n’) // terminates if user hit enters
{
ch = getchar ();

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

name[i] = ch;
i++;
}
name[i] = '\0’; // inserting null character at end
printf ("Name: %s", name);
return 0;
}

• In the program above, using the function getchar (), ch gets a single character from the user
each time.
• This process is repeated until the user enters return (enter key). Finally, the null character is
inserted at the end to make it a string.
• This process to take string is tedious.
• Example #2: Using standard library function to read a line of text

2. C program to read line of text using gets () and puts ()

o To make life easier, there are predefined functions gets () and puts in C language to
read and display string respectively.
#include <stdio.h>
int main ()
{
char name [30];
printf ("Enter name: ");
gets(name); //Function to read string from user.
printf ("Name: ");
puts(name); //Function to display string.
return 0;
}
Both programs have the same output below:
Output
Enter name: Tom Hanks
Name: Tom Hanks

Passing Strings to Functions

• Strings are just char arrays. So, they can be passed to a function in a similar manner as
arrays.
• Learn more about passing array to a function.

#include <stdio.h>
void displayString (char str []);

int main ()

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

{
char str [50];
printf ("Enter string: ");
gets(str);
displayString(str); // Passing string c to function.
return 0;
}
void displayString (char str [])
{
printf ("String Output: ");
puts(str);
}
• Here, string c is passed from main () function to user-defined function displayString (). In
function declaration, str [] is the formal argument.

Boolean
bool is a data type in C. It sends for Boolean variable, i.e. the variable which can has
only 0 or 1 value. In this case the value is True or False.

If you decide to define them yourself, the choice between #defines and enumeration
constants for the true/false values is arbitrary and not terribly interesting. Use any of

#define TRUE 1 #define YES 1


#define FALSE 0 #define NO 0

enum bool {false, true}; enum bool {no, yes};

or use raw 1 and 0, as long as you are consistent within one program or project. (An
enumeration may be preferable if your debugger shows the names of enumeration
constants when examining variables.)

You may also want to use a typedef:

typedef int bool;


or
typedef char bool;
or
typedef enum {false, true} bool;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Some people prefer variants like

#define TRUE (1==1)


#define FALSE (! TRUE)

Numeric constants: There are two types of numeric constants,

1. Integer constants
2. Real or floating-point constants

Integer constants

• Any whole number value is an integer.


• An integer constant refers to a sequence of digits without a decimal point.
• An integer preceded by a unary minus may be considered to represent a negative constant
• Example: 0 -33 32767

Decimal Integer constant (base 10)

• It consists of any combinations of digits taken from the set 0 through 9, preceded by an
optional – or + sign.
• The first digit must be other than 0.
• Embedded spaces, commas, and non-digit characters are not permitted between digits.

Valid: 0 32767 -9999 -23


Invalid: 12,245 - Illegal character (,)
10 20 30 - Illegal character (blank space)

Unsigned integer constant


An unsigned integer constant specifies only positive integer value. It is used only to count things. This
constant can be identified by appending the letter u or U to the end of the constant.

Valid: 0u 1U 65535u 0x233AU


Invalid: -123 - Only positive value

Long integer constant


A long integer constant will automatically be generated simply by specifying a constant that exceeds the
normal maximum value. It is used only to count things. This constant can be identified by appending the
letter l or L to the end of the constant.
Valid: 0l23456L 0x123456L -123456l
Invalid: 0x1.2L - Illegal character (.)

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Short integer constant


A short integer constant specifies small integer value. This constant can be identified by appending the
letter s or S to the end of the constant.

Valid: 123s -456 32767S


Invalid: 12,245 - Illegal character (,)
10 20 30 - Illegal character (blank space)

Note: - A sign qualifier can be appended at the end of the constant. Usually suffixes (s or S, u or U, l or L)
are not needed. The compiler automatically considers small integer constants to be of type short and
large integer constants to be of type long.

Rules for constructing Integer constants

i. An integer constant must have at least one digit.


ii. It must not have a decimal point.
iii. It can be either positive or negative.
iv. If no sign precedes an integer constant, it is assumed to be positive.
v. Commas or blanks are not allowed within an integer constant.

Real or Floating-point constant


Constants in C are fixed value that does not change during the execution of a program. A real constant is
combination of a whole number followed by a decimal point and the fractional part. Example:
0.0083 -0.75 .95 215.

Use of Real or Floating-point constants

Integer numbers are inadequate to represent quantities that vary continuously, such as
distances, heights, temperatures, prices and so on. These quantities are represented by numbers
containing fractional part. Such numbers are called real or floating-point constants.

The Real or Floating-point constants can be written in two forms:

1. Fractional or Normal form


2. Exponential or Scientific form

Express a Real constant in fractional form

A real constant consists for a series of digits representing the whole part of the number, followed by a
decimal point, followed by a series of representing the fractional part. The whole part or the fractional
part can be omitted, but both cannot be omitted. The decimal cannot be omitted. That is, it is possible
that the number may not have digits before the decimal point or after the decimal point.

Valid Real constants (Fractional): 0.0 -0.1 +123.456 .2 2.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Invalid Real constant: - 1 - a decimal point is missing


1, 2.3 - Illegal character (.)

Rules for Constructing Real Constants in Fractional Form

1. A real constant must have at least one digit.


2. It must have a decimal point.
3. It could be either positive or negative.
4. Default sign is positive.
5. Commas or blanks are not allowed within a real constant.

String Constant

A character string, a string constant consists of a sequence of characters enclosed in double


quotes.
A string constant may consist of any combination of digits, letters, escaped sequences and
spaces. Note that a character constant ‫ۥ‬A‫ ۥ‬and the corresponding single character string
constant "A" are not equivalent.

‫ۥ‬A‫ۥ‬ - Character constant - ‫ۥ‬A‫ۥ‬


"A" - String Constant - ‫ۥ‬A‫ۥ‬ and ‫ۥ‬0\ ‫( ۥ‬NULL)

The string constant "A" consists of character A and \0. However, a single character string
constant does not have an equivalent integer value. It occupies two bytes, one for the ASCII
code of A and another for the NULL character with a value 0, which is used to terminate all
strings.

Valid String Constants: - "W" "100" "24, Kaja Street"

Invalid String Constants: - "W the closing double quotes missing


Raja" the beginning double quotes missing

Rules for Constructing String constants

1) A string constant may consist of any combination of digits, letters, escaped sequences
and spaces enclosed in double quotes.
2) Every string constant ends up with a NULL character which is automatically assigned
(before the closing double quotation mark) by the compiler.

Difference between single character constant and string constant

Character Constant String Constant


A character constant is enclosed within single A sequence of characters enclosed in double
inverted commas. quotes.
The maximum length of a character constant A string constant can be any length.
can be one character.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

A single character string constant has an A single character string constant does not
equivalent integer value. have an equivalent integer value.
The character constant ‘A’ consists of only The string constant "A" consists of
character A. character A and \0.
A single character constant occupies one A single string constant occupies two bytes.
byte.
Every character constant does not end up Every string constant ends up with a NULL
with a NULL character. character which is automatically assigned
(before the closing double quotation mark) by
the compiler.

How to Use Constants in A C Program?


C Constants are also like normal variables. But only difference is, their values cannot be
modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax: const data_type variable_name;

We can define constants in a C program in the following ways.

1. By “const” keyword
2. By “#define” preprocessor directive

Please note that when you try to change constant values after defining in C program, it will through
error.

1. Example program using const keyword in c:

1 #include <stdio.h>
2 void main ()
3 {
4 const int height = 100; /*int constant*/
5 const float number = 3.14; /*Real constant*/
6 const char letter = 'A'; /*char constant*/
7 const char letter_sequence [10] = "ABC"; /*string constant*/
8 const char backslash_char = '\?'; /*special char cnst*/
9 printf ("value of height: %d \n", height);
10 printf ("value of number: %f \n", number);
11 printf ("value of letter: %c \n", letter);
12 printf ("value of letter_sequence: %s \n", letter_sequence);
13 printf ("value of backslash_char: %c \n", backslash_char);
14 }

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Output:

value of height: 100


value of number: 3.140000
value of letter: A
value of letter_sequence: ABC
value of backslash_char:?

2. Example program using #define preprocessor directive in c:

1 #include <stdio.h>
2 #define height 100
3 #define number 3.14
4 #define letter 'A'
5 #define letter_sequence "ABC"
6 #define backslash_char '\?'
7 void main ()
8 {
9 printf ("value of height: %d \n", height);
10 printf ("value of number: %f \n", number);
11 printf ("value of letter: %c \n", letter);
12 printf ("value of letter_sequence: %s \n”, letter_sequence);
13 printf ("value of backslash_char: %c \n”, backslash_char);
14 }

Output:

value of height: 100


value of number: 3.140000
value of letter: A
value of letter_sequence: ABC
value of backslash_char:?

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

C – Variable
C 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.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.

Rules for Naming C Variable:


1. Variable name must begin with letter or underscore.
2. Variables are case sensitive.
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name

Declaring & Initializing C Variable:


• Variables should be declared in the C program before to use.
• Memory space is not allocated for a variable while declaration. It happens only on variable
definition.
• Variable initialization means assigning a value to the variable.

Type Syntax
Variable declaration data_type variable_name;
Example: int x, y, z; char flat, ch;
Variable data_type variable_name = value;
initialization
Example: int x = 50, y = 30; char flag = ‘x’, ch=’l’;

There Are Three Types of Variables in C Program They Are,


a) Local variable
b) Global variable
c) Environment variable

1. Example Program for Local Variable In C:


• The scope of local variables will be within the function only.
• These variables are declared within the function and can’t be accessed outside the function.
• In the below example, m and n variables are having scope within the main function only. These
are not visible to test function.
• Likewise, a and b variables are having scope within the test function only. These are not visible to
main function.
1 #include<stdio.h>
2 void test ();
3
4 int main ()
5 {
6 int m = 22, n = 44;
7 // m, n are local variables of main function

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

8 /*m and n variables are having scope


9 within this main function only.
10 These are not visible to test funtion. */
11 /* If you try to access a and b in this function,
12 you will get 'a' undeclared and 'b' undeclared error */
13 printf ("\nvalues: m = %d and n = %d", m, n);
14 test ();
15 }
16
17 void test ()
18 {
19 int a = 50, b = 80;
20 // a, b are local variables of test function
21 /*a and b variables are having scope
22 within this test function only.
23 These are not visible to main function. */
24 /* If you try to access m and n in this function,
25 you will get 'm' undeclared and 'n' undeclared
26 error */
27 printf ("\n values: a = %d and b = %d", a, b);
28 }
Output:

values: m = 22 and n = 44
values: a = 50 and b = 80

2. Example Program for Global Variable in C:

• The scope of global variables will be throughout the program. These variables can be accessed
from anywhere in the program.
• This variable is defined outside the main function. So that, this variable is visible to main function
and all other sub functions.
1 #include<stdio.h>
2 void test (); int m = 22, n = 44;
3 int a = 50, b = 80;
4
5 int main ()
6 {
7 printf ("All variables are accessed from main function");
8 printf ("\nvalues: m=%d: n=%d: a=%d: b=%d", m, n, a, b);
9 test ();
10 }
11
12 void test ()
13 {
14 printf ("\n\nAll variables are accessed from" \

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

15 " test function");


16 printf ("\nvalues: m=%d: n=%d: a=%d: b=%d", m, n, a, b);
17 }
Output:

All variables are accessed from main function


values: m = 22: n = 44: a = 50: b = 80
All variables are accessed from test function
values: m = 22: n = 44: a = 50: b = 80

Array

C Array is a collection of variables belongings to the same data type. You can store group of data
of same data type in an array.

Array might be belonging to any of the data types


Array size must be a constant value.
Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any
values to array.

Example for C Arrays:

int a [10]; // integer array


char b [10]; // character array i.e. string

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Struct
C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.

If you want to access structure members in C, structure variable should be declared.


Many structure variables can be declared for same structure and memory will be
allocated for each separately.
It is a best practice to initialize a structure to null while declaring, if we don’t assign
any values to structure members.
Example member / attribute Student and Employee as a below:

Example of Struct

1.

2.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Difference between C Variable, C Array and C Structure:

A normal C variable can hold only one data of one data type at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types and Data types can be int, char, float,
double and long double etc.

C Structure:
Syntax struct student
{
int a;
char b [10];
}
Example a = 10;
b = “Hello”;

C Variable:
int Syntax: int a;
Example: a = 20;
char Syntax: char b;
Example: b=’Z’;

C Array:
int Syntax: int a [3];
Example:
a [0] = 10;
a [1] = 20;
a [2] = 30;
a [3] = ‘\0’;
char Syntax: char b [10];
Example: b=” Hello”;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Below table explains following concepts in c structure.

1. How to declare a C structure?


2. How to initialize a C structure?
3. How to access the members of a C structure?

Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example:
struct student
{
int mark;
char name [10];
float average;
};
Declaring structure using normal variable:
struct student report;
Initializing structure using normal variable:
struct student report = {100, “Mani”, 99.5};
Accessing structure members using normal variable:
report. mark;
report.name;
report. average;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.2.2 Tutorial 2

*Save as in C:\Librararies\Documents\Programming C\Tutorial2\

1. Exercise Introduction

/*This is a basic structure C program*/

#include <stdio.h>

void main ()
{
int form = 6;

printf ("\n I study at SMK Tinggi, Setapak.");


printf ("\n My class name is form %d Science 2", form);
}

2. Exercise Decimal 1

#include<stdio.h>

void main ()
{
printf ("%d, %d, %d\n",456, 456, 456);
printf ("%5d, %5d, %5d\n",456, 456, 456);
printf ("%7d, %7d, %7d\n",456, 456, 456);
}

3. Exercise Decimal 2

#include<stdio.h>

void main ()
{
printf ("%d, %d, %d\n",456, 456, 456);
printf ("%-5d, %-5d, %-5d\n",456, 456, 456);
printf ("%-7d, %-7d, %-7d\n",456, 456, 456);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4. Exercise Decimal 3

#include<stdio.h>

void main ()
{
int day, month, year;

printf ("Please enter a date:\n");


scanf ("%d %d %d”, &day, &month, &year);

printf ("Day: %d\t Month: %d\t Year: %d", day, month, year);
}

5. Exercise Character 1

#include<stdio.h>

void main ()
{
char my_alphabet;

printf ("Enter an alphabet from a to z: ");


scanf ("%c", &my_alphabet);

printf ("\nYou typed an alphabet %c", my_alphabet);


}

6. Exercise Character 2

#include<stdio.h>

void main ()
{
char gender;

printf ("Type f if you are female or m if you are male: ");


scanf ("%c", &gender);

printf ("\nYour are %c", gender);


}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

7. Exercise Float 1

#include<stdio.h>
void main ()
{
int item;
float price, sum;

printf ("Price: RM ");


scanf ("%f”, &price); //price input
printf ("Number of items: ");
scanf ("%d”, &item); //item input

sum = price * item;


printf ("\nYou have to pay RM %.2f\n”, sum);
//%.2f = The output is rounded to 2 decimal places
}

8. Exercise Float 2

#include<stdio.h>
void main ()
{
printf("%6.2f\n",123.4567);
printf("%7.1f\n",123.4567);
printf("%7.2f\n",123.4567);
printf("%7.3f\n",123.4567);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.3 Input and Output

Input and output function can used when you include a header file “stdio.h”

#include<stdio.h>

The printf have several format specifications:-

%d -> print integer

%u -> print unsigned integer

%ld -> print long integer

%f -> print a float

%lf -> print long float(double)

%e -> print a floating in scientific notation

%c -> print a character

%s -> print a string

Any occurences of the ‘ \ ’ character inside string is called an escape sequence. Some common
escape sequence :-

\’ - Output a single quote( ‘ ) charecter

\” - Output a double quote ( “ ) character

\? - output a question mark ( ? ) character

\\ - output a backslash( \ ) character

\a - cause an audible (bell) or visual alert

\b - move the cursor back one position on the current line

\f - move the cursor to the next logical page

\n - move the cursor to the beginning of the next line

\r - move the cursor to the beginning of the current line

\t - move the cursor to the next horizontal tab position

\v - move the cursor to the next vertical tab position

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.3.1 Printing String

Format specification: %s
You can specify a field with by placing a decimal number between the % and s, if the number is
larger than the data requires. It is padded with space on the left.
Example 1:

printf ( “Computer\n”); Output:

printf (“%s\n”, “Computer”);


Computer
printf(“%4s\n”, “Computer”);
Computer
printf(“%13s\n”, “Computer”);
Computer
Example 2:
#include<stdio.h> ~~~~~Computer
void main()
{
char color[ ] = “Yellow”;
printf(“%s”, color);
}
Example 3:

#include<stdio.h>
main()
{
printf(“[%30s]\n”, “SMK. Tinggi Setapak”);
printf(“[%-30s]\n”, “SMK. Tinggi Setapak”);
printf(“[%15.6s]\n”, “SMK. Tinggi Setapak”);
printf(“[%-15.6s\n”, “SMK. Tinggi Setapak”);
return 0;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.3.2 Printing Characters

Format : %c
Same as printing a string, you can specify a filed width by placing a decimal number between the
% and c.

Example:

printf(“%c%c%c%c”,’J’,’U’,’N’,’E’);

Output:

JUNE

printf(“%c%3c%7c”, ‘A’,’B’,’C’);

Output: A~~B~~~~~~C

char let1, let2, let3, let4;

let1 = ‘J’;

let2 = ‘U’;

let3 = ‘N’;

let4 = ‘E’;

printf(“%c%c%c%c”, let1, let2, let3, let4);

Output:

JUNE

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.3.3 Printing Integers and Floating Point Numbers

Format: %d - integers
%f - float

Coding: printf(“%5d\n”, 66);


printf(“%-5d%4d”,66,777);
Output: ~~~66
66~~~~777

Coding 1:
int num1;
float num2;
num1 = 5;
num2 = 33.77;
printf(“The first number is = %d \n”, num1);
printf(“The second number is = %f \n”, num2);

Output:
The first number is = 5
The second number is = 33.7700

Coding: printf(“%d\n”, 1234); Coding: printf(“%5d\n”, 1234);


printf(“%2d\n”, 1234); printf(“%6d\n”, 1234);
printf(“%3d\n”, 1234); printf(“%7d\n”, 1234);
printf(“%4d\n”, 1234); printf(“%8d\n”, 1234);
Output: ~1234
Output: 1234 ~~1234
1234 ~~~1234
1234 ~~~~1234
1234

Meanwhile, a format for floating point number is: %m.nf

▪ m=field width(the maximum number of total characters to print)

▪ n=number of decimal places (how many digits after the decimal point to print)

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020
Coding 1: Output:

printf(“%6.1f\n”, 12.12345); ~~12.1

printf(“%6.2f\n”, 12.12345); ~12.12

printf(“%6.3f\n”, 12.12345); 12.123

Coding 2:

printf(“% .1f\n”, 12.345678); Output:


The output is
12.3
printf(“% .2f\n”, 12.345678); rounded to 2
12.35
decimal places
printf(“% .3f\n”, 12.345678); 12.346

Coding 3:

printf(“%4.2f\n”, 7.88);
Output:
printf(“%4.2f\n”, 7.888); 7.88
7.89
printf(“%4.2f\n”, 7.8); 7.80
777.89
printf(“%4.2f\n”, 777.888);

2.3.4 Displaying Several Values at Once

You may use a single printf() to display several values

Coding:

printf(“%8.2f%3c%8d”, 7.2, ‘R’, 250);

The single printf() statement is equivalent to the three statement:


Output:
printf(“%8.2f”, 7.2);
~~~~7.20~~R~~~~~250
printf(“%3c”, ‘R’);
printf”%8d”, 250);

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Coding:

int year = 19;

float height = 1.72;

printf(“Weng Yee is %d years old and %.2f m height”, year, height);

Otuput:

Weng Yee is 19 years old and 1.72 m height

2.3.5 The scanf( ) Function

%d - read an integer

%f - read a float

%lf - read a long float(double)

%c - read a character

%s - read a string

Coding 1: Output:
Please enter a date:
int day, month, year;
24 6 2008
printf(“Please enter a date:\n”);
Day: 24 Month: 6 Year: 2008
scanf(“%d %d %d”, &day, &month, &year);
printf(“ Day:%d\t Month:%d\t Year:%d”, day, month, year);

Coding 2 :

char x, y[9];
printf(“Enter a string:”); Output:
scanf(“%c%s”, &x, y); Enter a string:Earth
printf(“The input was:\n”); The input was:
printf(“The character \”%c\””, x); The character “E” and the string “arth”
printf(“ and the string \”%s\””,y);

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.3.6 Other Functions for Input/Output Purposes

1. getc( ) and putc( )


2. getchar( ) and putchar( )
3. getch( ) and putch( )
4. gets( ) and puts( )

1. The getc( ) and putc( )

• function can be accessed from the standard header file<stdio.h>.


• The getc( ) reads a single character from standard input device.
• The putc( ) function prints one single character on the strandard output device:
• Format:-
variable = getc(stdin);
putc(variable, stdout);

2. The getchar( ) and putchar( ) function

• same as the getc( ) and putc( ) except you do not need to put the standard input/output
device in parenthesis.
• Format:-
variable = getc(stdin); putc(variable, stdout);
variable = getchar( ); putchar(variable);

Example:

#include<stdio.h>
main( )
{
int my_character;
printf(“Enter a character please:”);
my_character = getchar();
printf(“\n You typed a
character>>>”);
putchar(my_character);
return 0;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3. For getch( ) and putch( ) functions,

✓ you do not need to put the input/output standard device in the parenthasis.
✓ The format:
variable = getch( );
putch(variable);
✓ but this functions are eccessed from the standard header file<conio.h>.
✓ The other different is the input character from the keyboard will not be displayed on the
screen whereas for the other function before, the input can be seen on the screen.

Example:

#include<stdio.h>
#include<conio.h>

main( )
{
char letter;
printf(“Enter a character\n”);
letter = getch();
printf(“the character you have typed is:”);
putch(letter);
return 0;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3. The gets( ) and puts) can be accessed from the standard header file<stdio.h>.

✓ The gets( ) function reads a string entered from the keyboard.


✓ It will end the string with a null(\0) character.
✓ The puts( ) function prints a string on the screen.
✓ It will end the string with a new line( n) character.

Example:

#include<stdio.h>
#include<conio.h>

void main()

{
char name[30];
printf(“Enter your name>>”);
gets(name); /*reads a string */
printf(“\n How are you ”);
puts(name); /* prints a string */
puts(“\nIt is your lucky day!!!”);
getch();
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.3.7 Excercise 1 : Data Type – Character and String

1. A C program contains the following statements:


#include<stdio.h>
char a, s, y;

a) write appropriate getchar statement that will allow values for a, s and y to be entered into the
computer.

b) b) write appropriate putchar statement that will allow the current values of a, s, and y to be
written out of the computer.

2. A C program contains the following statements:

#include<stdio.h>
char text[55];

Write a scanf function that will allow a string to be read into the computer and assigned to the
caharacter array text. Assume that the string does not contain any whitespace characters.

3. A C program contains the following statements:

#include<stdio.h>
char name[30];

Write a printf function that will allow the contents of name to be displayed in the following ways:
a) Entirely on one line
b) Only the first five characters
c) The first five characters, followed by 7 blanks.
d) The first five characters, preceded by 7 blanks.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.4 Expressions and Operators

2.4.1 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

Arithmetic Operators
Assignment Operators
Unary Operators
Relational and Equality Operators
Logical Operators

2.4.1.1 Arithmetic Operators

We need operators to construct statements to do an operation and calculations.

Operator is a token that can be aplied to variables or any elements in an expression to


produce some kind of computation or action.

+ Addition operator
- Substraction operator
* Multiplication operator
/ Division operator
% Modulus operator(Remainder fo dividion)

*The fifth operator, % is called the ramainder(or modulus) operator. Its operands must be
integer
quantities.

Example 1: 43%8 = 3

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Example 2:

#include<stdio.h>
main( )
{
int num = 20, val = 30;

printf(“nilai asal num:%d dan dilai asal val:%d\n”, num,val);


num = val +5; /* addition operator: num is now 35 */

printf(“nilai num sekarang ialah:%d\n”,num);

val=num-val; /* substraction operator: val is now 5 */

printf(“nilai val ialah:%d\n”,val);

num=num * 2; /* multiplication operator: num is now 70 */

printf(“nilai num setelah darab dua ialah:%d\n”,num);

val=30/7; /* division operator: val is now 4 */

printf(“nilai baru val :%d\n”,val);

1. Assigning Mathematical Operator Combinations

To increase or decrease the value already assigned to a variable:

Example:

int num = 5; Or:

num = num – 6; int num = 5;

num -= 6;

int num = 5;

num -= 3; /* same as num =num -3; num is now 2 */

num *=4; /* same as num = num *4; num is now 8 */

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Compound Assignment

Operator Syntax Meaning


*= price*=2.5; price = price * 2.5;
/= total /=2; total=total/2;
%= month %=2; month = month %2;
+= bonus +=800; bonus = bonus+800;
-= balance -=sum+tax; balance = balance – (sum+tax)

2. Unary Sign Operator

Unary Operator---the unary operator operates on a single variable or constant statement.


Unary operator require only one operand and consist the symbols +,-,++ or --.
Example:
x = -y; p = +x * y;
++count; count--;

3. Binary Operator

Each operand links something from left to right with some action.
Binary operators require two operands and consist the symbol +,-,*,/,or %.
Example: z = y – x; x = y + z;

4. Expression with Multiple Operators

Expression can include both unary and binary operators. For readability, do not use a space
between a unary operator and its operand; do use space before and after binary operators.
Use bracket, if more then one expression, from left to right ( →) Rules for Evaluation of
Arithmetic Expressions.
The operator precedence rule:Operators in the same sub-expression are evaluated in the
following order:

Operators Evaluation Associativity


unary+,unary- First
*, /, % Next
+. - Last

For example:
(a) x * y * z + a / b – c * d can be write as...(b)
(b) (x * y * z ) + (a / b) – (c * d)

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Additional Notes:

Example

int a, b, c, d, e;
a=10, b=20, c=15, d=8, e=40;

consider the arithmetic expression : a*b/(- c * 31 % 13) * d;

The expression will be evaluated to six steps as shown below:

STEP OPERATOR REDUCE EXPRESSION


1 Unary - a*b/(-15 * 31 % 13) * d
2 * a*b/ (-465 % 13) * d
3 % a*b/(-10) * d
4 * 200 / (-10) * d
5 / -20 * d
6 * -160

Increment and Decrement Operator

1. Increment Operator: ++

The increment operator only use Unary / Operator. The purpose is to increment a variable
by 1 ( i = i + 1).
Also it is used as counter in loop structure. for (i =0; i < 4; i++)
for (i =0; i< 4; i++)

2. Decrement Operator: --

Only uses Unary – Operator. The operator is used to decrement a variable by 1 ( i = i – 1).

int a = 1, b = 2, c= 3;
c--;
printf (“%d %d %d \n”, --a, b--, c);

The table below shows the Syntax examples for the increment(prefix) and incremet(postfix) operator:

++i(prefix) i++(postfix)
In the letter case, the operator comes just in In the former case, we place the operator after
front of the variable. the variable
Incrementing i value Use i value in expression
Use new i value in expression Incrementing i value (before expresion executes)

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Example:

int a = 0, b = 0, c = 0, d =0;
c++;
printf(“ %d %d ”, 4 – d++, d);
printf (“ %d %d %d %d “, ++a, b++, c, d);

Increased Efficiency
value++; value--;
value+=1; value-=1;
value=value+1; value=value-1;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.4.1.2.Assignment Operators

The following table lists the assignment operators supported by the C language

Operator Description Example

= Simple assignment operator. Assigns values from C = A + B will assign the value of
right side operands to left side operand A + B to C

+= Add AND assignment operator. It adds the right C += A is equivalent to C = C + A


operand to the left operand and assign the result
to the left operand.

-= Subtract AND assignment operator. It subtracts C -= A is equivalent to C = C - A


the right operand from the left operand and
assigns the result to the left operand.

*= Multiply AND assignment operator. It multiplies C *= A is equivalent to C = C * A


the right operand with the left operand and
assigns the result to the left operand.

/= Divide AND assignment operator. It divides the left C /= A is equivalent to C = C / A


operand with the right operand and assigns the
result to the left operand.

%= Modulus AND assignment operator. It takes C %= A is equivalent to C = C % A


modulus using two operands and assigns the
result to the left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2. 4.1.3 Unary Operators

In the C family of languages, the following operators are unary:

1. Increment: ++x, x++


2. Decrement: −−x, x−−
3. Address: &x
4. Indirection: *x
5. Positive: +x
6. Negative: −x
7. Ones' complement: ~x
8. Logical negation: !x
9. Sizeof: sizeof x, sizeof(type-name)
10. Cast: (type-name) cast-expression

2. 4.1.4 Relational and Equality Operators

The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then

Operator Description Example

Checks if the values of two operands are equal or not. If yes,


== (A == B) is not true.
then the condition becomes true.

Checks if the values of two operands are equal or not. If the


!= (A! = B) is true.
values are not equal, then the condition becomes true.

Checks if the value of left operand is greater than the value of


> (A > B) is not true.
right operand. If yes, then the condition becomes true.

Checks if the value of left operand is less than the value of right
< (A < B) is true.
operand. If yes, then the condition becomes true.

Checks if the value of left operand is greater than or equal to the


>= (A >= B) is not true.
value of right operand. If yes, then the condition becomes true.

Checks if the value of left operand is less than or equal to the


<= (A <= B) is true.
value of right operand. If yes, then the condition becomes true.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2. 4.1.5 Logical Operators

Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then

Operator Description Example

Called Logical AND operator. If both the operands are non-


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

Called Logical OR Operator. If any of the two operands is


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

Called Logical NOT Operator. It is used to reverse the logical


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

Logical operator table in c;


✓ 1 – on / yes / true
✓ 0 – off / no / false

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.4.2 Operators Precedence in C

Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.4.3 Exercise 2: Expression and Operator

1. Write a C statement to accomplish each of the following task.


a) Declare variable sum and x of type int.
b) Initialize variable x to 1.
c) Initialize variable sum to 0.
d) Add variable x to variable sum and assign the result to variable sum.
e) Print “ The sum is.” Followed by the value of variable sum.

2. If a is 4, b is 3.8, and c is 2, what is the value of this expression?

(int)b+a*c

3. Assume that n and d represent positive integers. Write a more concise expression that is equivalent to

n-n/d*d

4. What does the following function do ?

Void nonsense (void)


{
printf(“*****\n”);
printf(“* *\n”);
printf(“*****\n);
}

5. What does the following main function do ?

int main(void)
{
nonsense();
nonsense();
nonsense();
return (0);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2.4.2 Tutorial 3: Expression and Operator

*Save as in C:\Librararies\Documents\Programming C\Tutorial3\

1. Exercise Modulus Operator

/*Operator % is called the remainder (or modulus) operator. Its operands must be
integer quantities. It calculates the remainder of the division of its first operand by its
second operand */

#include<stdio.h>
void main ()
{
int num;
int balance;

printf ("Enter digit number: ");


scanf ("%d”, &num);
balance = num % 2;
printf ("%d %% 2 = %d “, num, balance);
}

2. Exercise Unary Prefix Operator

/*Arithmetic Operator – Unary prefix


The unary operator operates on a single variable or constant statement.
Unary operators require only one operand and consist the symbols +, -, ++ or --
*/

#include<stdio.h>
void main ()
{
int a;
a=1;

printf ("%d\n”, ++a);

/* ++a (prefix). In the latter case, the operator comes just in front of the
variable. Incrementing a value. Use new a value in expression
Ex: 1 + 1 = a so a = 2 */

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3. Exercise Unary Postfix Operator

/* Arithmetic Operator - Unary a++ (postfix). In the former case, we place the operator
after the variable. Use a value in expression. Incrementing a value (before expression
executes). */

#include<stdio.h>

void main ()
{
int a;
a=1;
printf ("%d\n”, a++);

//use the original value


//original value is 1
}

4. Exercise Relational and Equality Operator

/* Relational and Equality Operator


< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to

The C relational and equality operators give a result of 1 for true and 0 for false */

#include<stdio.h>

void main ()
{
int a=10, b=3;

if(a==b)
printf("true");
else
printf("false");

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5. Exercise and Operator 1

/* Logic operator AND - symbol &&


true && true = true
true && false = false
false && true = false
false && false = false
*/

#include<stdio.h>

void main ()
{int a=2, b=3;
if((a<b) && (b>a))
printf("true");
else
printf("false");
}

6. Exercise and Operator 2

/* Logic operator AND - symbol &&


true && true = true
true && false = false
false && true = false
false && false = false
*/

#include<stdio.h>

void main ()
{int i=7;
float f=5.5;
char c='w';

if((i>=6) &&(c=='w'))
printf("true");
else
printf("false");
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

7. Exercise and Operator 3

/* Logic operator AND - symbol &&


true && true = true
true && false = false
false && true = false
false && false = false
*/

#include<stdio.h>

void main ()
{int i=7;
float f=5.5;
char c='w';

if((f<11) &&(i>100))
printf("true");
else
printf("false");
}

8. Exercise or Operator 1

/*Logic operator OR (||)


true || true = true
true || false = true
false || true = true
false || false = false
*/

#include<stdio.h>
void main ()
{
char sex;

printf ("Enter your sex (L/P): ");


scanf ("%c”, &sex);

switch (sex)
{
case 'L': case 'l':

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

printf ("\nHave a nice day, Sir");


case 'P': case 'p':
printf ("\nHave a nice day, Madam");
default:
printf ("Gender does not exist");
}
}

9. Exercise or Operator 2

/*Logic operator OR (||)


true || false = true
true || false = true
false || true = true
false || false = false
*/

#include<stdio.h>

void main ()
{int i=7;
float f=5.5;
char c='w';

if((i>=6) ||(c==119))
printf("true");
else
printf("false");
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

10. Exercise or Operator 3

/*Logic operator OR (||)


true || true = true
true || false = true
false || true = true
false || false = false
*/

#include<stdio.h>

void main ()
{int i=7;
float f=5.5;
char c='w';

if ((c! ='p’) ||((i+f) <=10))


printf("true");
else
printf("false");
}

11. Exercise Precedence Rules

/*The precedence rules


1. ()
2. *, /, %
3. +, -
*/

#include<stdio.h>

void main ()
{
printf ("%d\n", 5+2*6-4/2);
printf ("%d\n", 3*4/2+3-1);

printf ("%d\n", 5+2*(6-4)/2);


printf ("%d\n", 3*4/2+(3-1));
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3. Problem Solving in Programming

Solving problems is the core of computer science.


Programmers must first understand how a human solves a problem, then understand how to
translate this "algorithm" into something a computer can do, and finally how to "write" the
specific syntax (required by a computer) to get the job done.
It is sometimes the case that a machine will solve a problem in a completely different way than a
human.

3.1 Programming Steps

Problem-Solving Phase

1. Program Analysis and Define What solution


Clarification specification problem must do

Develop logical Verify (Follow


General sequence of steps - by
2. Program Design solution steps to solve hand)
(algorithm) problem

3. Program Code Translate


(program) algorithm to
code

Check
computed
4. Program Test
results
manually

Document 6
5. Program
programming
Documentation
steps

Modify to meet
changed
6. Maintenance requirements or
to correct errors

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

● ● ●

Five Phases of Programming


1. State the problem clearly.

2. Describe the input and output information.

3. Work the problem by hand (or with a calculator) for a specific set of data.

4. Develop a solution that is general in nature.

5. Test the solution with a variety of data sets.

● ● ●

3.2 Algorithm
In programming, algorithm is the set of well-defined instruction in sequence to solve a program. An
algorithm should always have a clear stopping point.

Qualities of a good algorithm

1. Inputs and outputs should be defined precisely.


2. Each step-in algorithm should be clear and unambiguous.
3. Algorithm should be most effective among many different ways to solve a problem.
4. An algorithm shouldn't have computer code. Instead, the algorithm should be written in such a
way that, it can be used in similar programming languages.

Method Algorithm

Algorithm

Pseudocode Flowchart

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3.2.1 Defining Pseudocode

Pseudocode is a simple way of writing programming code in English.


Pseudocode is not actual programming language.
It uses short phrases to write code for programs before you actually create it in a specific
language.
Once you know what the program is about and how it will function, then you can use
pseudocode to create statements to achieve the required results for your program.

Understanding Pseudocode
Pseudocode makes creating programs easier.
Programs can be complex and long; preparation is the key.
For years, flowcharts were used to map out programs before writing one line of code in a
language.
However, they were difficult to modify and with the advancement of programming languages, it
was difficult to display all parts of a program with a flowchart.
It is challenging to find a mistake without understanding the complete flow of a program.
That is where pseudocode becomes more appealing.
To use pseudocode, all you do is write what you want your program to say in English.
Pseudocode allows you to translate your statements into any language because there are no
special commands and it is not standardized.
Writing out programs before you code can enable you to better organize and see where you
may have left out needed parts in your programs.
All you have to do is write it out in your own words in short statements. Let's look at some
examples.

Examples of Pseudocode
Let's review an example of pseudocode to create a program to add 2 numbers together and
then display the result.
1. Step 1 - Describe the input, output information and formula
Input: 2 numbers
Output: Result sum of two numbers
Formula: Sum = A + B

2. Step 2 - Develop logical sequence of steps to solve problem

1. Start Program
2. Enter two numbers, A, B
3. Add the numbers together
4. Print Sum
5. End Program

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Now, let's look at a few more simple examples of pseudocode. Here is a pseudocode
to compute the area of a rectangle:
1. Step 1 - Describe the input, output information and formula
Input: 2 numbers, length and width
Output: Result multiply of length and width
Proses: area = l* w

2. Step 2 - Develop logical sequence of steps to solve problem

1. Start Program
2. Get the length, l, and width, w
3. Compute the area = l*w
4. Display the area
5. End Program

● ● ●

Remember;
Writing basic pseudocode is not like writing an actual coding language.
It cannot be compiled or run like a regular program.
Pseudocode can be written how you want.
But some companies use specific pseudocode syntax to keep everyone in the
company on the same page.
Syntax is a set of rules on how to use and organize statements in a programming
language.
By adhering to specific syntax, everyone in the company can read and understand
the flow of a program.
This becomes cost effective and there is less time spent finding and correcting
errors.

● ● ●

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3.2.2 Flowchart in Programming

Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing program


and explaining program to others.

Symbols Used in Flowchart

Different symbols are used for different states in flowchart, for example: Input/Output and decision
making has different symbols. The table below describes all the symbols that are used in making
flowchart

Symbol Purpose Description


Flow line Used to indicate the flow of logic by connecting
symbols.
Terminal (Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Processing Used for airthmetic operations and data-


manipulations.

Desicion Used to represent the operation in which there are


two alternatives, true and false.

On-page Connector Used to join different flowline

Off-page Connector Used to connect flowchart portion on different


page.

Predefined Process/Function Used to represent a group of statements


performing one processing task.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Examples of flowcharts in programming


Let's review an example of flowchart to create a program to add 2 numbers together and then
display the result.
1. Step 1 - Describe the input, output information and formula
Input: 2 numbers
Output: Result sum of two numbers
Proses: Sum = A + B

2. Step 2 - Develop logical sequence of steps to solve problem

3.3 Exercise 2: Algorithm

Define the pseudocode and flowchart of a program where the user supplies three positive numbers
and the program returns the sum, average and root-mean-square of the values. Write the
corresponding algorithm.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4. Control Structures

Control Statements

Conditional Statement Looping Statement Jumping Statement

1. if statement
2. if else statement
1. for loop 1. break statement
3. nested if else
2. while loop 2. continue statement
4. else if construct
3. do while loop 3. goto statement
5. switch statement

A statement that is used to control the flow of execution in a program is called control structure.
It combines instruction into logical unit. Logical unit has one entry point and one exit point.

Types of control structures


1. Sequence
2. Selection
3. Repetition

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.1 Sequence:

Statements are executed in a specified order. No statement is skipped and no statement


is executed more than once.
Flowchart

For Example:

#include<stdio.h>

void main ()
int a;

{
int a=5;
printf (“Square of a = %d”,a);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.2 Selection

It selects a statement to execute on the basis of condition.


Statement is executed when the condition is true and ignored when it is false e.g if,
if else, switch structures.
Flowchart

For Example

#include<stdio.h>
#include<conio.h>

void main ()
{
int y;
clrscr ();

printf ("Enter a year:");


scanf ("%d”, &y);

if (y % 4==0)
printf ("%d is a leap year.”, y);
else
printf ("%d is not a leap year.”. y)

getch ();
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.2.1 “if”, “else” and “nested if” Decision Control Statements in C:

In decision control statements (if-else and nested if), group of statements are executed when condition
is true. If condition is false, then else part statements are executed.

There are 3 types of decision-making control statements in C language. They are,


1. if statements
2. if else statements
3. nested if statements

Syntax for each C decision control statements are given in below table with description.

Decision control statements Syntax/Description


Syntax:
if (condition)
{ Statements;}

if Description:
In these types of statements, if condition is true, then
respective block of code is executed.

Syntax:
if (condition)
{ Statement1; Statement2;}
else
{ Statement3; Statement4;}
if…else
Description:
In these type of statements, group of statements are
executed when condition is true. If condition is false, then
else part statements are executed.

Syntax:
if (condition1)
{Statement1;}
else
if(condition2)
{ Statement2;}
nested if else
Statement 3;
Description:
If condition 1 is false, then condition 2 is checked and
statements are executed if it is true. If condition 2 also gets
failure, then else part is executed.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.2.1.1 Example Program for “if” Statement in C:

In “if” control statement, respective block of code is executed when condition is true.

1 int main ()
2{
3 int m=40, n=40;
4 if (m == n)
5 {
6 printf ("m and n are equal");
7 }
8}
Output:
m and n are equal

4.2.1.2 Example Program for “if else” Statement in C:

In C if else control statement, group of statements are executed when condition is true. If condition is
false, then else part statements are executed.

1 #include <stdio.h>
2 int main ()
3 {
4 int m=40, n=20;
5 if (m == n)
6 {
7 printf ("m and n are equal");
8 }
9 else
10 {
11 printf ("m and n are not equal");
12 }
13
14 }
Output:
m and n are not equal

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.2.1.3 Example Program for Nested if Statement in C:

In “nested if” control statement, if condition 1 is false, then condition 2 is checked and
statements are executed if it is true.
If condition 2 also gets failure, then else part is executed.

1
#include <stdio.h>
2
int main ()
3
{
4
int m=40, n=20;
5
if (m>n)
6
printf ("m is greater than n");
7
else if(m<n)
8
printf ("m is less than n");
9
else
10
printf ("m is equal to n");
11
}
12

Output:
m is greater than n

4.2.2 Switch Statement

A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each switch case.
Syntax
The syntax for a switch statement in C programming language is as follows −
switch(expression)
{

case constant-expression: statement(s);


break; /* optional */
case constant-expression: statement(s);
break; /* optional */

/* you can have any number of case statements */


Default : /* Optional */
statement(s);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

The following rules apply to a switch statement: -


1. The expression used in a switch statement must have an integral or enumerated type, or be of a
class type in which the class has a single conversion function to an integral or enumerated type.
2. You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
3. The constant-expression for a case must be the same data type as the variable in the switch, and
it must be a constant or a literal.
4. When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
5. When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
6. Not every case needs to contain a break. If no break appears, the flow of control will fall through
to subsequent cases until a break is reached.
7. A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
Flow Diagram

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Example
#include <stdio.h>

int main ()
{

/* local variable definition */


char grade = 'B';

switch(grade)
{
case 'A’: printf ("Excellent! \n”); break;
case 'B’: case 'C’: printf ("Well done\n”); break;
case 'D’: printf ("You passed\n”); break;
case 'F’: printf ("Better try again\n”); break;
default: printf ("Invalid grade\n”);
}

printf ("Your grade is %c\n", grade);

return 0;
}

When the above code is compiled and executed, it produces the following result −

Well done
Your grade is B

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.2.3 Tutorial 4: Control /Conditional Statements


*Save as in C:\Librararies\Documents\Programming C\Tutorial4\

1. if statement

//if statement

#include<stdio.h>
void main ()
{
int num;

printf ("Enter a number from 1-20: ");


scanf ("%d”, &num);

if((num>=1) &&(num<=10))
printf ("%d is less than or equal to 10.\n”, num);

if((num>10) &&(num<=20))
printf ("%d greater than or equal to 20.\n", num);

if(num>20)
printf ("Out of Range.");
}

2. if selection strucutre

//if selection structure

#include<stdio.h>
void main ()
{
float nom1, nom2;

printf ("PLEASE INPUT 2 NUMBER.\n");


printf ("First Number: ");
scanf ("%f", &nom1);

printf ("Second Number: ");


scanf ("%f", &nom2);

if(nom1==nom2)
printf ("\n%.1f is equal to %.1f", nom1, nom2);

if (nom1! =nom2)
printf ("\n%.1f is not equal to %.1f", nom1, nom2);

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

if(nom1<nom2)
printf ("\n%.1f is less than %.1f", nom1, nom2);

if(nom1<=nom2)
printf ("\n%.1f is less than or equal to %.1f", nom1, nom2);

if(nom1>nom2)
printf ("\n%.1f is greater than %.1f", nom1, nom2);

if(nom1>=nom2)
printf ("\n%.1f is greater than or equal to %.1f", nom1, nom2);
}

3. if …. else statement
// if...else statement

#include<stdio.h>
void main ()
{
int num;

printf ("Enter a number from 1-20: ");


scanf ("%d”, &num);

if(num<=10)
printf ("%d less than or equal to 10.\n”, num);
else
printf ("%d greater than or equal to 20.\n", num);
}

4. Nested if statement

#include<stdio.h>

int main ()
{
float fuel;

printf ("Enter fuel");


scanf (“%f", &fuel);

printf (" First with braces");

if (fuel < 0.75)


{
if (fuel < 0.25)

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

printf ("fuel very low. Caution! \n");


}
else
{
printf ("fuel over ¾ don't stop now! \n");
}

printf ("Without braces:\n");

if (fuel < 0.75)


if (fuel < 0.25)
printf ("fuel very low. Caution! \n");

else

printf ("fuel over ¾ don't stop now! \n");

return 0;
}

5. if…. else statement

#include <stdio.h>

void main ()
{
int j;
char i;

printf (“Enter 1 character or number");


scanf ("%c", &i);

if (i== 0)
printf (“1 is true");

else
if((i=='a'||i=='b’) &&(i=='b'||i=='a'))
printf ("a or b");

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6. Odd or even numbers

//odd or even numbers

#include<stdio.h>

void main ()
{
int number;
int num;

printf ("please enter a number from 1-10: ");


scanf ("%d”, &number);

num= number %2;

if (num == 1)
printf ("%d, is an odd number.\n”, number);

else
printf ("%d, is an even number.\n”, number);

7. This program to recognize odd or even number

/*this program to recognise odd or even number*/

#include <stdio.h>
void main ()
{ int num, number;

printf ("enter a number from 1-10:");


scanf ("%d”, &num);

if (num > 10)


printf ("out of range\n");
else
{
number = num % 2;

if(number==1)
printf ("%d an odd number.\n”, num);

else
printf ("%d an even number.\n”, num);
}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

8. Nested if …else if statments

//nested if...else if statements

#include<stdio.h>

void main ()
{
int num, balance;

printf ("Enter a number from 1-20: ");


scanf ("%d”, &num);

if(num<=10)
{ printf ("%d less than or equal to 10.\n”, num);
balance = num % 2;
{
if(balance==1)
printf ("%d is an odd number", num);
else
printf ("%d is an even number", num);
}
}
else if(num<=20)
{
printf ("%d smaller than or equal to 20.\n", num);
balance = num % 2;
{
if(balance==1)
printf ("%d is an odd number", num);
else
printf ("%d is an even number", num);
}
}
else
printf ("Out of range.");
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

9. switch …case statement

/*swicth...Case Statement */

#include<stdio.h>

void main ()
{
char greeting;

printf ("\nA. Selamat Hari Raya\nB. Happy Deepavali \nC. Kong Xi Fa Choi \n");
printf ("Enter the number of your desired greeting: ");
scanf ("%c", &greeting);

switch (greeting)
{
case 'A': case 'a':
printf ("Selamat Hari Raya\n");
break;
case 'B': case 'b':
printf ("Happy Deepavali\n");
break;
case 'C': case 'c':
printf ("Kong Xi Fa Choi\n");
break;
default: printf ("Error number of greeting");
break;
}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.3 Repetition / Looping

You may encounter situations, when a block of code needs to be executed several number of
times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
Given below is the general form of a loop statement in most of the programming languages −

C programming language provides the following types of loops to handle looping requirements.

No Loop Type & Description


while loop
1 Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
for loop
2 Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
do...while loop
3 It is more like a while statement, except that it tests the condition at the end of the loop
body.
nested loops
4
You can use one or more loops inside any other while, for, or do..while loop.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3.4.1 while loop

A while loop in C programming repeatedly executes a target statement as long as a given


condition is true.
Syntax
The syntax of a while loop in C programming language is –

While (condition)
{
Statement(s);
}

Here, statement(s) 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.
Flow Diagram

Here, the key point to note is that 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.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Example
#include<stdio.h>

int main ()
{
/*local variable definition*/
int a= 10;

/*while loop execution*/


While(a<20)
{
printf (“Value of a: %d\n”, a);
a++;
}
return 0;
}

When the above code is compiled and executed, it produces the following result –

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

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.3.1 for loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is –
for (initialize; condition; increment/decrement)
{
Statement(s);
}

Here is the flow of control in a 'for' loop −


The initalize 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.
Flow Diagram

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Example

#include<stdio.h>

int main ()
{
/*local variable definition*/
int a= 10;

/*for loop execution*/


for (a = 10; a < 20; a ++)
{
printf (“Value of a: %d\n”, a);
}
return 0;
}
When the above code is compiled and executed, it produces the following result –

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

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.3.2 do...while loop

Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while 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.
Syntax
The syntax of a do...while loop in C programming language is –

do
{
Statement(s);
} while (condition);

Notice that the conditional expression appears at the end of the loop, so the statement(s) 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(s) in the
loop executes again. This process repeats until the given condition becomes false.
Flow Diagram

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Example

#include<stdio.h>

int main ()
{
/*local variable definition*/
int a= 10;

/*for loop execution*/


do
{
printf (“Value of a:%d\n”,a);
a = a + 1;
} while (a < 20)

return 0;
}

When the above code is compiled and executed, it produces the following result −

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

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.3.3 nested loop

C programming allows using one loop inside another loop. The following section shows a few
examples to illustrate the concept.

4.3.4.1 Nested for loop

The syntax for a nested for loop statement in C is as follows –

for (initialize; condition; increment)


{
for (initialize; condition; increment)
{
Statement(s);
}
Statement(s);
}

C program to print patterns of numbers and stars

These program prints various different patterns of numbers and stars.


These codes illustrate how to create various patterns using c programming.
Most of these c programs involve usage of nested loops and space.
A pattern of numbers, star or characters is a way of arranging these in some logical
manner or they may form a sequence.
Some of these patterns are triangles which have special importance in mathematics.
Some patterns are symmetrical while other is not.
Please see the complete page and look at comments for many different patterns.

*
***
*****
*******
*********

We have shown five rows above, in the program you will be asked to enter the numbers
of rows you want to print in the pyramid of stars.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

C programming code

#include <stdio.h>

int main ()
{
int row, c, n, temp;

printf ("Enter the number of rows in pyramid of stars you wish to see ");
scanf ("%d”, &n);

temp = n;

for (row = 1; row <= n; row++)


{
for (c = 1; c < temp; c++)
printf (" ");

temp--;

for (c = 1; c <= 2*row - 1; c++)


printf ("*");

printf("\n");
}

return 0;
}

For more patterns or shapes on numbers and characters see comments below and also
see codes on following pages:
Floyd triangle
Pascal triangle

Consider the pattern


*
**
***
****
*****

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

to print above pattern, see the code below:

#include <stdio.h>

int main ()
{
int n, c, k;

printf ("Enter number of rows\n");


scanf ("%d”, &n);

for (c = 1; c <= n; c++)


{
for (k = 1; k <= c; k++)
printf ("*");

printf("\n");
}

return 0;
}

Using these examples, you are in a better position to create your desired pattern for
yourself.
Creating a pattern involves how to use nested loops properly; some pattern may involve
alphabets or other special characters.
Key aspect is knowing how the characters in pattern changes.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

C pattern programs
Pattern:

*
*A*
*A*A*
*A*A*A*

C pattern program of stars and alphabets:

#include<stdio.h>

main ()
{
int n, c, k, space, count = 1;

printf ("Enter number of rows\n");


scanf ("%d”, &n);

space = n;

for (c = 1; c <= n; c++)


{
for (k = 1; k < space; k++)
printf (" ");

for (k = 1; k <= c; k++)


{
printf ("*");

if (c > 1 && count < c)


{
printf("A");
count++;
}
}

printf("\n");
space--;
count = 1;
}
return 0;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Pattern:
1
232
34543
4567654
567898765
C program:
#include<stdio.h>
main ()
{
int n, c, d, num = 1, space;

scanf ("%d”, &n);

space = n - 1;

for (d = 1; d <= n; d++)


{
num = d;

for (c = 1; c <= space; c++)


printf(" ");

space--;

for (c = 1; c <= d; c++)


{
printf ("%d", num);
num++;
}
num--;
num--;
for (c = 1; c < d; c++)
{
printf ("%d", num);
num--;
}
printf("\n");

}
return 0;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.3.4.2 Nested while loop

The syntax for a nested while loop statement in C programming language is as follows –

while (condition)
{
While(condition)
{
Statement(s);
}
Statement(s);
}

Flowchart of Nested while loop

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Example of Nested while loop


C program to print the number pattern.

1
12
123
1234
12345

#include <stdio.h>
int main ()
{
int i=1, j;
while (i <= 5)
{
j=1;
while (j <= i)
{
printf ("%d “, j);
j++;
}
printf("\n");
i++;
}
return 0;
}

In this program, nested while loop is used to print the pattern.


The outermost loop runs 5 times and for every loop, the innermost loop runs i times which is 1
at first, meaning only "1" is printed, then on the next loop it's 2 numbers printing "1 2" and so
on till 5 iterations of the loop executes, printing "1 2 3 4 5".
This way, the given number pattern is printed.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.3.4.2 Nested do...while loop

The syntax for a nested do...while loop statement in C programming language is as follows –

do
{
do
{
Statement(s);
} while (condition);

Statement(s);
} while(condition);
Example of Nested do-while loop
C program to print the given star pattern.

*
**
***
****
*****

#include <stdio.h>
int main ()
{
int i=1, j;
do
{
j=1;
do
{
printf ("*");
j++;
} while (j <= i);
i++;
printf("\n");
} while (i <= 5);
return 0;
}

In this program, nested do-while loop is used to print the star pattern.
The outermost loop runs 5 times and for every loop, the innermost loop runs i times which is 1
at first, meaning only one "*" is printed, then on the next loop it's 2 printing two stars and so on
till 5 iterations of the loop executes, printing five stars.
This way, the given star pattern is printed.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

A final note on loop nesting is that you can put any type of loop inside any other type of loop.
For example, a 'for' loop can be inside a 'while' loop or vice versa.

4.3.5 Tutorial 5: Repetition/Loop Statements


*Save as in C:\Librararies\Documents\Programming C\Tutorial5\

1. for loop to sum until input number given

#include <stdio.h>
void main ()
{
int i, x, sum = 0;

printf ("Enter number:");


scanf ("%d”, &x);

for (i=5; i<=x; i=i+5)


{
printf (" i = %d", i);
sum += i;
printf ("**%d “, sum);
}

printf ("Sum of the number: %d “, sum);

2. for loop to find out the average of sum number until number given by user

#include <stdio.h>
void main ()
{
int i, x, sum = 0, no = 0;
float average = 0;

printf ("Enter number:");


scanf ("%d”, &x);

for (i=5; i<=x; i=i+5)


{

//printf (" i = %d", i);

sum += i;

// printf ("**%d “, sum);

no++;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

//printf ("no = %d”, no);

average = sum / no;

printf ("\n Average: %.2f “, average);

3. while loop for find out factorial number input by user

#include <stdio.h>
void main ()
{
int i, x;
long factor;

printf ("Enter number:");


scanf ("%d”, &x);
i=x;
factor =x;
while (i! = 1)
{

i= i - 1;
printf (" i = %d", i);
factor = factor * i;
printf ("**%ld “, factor);

printf ("\nfactorial = %ld”, factor);


}

4. for loop to find out factorial that given number

#include <stdio.h>
int main ()
{
int c, n, fact = 1;

printf ("Enter a number to calculate it's factorial\n");


scanf ("%d", &n);

for (c = 1; c <= n; c++)


fact = fact * c;

printf ("Factorial of %d = %d\n", n, fact);

return 0;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5. for loop to find greater number between four numbers given by user

#include <stdio.h>
void main ()
{
int i, no, greater = 0;

for (i=1; i<=4; i++)


{

printf ("Enter number %d:”, i);


scanf ("%d”, &no);

if (greater < no)


greater = no;
else
continue;

}
printf (" The greater number = %d”, greater);

6. for loop to timetable multiplication

// for statement

#include<stdio.h>
void main ()
{
int counter, sum, timetable, multiplication;

printf ("What timetable do you want? ");


scanf ("%d", &timetable);
printf ("Please enter amount multiplication you want? ");
scanf ("%d", &multiplication);

for (counter = 1; counter<=multiplication; counter++)


{
sum = counter * timetable;
printf ("%d x %d = %d\n”, counter, timetable, sum);
}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

7. nested for to calculate averages for several different lists of numbers

// nested for
// calculate averages for several different lists of numbers

#include<stdio.h>
void main ()
{
int n, count, loops, loopcount;
float x, average, sum;

//read in the number of lists


printf ("How many lists? ");
scanf ("%d", &loops);

//outer loop (process each list of numbers


for (loopcount = 1; loopcount<=loops; ++loopcount)
{
//initialize and read in a value for n
sum=0;

printf ("\nList number %d\nHow many numbers? ", loopcount);


scanf ("%d", &n);

//read in the numbers


for (count=1; count<=n; ++count)
{
printf ("x = ");
scanf ("%f", &x);
sum += x;
}//end inner loop

//calculate the average and display the answer


average = sum/n;

printf ("\nThe average is %f \n", average);


}//end outer loop

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

8. nested for
#include<stdio.h>
void main ()
{
int i, j;
for (i=1; i<=4; i++)
{
for (j=1; j<=4; j++)
printf ("%c", '*');
printf("\n");
}
}

9. while loop
// while

#include<stdio.h>
void main ()
{
int x=1;

while(x<5)
{ printf (" %d ", x);
x++;
}
}

10. while loop


// while

#include<stdio.h>
void main ()
{
int counter=1, sum, timetable, multiplication;

printf ("What timetable do you want? ");


scanf ("%d", &timetable);
printf ("Please enter amount multiplication you want? ");
scanf ("%d", &multiplication);

while(counter<=multiplication)
{
sum = counter * timetable;
printf ("%d x %d = %d\n”, counter, timetable, sum);
counter++;
}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.4 Jumping Statement


What are jumping statements?

C language provides us multiple statements through which we can transfer the control
anywhere in the program.
There are basically 3 Jumping statements:
1. break jumping statements.
2. continue jumping statements.
3. goto jumping statements.

1. break jumping statements.


By using this jumping statement, we can terminate the further execution of the program and
transfer the control to the end of any immediate loop.
To do all this we have to specify a break jumping statements whenever we want to terminate
from the loop.
Syntax: break;

NOTE: This jumping statement always used with the control structure like switch case, while, do while,
for loop etc.

NOTE: As break jumping statements ends/terminate loop of one level. so, it is refered to use return or
goto jumping statements, during more deeply nested loops.

Example: Program based upon break jumping statements:


WAP to display the following output:
1 2 3 4 5 . . . . .

#include<stdio.h>
#include<conio.h>
void main ()
{
int i=1;
for (i=1; i<=10; i++)
{
printf (“Enter”, i,”no”);
printf (“\t %d”, i);

if(i>5)
break;
}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2. continue jumping statements.

By using this jumping statement, we can terminate the further execution of the program and
transfer the control to the begining of any immediate loop.
To do all this we have to specify a continue jumping statements whenever we want to terminate
terminate any particular condition and restart/continue our execution.
Syntax: continue;

NOTE: This jumping statement always used with the control structure like switch case, while, do while,
for loop etc.

Example: Program based upon continue jumping statements:


WAP to display the following output:

1 2 3 4 . 6 7 . 9 10

#include<stdio.h>
#include<conio.h>
void main ()
{
int i=1;
for (i=1; i<=10; i++)
{
printf (“Enter”, i,”no”);
printf (“\t %d”, i);
if (i==5 || i==8)
continue;
}
}

3. goto jumping statements.

By using this jumping statement, we can transfer the control from current location to anywhere
in the program.
To do all this we have to specify a label with goto and the controlwill transfer to the location
where the label is specified.
Syntax: goto <label>;

NOTE:
The control will transfer to those label that are part of particular function, where goto is specified.
All those labels will not be included, that are not the part of a particular function where the goto is
specified.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

NOTE:
It is good programming style to use the break, continue and return instead of goto.
However, the break may execute from single loop and goto executes from more deeper loops.

Example: Program based upon continue jumping statements:

WAP to display the square root of a no, if no. is not positive then re enter the input.

#include<stdio.h>
#include<conio.h>

void main ()
{
int i, n;
float s;

start:

printf (“Enter a no.”);


scanf (“%d”, &n);

s=sqrt(n);

if(n<=0)
goto start;

printf (“%f”, s);


}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.5 Tutorial 6: Algorithm


*Save as in C:\Librararies\Documents\Programming C\Tutorial6\

4.5.1 Pengenalan

Tutorila ini bertujuan memberikan pengetahuan tentang pembinaan penyelesaian (developing


solution) dan mendokumenkannya dalam bentuk carta alir atau pseudocode.
Dalam tutorial ini, anda diberikan beberapa contoh jawapan sebagai panduan.
Sila fahamkan contoh-contoh tersebut sebelum mencuba soalan-soalan berilkutnya.
Tips: Untuk menyemak sama ada carta alir atau pseudocode yang anda hasilkan adalah betul,
caranya adalah dengan menjejak (trace) carta alir atau pseudocode tersebut.

4.5.2 Objektif

Selepas membuat tutorial ini anda sepatutnya boleh


1. Membina carta alir atau menulis pseudocode bagi sesuatu masalah
2. Menggunakan struktur-struktur kawalan iaitu sequential, selection dan repetition

4.5.3 Bahagian 1: Sequential Structure

Contoh 1
Tulis pseudocode dan bina sebuah carta alir untuk mengira hasil tambah dua nombor.

Jawapan:
Sebelum membuat carta alir / pseudocode, kenalpasti input, ouput dan proses (formula) terlebih
dahulu.

Langkah 1:

Input : Dua nombor, A dan B


Output : Hasil tambah dua nombor tersebut
Proses : Rumus yang digunakan: Hasil Tambah = A + B

Langkah 2:

Pseudocode
1. Start Program
2. Enter two numbers, A, B
3. Add the numbers together
4. Print Sum
5. End Program

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Flowchart

Start

Declare variables A, B and sum

Read A and B

sum = A + B

Display sum

Stop

Soalan
1. Tulis pseudocode dan bina sebuah carta alir untuk mengira isipadu sebuah bongkah. Kemudian, tulis
dalam C.

2. Tulis pseudocode dan bina sebuah carta alir untuk mengira Jumlah Pinjaman dan Ansuran Bulanan
(montly payment) bagi pinjamanan kenderaan. Kadar Bunga (interest rate) adalah 4% setahun.
Kemudian, tulis dalam C.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4.5.4 Bahagian 2: Selection Structure

Contoh 2
Tulis pseudocode dan bina sebuah carta alir untuk menentukan sama ada suatu nobor itu genap atau
ganjil.

Jawapan:

Langkah 1:

Input : Satu nombor, Num


Output : Genap atau Ganjil
Proses : Gunakan modulus (bahagi baki). Pengujian untuk nombor genap: Num modulus 2 = 0.

Langkah 2:

Pseudocode
1. Mula Program
2. Baca Num
3. Pengujian untuk nombor genap: Num modulus 2 = 0
3.1 Jika benar: papar Num adalah nombor genap
3.2 Jika tidak benar: papar Num adalah nombor ganjil
4. Tamat Program

Flowchart

Start

Read Num

Yes
Is Num modulus 2 = 0 Print “it’s an even number”

No

Print “it’s an odd number”

Stop

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Soalan

3. Tulis pseudocode dan bina carta alir untuk menentukan nombor terbesar daripada dua nombor.

4. Tulis pseudocode dan bina carta alir untuk menentukan sama ada suatu nombor itu merupakan
gandaan 3 atau gandaan 5 atau kedua-duanya.

5. Tulis pseudocode dan bina carta alir untuk mengira Ansuran Bulanan (monthly payment) bagi
pinjaman kenderaan. Jumlah pinjaman dan tahun pinjaman adalah maklumat daripada pengguna.
Kadar pinjaman adalah bergantung kepada bilangan tahun pinjaman, seperti berikut:

Bil Tahun Kadar Bunga


Kurang daripada 5 tahun 2.5% setahun
5 tahun atau lebih 3.0% setahun

6. Sebuah bank menyediakan perkhidmatan pinjaman peribadi (personal loan). Syarat-syarat


permohonan dan pinjaman adalah seperti berikut:

Kadar Bunga
Bil Tahun Kadar Bunga (%) setahun
1 -2 3.0
3 -5 5.0
6 – 10 7.0

Pinjaman Maksimum:
RM 50,000.00

Pinjaman Maksimum:
Gaji Kasar Pemohon mestilah 3 kali ganda lebih besar daripada Ansuran Bulanan
(monthly payment).

Berdasarkan spesifikasi di atas, bina sebuah carta alir untuk membantu pihak bank tersebut bagi
membuat keputusan sama ada meluluskan atau menolak sesuatu permohonan.

4.5.5 Bahagian 3: Repeatition Structure

Contoh 3

Tulis pseudocode dan bina sebuah carta alir untuk mengira hasil tambah semua nombor daripada 1
hingga n. (anggap n >0)

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Jawapan:

Langkah 1:

Input : Nombor n
Output : Hasil tambah nombor-nombor 1 hingga n
Proses : Jumlahkan semua nombor: 1 + 2 + 3 + …. + (n-1) + n

Langkah 2:

Pseudocode Flowchart

1. Mula Program Start


2. Baca n
3. Nilai awalan sum = 0 dan i = 0
4. Mula gelung
4.1 sum tambah dengan nilai i Read n
4.2 tambah nilai i dengan 1
5. Pengujian i sama ada kurang atau sama dengan nilai n
5.1 Jika benar, teruskan gelung Initialize
5.2 Jika tidak, gelung tamat
sum = 0
6. Papar hasil tambah nombor 1 hingga n
7. Tamat Program i=0

sum = sum + 1
i++
Yes

is i less than or
equal to n?

No

Print sum

Stop

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Contoh 4
Tulis pseudocode dan bina sebuah carta alir untuk bilangan nombor ganjil daripada 1 hingga n. (yang
mana, n > 0)

Jawapan:

Langkah 1:

Input : Nombor n
Output : Bilangan nombor ganjil
Proses : Kira bilangannombor ganjil sahaja. Pengujian untuk nombor ganjl: N modulus 2 =1

Langkah 2:

Pseudocode Flowchart

1. Mula Program Start


2. Baca n
3. Mula gelung
3.2 Nilai awalan Oddcount = 0 dan i = 1 Read n
3.2 Pengujian i sama ada nombor ganjil
3.2.1 Jika benar, Oddcount tambah 1
dan i tambah dengan 1 Initialize
3.2.2 Jika tidak, i tambah dengan 1 sum = 0
4. Pengujian i sama ada kurang atau sama dengan nilai n i=0
4.1 Jika benar, teruskan gelung
4.2 Jika tidak, gelung tamat
5. Papar Oddcount
6. Tamat Program is modulus 2 =1?

No Yes
Oddcount = Oddcount + 1
Yes

i++

is i less than or equal to


n?

No

Print

Stop

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Soalan

7. Tulis pseudocode dan bina carta alir untuk mengira hasil tambah semua nombor gandaan 5 daripada
5 hingga n.

Contoh: 5 + 10 +15 + 20……

8. Tulis pseudocode dan bina carta alir untuk mengira purata nombor-nombor gandaan 5 daripada 5
hingga n.

Contoh:
Katakan n =15,
Purata = (5 + 10 + 15)/3 =10

9. Tulis pseudocode dan bina carta alir untuk mengira factorial bagi suatu nombor n. Rumus factorial
adalah seperti berikut:

n! = n x (n-1) x …………x 2 x 1

Contoh:
Katakan n = 5
5! = 5 x 4 x 3 x 2 x 1 = 120

8. Tulis pseudocode dan bina carta alir yang dapat menentukan nombor terbesar daripada n bilangan
nombor yang dimasukkan oleh penggguna.

Contoh:

Katakan pengguna memasukkan bilangan nombor, n = 4. Selepas itu, pengguna memasukkan 4


nombor tersebut, katakan 10,20,10 dan 40. Jadi nombor terbesar adalah 40.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5. Functions

5.1 Type of 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,
✓ Library functions
✓ User-defined functions

Library functions are those functions which are defined by C library, example printf (), scanf
(), strcat () etc. You just need to include appropriate header files to use these functions.
These are already declared and defined in C libraries.
User-defined functions are those functions which are defined by the user at the time of
writing program. Functions are made for code reusability and for saving time and space.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5.2 Benefits of Using Functions


1. It provides modularity to the program.
2. Easy code Reusability. You just have to call the function by its name to use it.
3. In case of large programs with thousands of code lines, debugging and editing becomes easier if you
use functions.

5.3 Function declaration / Function Prototypes

General syntax of function declaration is,


return-type function-name (parameter-list);
Like variable and an array, a function must also be declared before it called.
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately. A function declaration consists of 4
parts.
✓ return-type
✓ function name
✓ parameter list
✓ terminating semicolon

5.4 Function definition Syntax

General syntax of function definition is,


return-type function-name (parameter-list)
{
function-body;
}
The first line return-type function-name(parameter) is known as function header and the statement
within curly braces is called function body.

5.4.1 return-type

return type specifies the type of value (int, float, char, double) that function is expected to return to the
program calling the function.

5.4.2 function-name

function name specifies the name of the function. The function name is any valid C identifier and
therefore must follow the same rule of formation as other variables in C.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5.4.3 parameter-list

The parameter list declares the variables that will receive the data sent by calling program. They often
referred to as formal parameters. These parameters are also used to send values to calling program.

5.4.4 function-body

The function body contains the declarations and the statement(algorithm) necessary for performing the
required task. The body is enclosed within curly braces { } and consists of three parts.

✓ local variable declaration.


✓ function statement that performs the tasks of the function.
✓ a return statement that return the value evaluated by the function.

5.5 Functions and Arguments

Arguments are the values specified during the function call, for which the formal parameters are
declared in the function.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5.5.1 Example: Function that return some value

#include<stdio.h>
#include<conio.h>
int larger (int a, int b); // function declaration

void main ()
{
int i, j, k;
clrscr ();
i=99;
j=112;
k=larger (i, j); // function call
printf ("%d”, k);
getch ();
}

int larger (int a, int b) // function declaration


{
if(a>b)
return a;
else
return b;
}

5.5.2 Nesting of Functions

C language also allows nesting of functions, one function using another function inside its body. We
must be careful while using nested functions, because it may lead to infinte nesting.
function1()

function2();

//statements

If function2 calls function1 inside it, then in this case it will lead to infinite nesting, they will keep calling
each other. Hence, we must be careful.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5.5.3 Recursion

Recursion is a special of nesting functions, where a function calls itself inside it. We must have certain
condition to break out of the recursion, otherwise recursion is infinite.
function1()

function1();

//statements

5.5.3.1 Example: Factorial of a number using Recursion

#include<stdio.h>
#include<conio.h>
int factorial (int x);

void main ()
{
int a, b;
clrscr ();
printf ("Enter no.");
scanf ("%d”, &a);
b=factorial(a);
printf ("%d”, b);
getch ();
}
int factorial (int x)
{
int r=1;
if(x==1) return 1;
else r=x*factorial(x-1);
return r;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5.6 Tutorial 7: Function

*Save as in C:\Librararies\Documents\Programming C\Tutorial7\

1. Exercise 1

a) Tulis satu aturcara untuk melakukan pengiraan terhadap 2 nombor menggunakan operasi tolak,
darab dan bahagi dan mencetak hasil bagi setiap operasi tersebut.
b) Kita akan menggunakan pendekatan aturcara bermodul (pecahkan kepada bbrp. modul).

Modul
Utama

Operasi Operasi Operasi


Tolak Darab Bahagi
Modul 1 Modul 2 Modul 3

//Penggunaan fungsi tanpa parameter


#include<stdio.h>

void fungsi_tolak( ); //prototaip fungsi


void fungsi_darab( ); //prototaip fungsi
void fungsi_bahagi( ); // prototaip fungsi

int x, y;

void main( )
{
x=10;
y=20;

fungsi_tolak( ); Fungsi main ()


fungsi_darab( );
fungsi_bahagi( );
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

//takrif fungsi tolak


void fungsi_tolak( )
{ int f1;

f1=y-x;

printf(“\nHasil tolak %d - %d ialah %d”, y,x,f1);


}

//takrif fungsi darab


void fungsi_darab ( )
{ int f2;

f2=y*x;

printf(“\nHasil darab %d x %d ialah %d”, y,x,f2);


}

//takrif fungsi bahagi


void fungsi_bahagi ( )
{ int f3;

f3=y/x;

printf(“\nHasil darab %d / %d ialah %d”, y,x,f3);


}

2. // Aturcara dgn 2 pembolehubah setempat berbeza tetapi mempunyai nama sama.

#include<stdio.h>

void main( )
{
int baca_umur( );
int umur;

printf(“Berapa umur anda ?”);


scanf(“%d”,&umur);

printf(“\nPembolehubah umur dlm FUNGSI MAIN( ) ialah %3d”, umur);


baca_umur( );
printf(“\nPemblehubah umur dlm FUNGSI MAIN( ) masih %3d\n”,umur);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

int baca_umur( )
{
int umur;

printf(“\nTaipkan semula umur anda : “);


scanf(“%d”, &umur);

printf(“\nPembolehubah umur dalam FUNGSI BACA_UMUR( ) ialah %d”, umur);


return 0;
}

3. /* Penggunaan fungsi (dengan parameter)--- fungsi ialah satu bahagian aturcara untuk melakukan
sesuatu tugas tertentu yang ditulis secara berasingan */

#include<stdio.h>
void cari_gred(int);

void main( )
{
int markah;

printf(“Masukkan markah : ” );
scanf(“%d”, &markah);

cari_gred(markah);
}

void cari_gred (int markah)


{
char gred;

if (markah >= 80)


gred = ‘A’;
else
if (markah >=70)
gred=’B’;
else
if (markah >=60)
gred=’C’;
else
if (markah >=50)
gred=’D’;
else
gred=’E’;

printf(“Anda dapat gred %c” , gred);


}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4. // fungsi dengan parameter

#include<stdio.h>

char cari_gred(int); //prototaip fungsi

void main( )
{
int markah;

printf(“Masukkan markah :”);


scanf(“%d”, &markah);

printf(“Anda dapat gred %c”, cari_gred(markah)); //panggilan fungsi


}

char cari_gred(int markah)


{
char gred;

if (markah >= 80)


gred = ‘A’;
else
if (markah >=70)
gred=’B’;
else
if (markah >=60)
gred=’C’;
else
if (markah >=50)
gred=’D’;
else
gred=’E’;

return gred;
}

5. Operation subtraction, multiply and division 2 numbers that give by user


// Functions

#include<stdio.h>

int func_subtraction(int a, int b); //function prototype


int func_multiplication(int a, int b); //function prototype
float func_division(int a, int b); //function prototype

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

void main()
{
int x,y,answer1;
printf("Please enter first number:");
scanf("%d",&x);
printf("\n Please enter second number:");
scanf("%d",&y);

answer1 = func_subtraction(x,y);
printf("\n%d - %d = %d ", x,y,answer1); //function call
printf("\n%d x %d = %d ", x,y,func_multiplication(x,y)); //function call
printf("\n%d / %d = %.2f ", x,y,func_division(x,y)); //function call
}
int func_subtraction(int no1,int no2)
{ int f1;
f1=no1-no2;
return f1;
}
int func_multiplication(int no1,int no2)
{ int f2;
f2=no1*no2;
return f2;
}
float func_division(int no1,int no2)
{ float f3;
f3=no1/no2;
return f3;
}

6. // Calculate discount

#include<stdio.h>
float ProductDiscount(float, int);

void main()
{ float ProductPrice;
int discount;

printf("Product Price ? RM");


scanf("%f", &ProductPrice);
printf("Discount ? ");
scanf("%d", &discount);

printf("\nPrice of product after %d %% discount : RM%.2f", discount, ProductDiscount


(ProductPrice, discount));
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

float ProductDiscount (float ProductPrice, int discount)


{
float NewPrice;
NewPrice = ProductPrice - ((float) discount / 100 * ProductPrice);
return NewPrice;
}

7. //function with 1 parameter

#include<stdio.h>
char search_grade(int); //function prototype
void comment(char);

void main()
{
int mark;
printf("Enter your mark : ");
scanf("%d", &mark);

printf("You got grade %c", search_grade(mark)); //function call


comment(search_grade(mark));
}

char search_grade(int mark)


{
char grade;
if (mark >= 80)
grade = 'A';
else if (mark >= 70)
grade = 'B';
else if (mark >= 60)
grade = 'C';
else if (mark >= 50)
grade = 'D';
else
grade = 'E';
return grade;
}
void comment(char mark)
{
switch(mark)
{
case 'A': printf("\nExcellent");
break;
case 'B': printf("\nGood");
break;
case 'C': printf("\nSatisfy");

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

break;
case 'D': printf("\nWeak");
break;
case 'E': printf("\nVery Weak");
break;
}
}

8. /* Functions with parameters */

#include<stdio.h>
void Menu_Greeting(int);

void main()
{
int greeting;
printf("Enter the month of your desired greeting: ");
scanf("%d", &greeting);

Menu_Greeting(greeting);
}
void Menu_Greeting(int greeting) //can use any name variable
{
switch (greeting)
{
case 1: printf("Selamat Hari Raya\n");
break;
case 2: printf("Happy Deepavali\n");
break;
case 3: printf("Kong Xi Fa Choi\n");
break;
default: printf("Error number of greeting");
break;
}
}

9. //Functions with parameter

#include<stdio.h>

void find_value(int);

void main()
{
int num;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

printf("Enter a number from 1-20: ");


scanf("%d",&num);

if(num<=10)
{ printf("%d less than or equal to 10.\n",num);
find_value(num);
}
else if(num<=20)
{ printf("%d greater than or equal to 20.\n", num);
find_value(num);
}
else
printf("Out of range.");
}
void find_value(int num)
{ int balance;
balance = num % 2;
{ if(balance==1)
printf("%d is a odd number", num);
else
printf("%d is a even number", num);
}
}

10. //function with 1 parameter

#include<stdio.h>

char search_grade(int); //function prototype

void main()
{
int mark;
printf("Enter your mark : ");
scanf("%d", &mark);

printf("You got grade %c", search_grade(mark)); //function call


}

char search_grade(int mark)


{
char grade;
if (mark >= 80)
grade = 'A';
else if (mark >= 70)
grade = 'B';
else if (mark >= 60)

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

grade = 'C';
else if (mark >= 50)
grade = 'D';
else
grade = 'E';
return grade;
}

11. Function with 2 parameter

#include<stdio.h>

void cetak_segiempat(int, int); // function prototype

void main()
{
int long, width;

printf(“What is the long value :”) ;


scanf(“%d”, &long);

printf(“What is the with value:”);


scanf(“%d”, &width);

cetak_segiempat(long, width); //function call


}

void cetak_segiempat(int long, int width) //function definition


{
int i, j, a;

a=1;

for (i=1; i<=long; i++)


{
printf(“\n”);

for (j=1; j<=width; j++)


printf(“%d”, a);
}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

12. Selepas modify program ini untuk cetak segiempat dan kita kira pula luas segiempat inilah
programnya:

#include<stdio.h>

void cetak_segiempat (int, int);


void kira_luas (int, int); // function prototype

void main()
{
int panjang, lebar;

printf("What is the long value(CM) :") ;


scanf("%d", &panjang);

printf("What is the witdh value(CM):");


scanf("%d", &lebar);

cetak_segiempat(panjang, lebar); //call function


kira_luas(panjang, lebar); //call function

void cetak_segiempat(int panje, int leba)


void cetak_segiempat (int panjang, int lebar)
{
int i, j, a;

a=5;

for (i=1; i<=panjang; i++)


{
printf("\n");
for (j=1; j<=lebar; j++)
printf("%d", a);
}

void kira_luas(int panjang,int lebar)


{

int luas;

luas = panjang*lebar;

printf("\n\nThe area of this rectangle is : %d CM2\n", luas);

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5.7 Tutorial 8: Algorithm for Function

*Save as in C:\Librararies\Documents\Programming C\Tutorial8\

Contoh 1
a) Tulis pseudocode dan bina sebuah carta alir untuk sebuah fungsi (function / subroutine/ module)
yang menerima dua nombor, kemudian mengira hasil tambah kedua-dua nombor tersebut.

b) Seterusnya, tulis pseudocode dan bina carta alir utama (main flowchart) dengan memanggil
fungsi tadi, untuk mengira hasil tambah empat nombor yang dimasukkan oleh pengguna.

Jawapan:

Langkah 1:

Input : 2 nombor, n1 dan n2


Output : Hasil tambah 2 nombor
Proses : Operasi tambah dua nombor dilaksanakan di dalam fungsi (modul)

Langkah 2:

Pseudocode Carta alir (Flowchart)

(a) Main Program Utama (Main)

1. Mula Program Main


2. Baca n1 dan n2 Start
3. Panggil fungsi ADD (call function ADD)
4. Papar hasil tambah 2 nombor tersebut
Read n1 and n2
5. Baca dua nombor baharu n3 dan n4
6. Panggil fungsi ADD (call function ADD)
7. Papar hasil tambah 2 nombor tersebut ADD (n1, n2)
8. Tamat Main Program

Print sum1 result

Read n3 and n4

ADD (n1, n2)

Print sum2 result

Stop

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

(b) ADD Function Program Fungsi (Function)

1. Mula Fungsi ADD


ADD (A,B)
2. Operasi tambah 2 nombor yang
dihantar dari main program
3. Pulangkan hasil tambah kepada Result = A + B
4. program main semula.

Return

Contoh 2

Tulis pseudocode dan bina sebuah carta alir untuk sebuah fungsi (function / subroutine/ module) yang
menerima dua nombor, kemudian mengira hasil tambah kedua-dua nombor tersebut.

Jawapan:

Langkah 1:

Input : 3 nombor, n1, n2 dan n3


Output : Nombor yang paling besar antara 3 nombor
Proses : Operasi pengujian terbesar antara 3 nombor dilaksanakan di dalam fungsi (modul)

Langkah 2:

Pseudocode
Main Program
1. Mula Program Main
2. Baca n1, n2 dan n3
3. Panggil fungsi BIGGEST untuk banding n1 dan n2 (call function BIGGEST)
4. Papar nombor yang terbesar
5. Panggil fungsi BIGGEST untuk banding result perbandingan antara n1 dn n2 dengan n3
pula (call function BIGGEST)
6. Papar nombor yang terbesar
7. Tamat Main Program

BIGGEST Function Program

1. Mula Fungsi BIGGEST


2. Pengujian nombor terbesar antara dua nombor
3. Pulangkan nombor terbesar.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Carta alir (Flowchart)

(a) Fungsi
BIGGEST (x, y)

Yes
is x > y? result = x

No

result = y

Return

(b) Utama Start

Read n1, n2 and n3

BIGGEST (n1, n2)

Print Biggest1

BIGGEST (Biggest1, n3)

Print the latest biggest


number

Stop

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Contoh 3

Tulis pseudocode dan bina sebuah carta alir untuk mengira hasil tambah nombor-nombor daripada a
hingga b (a > 0 dan b> a).

Seterusnya tulis pseudocode dan bina carta alir utama untuk memanggil fungsi tersebutuntuk mengira
hasil tambah esmua nombor daripan 1 hingga n. (nilai n dimasukkan oleh pengguna)

Jawapan:

Langkah 1:

Input : 3 nombor, n1, n2 dan n3


Output : Nombor yang paling besar antara 3 nombor
Proses : Operasi pengujian terbesar antara 3 nombor dilaksanakan di dalam fungsi (modul)

Langkah 2:

Pseudocode
Sum Function Program

1. Mula Fungsi SUM terima nilai 1 sebagai a dan n sebagai b


2. Letak nilai awalan total = 0 dan num = a.
3. Pergiraan hasil tambah total = total + num
4. Penambahan nilai num dengan 1
5. Pengujian num kurang daripada atau sama dengan nilai b
5.1 Jika benar, ulang ke langkah 3 lagi
5.2 Jika tidak, result = total
6. Pulangkan result kepada program utama

Main Program
1. Mula Program Main
2. Baca n
3. Panggil fungsi Sum hantar nilai 1 dan n
4. Papar keputusan
5. Tamat Main Program

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Carta alir (Flowchart)


SUM (a, b)

Fungsi
Initialize:
Total = 0
num = a

total =total + num Yes

num = num + 1

Is num less than


or equeal to b

No

result = total

Return

Utama Start

Read n

SUM (1,n)

Print result

Stop © Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Soalan
1. Tulis pseudocode dan bina carta alir untuk sebuah fungsi yang mengira isipadu sebuah bongkah.
Seterusnya tulis pseudocode dan bina carta alir utama yang memanggil fungsi tersebut untuk
mengira isipadu sebuah tangki. Dimensi –dimensi tangki tersebut (panjang, lebar dan tinggi)
dimasukkan oleh pengguna.

2. Kereta Honda

a) Tulis pseudocode dan bina carta alir sebuah fungsi untuk mengira Harga Kereta
berdasarkan Model Kereta. Model dan harga kereta adalah seperti berikut:
Model Kereta Harga (RM)
Honda Accord 2.0 VTi 14 1000.00
Honda City 1.5 VTEC 85 000.00
Honda Civic 2.0 I-VTEC 122 000.00

b) Tulis pseudocode dan bina carta alir sebuah fungsi untuk mengira Kadar Bunga (interest
rate) berdasarkan bilangan tahun pinjaman. Kadar pinjaman adalah seperti berikut:

Bil Tahun Kadar Bunga (%)


1 -3 2.0
4–5 2.5
6–9 2.7
10 3.0

c) Tulis pseudocode dan bina carta alir utama yang menggunakan kedua-dua carta alir
fungsi di atas untuk mengira Ansuran Bulanan (monthly payment). Input yang perlu
dimasukkan oleh pengguna adalah Model Kereta yang hendak dibeli, downpayment dan
bilangan tahun pinjaman.

3. Tulis pseudocode dan bina sebuah carta alir fungsi untuk mengira factorial suatu nombor, n.

4. Tulis pseudocode dan bina sebuah carta alir untuk mengira bilangan nombor gandaan a
daripada 1 hingga n.

Contoh:
Katakan a = 3 (bermakna nombor ganddan 3
n = 15 (bermakna 1 hingga 15)

Nombor gandaan 3 daripada 1 hingga 15 ialah 3, 6, 9, 12, 15


Maka bilangan nombor = 5

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5.8 Quiz Function

1. State the condition of the statement is true or false.

a) Top-down design and structured programming design determine a program should be separated
into a main module and its related modules.
b) A function can return more than one value.
c) A function prototype requires only the return type of the function, the function name, and the
number, types and the order of the formal parameters.
d) Variables defined within a block have a global scope.

2. State an appropriate function call for each of the following functions.

a. float line (float a)


{
float b;
b = 3 * a – 1;
return (b);
}

b. void height_ball ( int k, int l )


{
int c;
c = sqrt ( k * k + 1 * 1 );
printf(“c=%i \n”, c);
}

3. Write the first line of the function definition, including argument declarations.
a. A function called simple generates and returns a floating-point quantity.
b. A function called peak accepts two integer arguments and returns a integer results.
c. A function called differ accepts a character and returns another character.
d. A function called move accepts long integer and returns a character.
e. A function called reverse accepts a vharacter and returns a long integer.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6. Data Structures

Data
Structures

Arrays Structures

6.1 Arrays

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.

Arrays are of two types:


1. One-dimensional arrays
2. Multidimensional arrays

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.1.1 One-dimensional Arrays

Array declaration, initialization


Example
and accessing
Array declaration syntax: Integer array example:
data_type arr_name [arr_size]; int age [5];
int age [5] = {0, 1, 2, 3, 4};
Array initialization syntax:
data_type arr_name [arr_size] = age [0]; /*0 is accessed*/
(value1, value2, value3,..); age [1]; /*1 is accessed*/
age [2]; /*2 is accessed*/
Array accessing syntax:
arr_name[index];
Character array example:
char str [10];
char str [10] = {‘H’, ‘a’, ‘i’};
(or)
char str [0] = ‘H’;
char str [1] = ‘a’;
char str [2] = ‘i;

str [0]; /*H is accessed*/


str [1]; /*a is accessed*/
str [2]; /*i is accessed*/

6.1.1.1 How to declare an array in C?

data_type array_name[array_size];

For example, float mark [5];

Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5
floating-point values.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.1.1.2 Elements of an Array and How to access them?

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark [0], second element is
mark [1] and so on.

Few key notes:


1. Arrays have 0 as the first index not 1. In this example, mark [0]
2. If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark
[4]
3. Suppose the starting address of mark [0] is 2120d. Then, the next address, a [1], will be 2124d,
address of a [2] will be 2128d and so on. It's because the size of a float is 4 bytes.

6.1.1.3 How to initialize an array in C programming?

It's possible to initialize an array during declaration. For example,

int mark [5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

int mark [] = {19, 10, 8, 17, 9};

Here,

mark [0] is equal to 19


mark [1] is equal to 10
mark [2] is equal to 8
mark [3] is equal to 17
mark [4] is equal to 9

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.1.1.4 How to insert and print array elements?

int mark [5] = {19, 10, 8, 17, 9}

// insert different value to third element


mark [2] = 9;

// take input from the user and insert in third element


scanf ("%d", &mark [2]);

// take input from the user and insert in (i+1) th element


scanf ("%d", &mark[i]);

// print first element of an array


printf ("%d", mark [0]);

// print ith element of an array


printf ("%d", mark[i-1]);

6.1.1.5 Example: C Arrays

// Program to find the average of n (n < 10) numbers using arrays

#include <stdio.h>
int main ()
{
int marks [10], i, n, sum = 0, average;
printf ("Enter n: ");
scanf ("%d", &n);
for (i=0; i<n; ++i)
{
printf ("Enter number%d: “, i+1);
scanf ("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;

printf ("Average marks = %d", average);

printf ("Diplay value in array marks”);


for (i=0; i<n; ++i)
{
printf (" number%d: “, marks[i]);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

return 0;
}
Output

Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

6.1.1.6 Important thing to remember when working with C arrays

Suppose you declared an array of 10 elements. Let's say,

int testArray [10];

You can use the array members from testArray [0] to testArray [9].

If you try to access array elements outside of its bound, let's say testArray [12], the compiler
may not show any error. However, this may cause unexpected output (undefined behavior)

6.1.2 Tutorial 9: Array One Dimensional

*Save as in C:\Librararies\Documents\Programming C\Tutorial9\

1. #include<stdio.h>
#include<conio.h>

main()
{
int x[5]={4, 3, 2, -5, 9};
int total=0, i;

for (i=0; i < 5; i++)


{
printf(“x[%d]=%d\n”, i, x[i] );
total+=x[i];
}

printf(“TOTAL=%d\n”, total );
getch();
return 0;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

}
2. /* this program is to read 10 numbers and get an average */
#include<conio.h>
#include<stdio.h>

main( )
{

clscr();
int x[10], total=0, i;
for (i=1; i <= 10; i++)
{
printf("Insert number %d>>>", i);
scanf("%d", &x[i]);
total+=x[i];
}
printf("TOTAL = %d\n", total);
printf("AVERAGE = %d",total/10);
getch();
return 0;
}

3. // Sum the number in array

#include<stdio.h>
#define MAX 10

void main ()
{
int num [MAX];
int a, total = 0;

for (a=0; a<10; a++)


{
printf ("%d. Enter 10-digit number: ", a+1);
scanf ("%d", &num[a]);
}
//total all number in array
for (a=0; a<10; a++)
total = total + num[a];

printf ("\nElements in array is");


for (a=0; a<10; a++)
printf("\nnum[%d] = %d", a, num[a]);
printf ("\n\nTotal digit in array is %d”, total);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4. #include <stdio.h>
main ()
{
int i, num [5];

// Input data
printf ("Input 5 scores \n");
printf ("Input scores from 0 to 100\n");

for (i=0; i<4; i++)


{
scanf ("%d”, &num[i]);
}

// Show the data


for (i=0; i<4; i++)
{
printf ("score %d = %d\n”, i+1, num [i]);
}

return (0);
}

5. // Array 1 dimensional

#include<stdio.h>

void main ()
{
int mark [6] = {78,98,86,80,75,70};
int i;

for (i=0; i<6; i++)


printf ("Mark student %d [%d] = %d\n", i+1, i, mark[i]);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.1.3 Searching An Array

Array is usually used to store a list of data, for example list of students scores and list of staff
salary.
At times, we want to find out a certain value like the highest score from the list.
Highest and lowest values of the list can be easily accessed by using array, and also for and if
structure.
Example :

/*This program is to get a maximum value from an array */

#include<conio.h>
#include<stdio.h>

void main ()
{
int i, num [10], max;

printf (“Insert 10 numbers\n”);

for (i=0; i<10; i++)


scanf (“%d”, &num[i]);

max=num [10];

for (i=0; i<10; i++)


{
if (num[i] > max)
{
max = num[i];
}
}
printf (“MAXIMUM value is %d\n”, max);
getch ();
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.1.3.1 Tutorial 10: Searching an Array

*Save as in C:\Librararies\Documents\Programming C\Tutorial10\

1. #include<stdio.h>

void SumArray(int [ ]);

void main( )
{
int markah[5];
int i;

for(i=0; i<5; i++)


{
printf ("Enter mark %d ---> ", i+1);
scanf("%d", &markah[i]);
}
SumArray(markah);
}

void SumArray(int markah[ ])


{
int i;
for (i=0; i<5; i++)
printf (" In Array, Mark[%d] %d\n", i, markah[i]);
}

2. //This program is to get the minimum and maximum value from an array.

#include<conio.h>
#include<stdio.h>

void main( )
{
int i, num[10], max, min;

printf("Insert 10 numbers:\n");

for (i=0; i<10; i++)


scanf("%d",&num[i]);

max=num[10];
min=num[10];

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

for(i=0; i<10; i++)


{
if (num[i] > max)
{
max = num[i];
}

if (num[i] < min)


{
min = num[i];
}
}

printf("MAXIMUM value is %d\n", max);


printf("MINUMUM value is %d\n", min);

getch();

3. #include<stdio.h>
#include<conio.h>

void main( )
{
int i, mark[5], j;

// clscr( );

printf("Insert 5 computing students marks:\n");

for (i=0; i<5; i++)


{
scanf("%d",&mark[i]);
}
j=0;
for(i=0; i<5; i++)
{
if (mark[i]>=50)
{
j++;
}
}
printf("\n Total of students passed: %d", j);
getch( );
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

4. // searching for minimum or maximum number

#include<stdio.h>

void main()
{
int num[5];
const n=5;
printf("Enter 5 digit number.\n\n");
for(int a=0; a<n; a++)
{ printf("Number %d : ", a+1);
scanf("%d", &num[a]);
}

//searching maximum number


int max=0;
for(int e=0; e<n; e++)
if(max < num[e])
max = num[e];

printf("\nThe number maximum is %d", max);

6.1.2 Two-dimensional Arrays


The simplest form of multidimensional array is the two-dimensional array.
A two-dimensional array is, in essence, a list of one-dimensional arrays.
To declare a two-dimensional integer array of size [x][y], you would write something as follows −

type arrayName [ x] [ y];

Where type can be any valid C data type and arrayName will be a valid C identifier.
A two-dimensional array can be considered as a table which will have x number of rows and y
number of columns.
A two-dimensional array a, which contains three rows and four columns can be shown as
follows –

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where
'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element
in 'a'.

Array declaration, initialization and accessing Example


Array declaration syntax: Integer array example:
data_type arr_name [num_of_rows] [num_of_column]; int arr [2][2];
int arr [2][2] = {1,2, 3, 4};
Array initialization syntax:
data_type arr_name [2][2] = {{0,0}, {0,1}, {1,0}, {1,1}}; arr [0] [0] = 1;
arr [0] ]1] = 2;
Array accessing syntax: arr [1][0] = 3;
arr_name[index]; arr [1] [1] = 4;

6.1.2.1 Example Program for Two Dimensional Arrays:


Example 1:

1 #include<stdio.h>
2
3 int main ()
4 {
5 int i, j;
6 // declaring and Initializing array
7 int arr [2][2] = {10,20,30,40};
8 /* Above array can be initialized as below also
9 arr [0][0] = 10; // Initializing array
10 arr [0][1] = 20;
11 arr [1][0] = 30;
12 arr [1][1] = 40; */
13 for (i=0; i<2; i++)
14 {
15 for (j=0; j<2; j++)
16 {
17 // Accessing variables
18 printf ("value of arr[%d] [%d]: %d\n”, i, j, arr[i][j]);
19 }
20 }
21 }

Output:
value of arr [0] [0] is 10
value of arr [0] [1] is 20
value of arr [1] [0] is 30
value of arr [1] [1] is 40

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.1.2.2 Tutorial 11: Program for Two Dimensional Arrays:

*Save as in C:\Librararies\Documents\Programming C\Tutorial11\

// Array 2 Dimensional

#include<stdio.h>

void main ()
{ const int a=3, b=2;
int mark[a][b];
int row, column;

printf ("ARRAY 2 DIMENSIONAL\n\n");

for (row=0; row<a; row++)


{ printf("\n");
for (column=0; column<b; column++)
{ printf("mark[%d] [%d] = ", row, column);
scanf ("%d", &mark[row][column]);
}
}
printf("\n");

//print array
for (row=0; row<a; row++)
{ for (column=0; column<b; column++)
printf ("%d\t", mark[row][column]);
printf("\n");
}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.2 Sorting an Array

Many situation in life we need to present a list of data in order.


For example, we might need to sort a list of integers in ascending order.

Sorting an
Array

Bubble Insertion

6.2.1 Bubble Sort


Bubble sort repetitively compares adjacent pairs of elements and swaps if necessary.
Scan the array, swapping adjacent pair of elements if they are not in relative order. This
bubbles up the largest element to the end.
Scan the array again, bubbling up the second largest element.
Repeat until all elements are in order.
The following bubbleSort () method implements bubble sort. It uses a nested loop to repetitively
swap elements and bubble up the largest elements one by one.
Example 1:

1 public static void bubbleSort (int [] data)


2 {
3 for (int i = data. length - 1; i >= 0; i--)
4 {
5 // bubble up
6 for (int j = 0; j <= i - 1; j++)
7 {
8 if (data[j] > data [j + 1])
9 swap (data, j, j + 1);
10 }
11 }
12 }

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

The following tracks the code on an array with elements {38, 27, 43, 3, 9, 82, 10} for three rounds of
bubbling.
1 {38, 27, 43, 3, 9, 82, 10}
2 i: 6
3 {27, 38, 43, 3, 9, 82, 10}, j: 0
4 {27, 38, 43, 3, 9, 82, 10}, j: 1
5 {27, 38, 3, 43, 9, 82, 10}, j: 2
6 {27, 38, 3, 9, 43, 82, 10}, j: 3
7 {27, 38, 3, 9, 43, 82, 10}, j: 4
8 {27, 38, 3, 9, 43, 10, 82}, j: 5
9 i: 5
10 {27, 38, 3, 9, 43, 10, 82}, j: 0
11 {27, 3, 38, 9, 43, 10, 82}, j: 1
12 {27, 3, 9, 38, 43, 10, 82}, j: 2
13 {27, 3, 9, 38, 43, 10, 82}, j: 3
14 {27, 3, 9, 38, 10, 43, 82}, j: 4
15 i: 4
16 {3, 27, 9, 38, 10, 43, 82}, j: 0
17 {3, 9, 27, 38, 10, 43, 82}, j: 1
18 {3, 9, 27, 38, 10, 43, 82}, j: 2
19 {3, 9, 27, 10, 38, 43, 82}, j: 3

Example 2: A bubble sort compares 2 array elements and exchanges values if they are out of order.

Loop 1:
3 2 5 1 4
2 3 5 1 4 /* swap 3 and 2 */
2 3 5 1 4 /* Compare 3 and 5 */
2 3 1 5 4 /* swap 1 and 5 */
2 3 1 4 5 /* swap 5 and 4 */

Loop 2:
2 3 1 4 5 /* swap 2 with 3 */
2 1 3 4 5 /* swap 1 with 3 */
2 1 3 4 5 /* Compare 3 with 4 */

Loop 3:
1 2 3 4 5 /*swap 2 with 1 */
1 2 3 4 5 /*compare 2 with 3 */

Loop 4:
1 2 3 4 5 /* compare 1 with 2 */

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.2.1.1 Tutorial 12 : Bubble Sort

*Save as in C:\Librararies\Documents\Programming C\Tutorial12\

1. #include<conio.h>
#include<stdio.h>
#include<stdlib.h>

void main( )
{
// clscr( );
int nom[10],i,j,temp;

for(i=0;i<10;i++)
{
nom[i]=(rand( )%10); // generate random numbers range 0-10
printf("[%d]=%d\n",i,nom[i]);
}
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(nom[i]>nom[j])
{
temp=nom[i];
nom[i]=nom[j];
nom[j]=temp;
}
}
}
for(i=0;i<10;i++)
{
printf("%d\t",nom[i]);
}
getch();
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2. //susunan nombor secara Isihan Buih(Bubble Sort)


#include<stdio.h>
void main( )
{ int no[5];
int temp;
printf("Masukkan 5 nombor:\n\n");
for(int a=0; a<5; a++)
{
printf("Nombor %d :", a+1);
scanf("%d", &no[a]);
}

// susun secara Isihan Buih


for (int b=0; b<5; b++)
{
for (int c=1; c<5; c++)
if (no[c]<no[c-1])
{
int temp;
temp=no[c];
no[c]=no[c-1];
no[c-1]=temp;
}
}

printf("\nSusunan menaik nombor tersebut ialah: ");

for(int d=0; d<5;d++)


printf("%d\t",no[d]);
}
// modify the program above for sorting descending.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3. Modify
//susunan nombor secara Isihan Buih(Bubble Sort)

#include<stdio.h>
void main()
{
int no[5];
int temp;

printf("Masukkan 5 nombor:\n\n");

for(int a=0; a<5; a++)


{
printf("Nombor %d :", a+1);
scanf("%d", &no[a]);
}

// susun secara Isihan Buih


for (int b=0; b<5; b++)
{
for (int c=1; c<5; c++)
if (no[c]<no[c-1])
{ int temp;
temp=no[c];
no[c]=no[c-1];
no[c-1]=temp;
}
}
printf("\nSusunan menaik nombor tersebut ialah: ");
for(int d=0; d<5;d++)
printf("%d\t",no[d]);

for (int e=0; e<5; e++)


{
for (int f=1; f<5; f++)
if (no[f]>no[f-1])
{ int temp;
temp=no[f];
no[f]=no[f-1];
no[f-1]=temp;
}
}

printf("\nSusunan menurun nombor tersebut ialah: ");

for(int g=0; g<5;g++)


printf("%d\t",no[g]);

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.2.2 Insertion Sort

Insertion sort maintains a sorted sub-array, and repetitively inserts new elements into it. The
process is as following:
Take the first element as a sorted sub-array.
Insert the second element into the sorted sub-array (shift elements if needed).
Insert the third element into the sorted sub-array.
Repeat until all elements are inserted.
The following insertionSort () method implements insertion sort. It uses a nested loop to
repetitively insert elements into the sorted sub-array.

1 public static void insertionSort (int [] arr)


2 {
3 for (int i = 1; i < arr. length; i++)
4 {
5 // a temporary copy of the current element
6 int tmp = arr[i];
7 int j;
8
9 // find the position for insertion
10 for (j = i; j > 0; j--)
11 {
12 if (arr [j - 1] < tmp)
13 break;
14 // shift the sorted part to right
15 arr[j] = arr [j - 1];
16 }
17
18 // insert the current element
19 arr[j] = tmp;
20 }
21 }

The following tracks the code on an array with elements {38, 27, 43, 3, 9, 82, 10}.

1 {38, 27, 43, 3, 9, 82, 10}


2 {27, 38, 43, 3, 9, 82, 10}, i: 1
3 {27, 38, 43, 3, 9, 82, 10}, i: 2
4 {3, 27, 38, 43, 9, 82, 10}, i: 3
5 {3, 9, 27, 38, 43, 82, 10}, i: 4
6 {3, 9, 27, 38, 43, 82, 10}, i: 5
7 {3, 9, 10, 27, 38, 43, 82}, i: 6

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Summary

Bubble sort Insertion sort


Algorithm Scan through the array from The first part of the list is sorted and
left to right, comparing the remainder is unsorted.
adjacent elements. To begin with, all elements are in
Whenever two adjacent the unsorted part.
elements are out of order, Go through the elements in the
swap them. unsorted part sequencially and
Repeat this until the array is insert each into the sorted part by
sorted. searching for it's correct position
with a linear search or a binary
search.
Pros Simple to implement and Fairly easy to implement with a
understand, but not much linear search
more so than several more If a backwards linear search is used,
efficient sorts it is much faster on a partially sorted
Will be very quick on an array
already sorted list

Cons Probably the slowest sort ever On an array, insertion is slow because all
invented the elements after it have to be moved
up.

Notes Don't bother learning this -


sort.
There are other sorts which
are just as easy to implement
and much faster.
Although there are some
time saving modifications
that can be made (e.g.
keeping track of the last swap
in the previous pass, and only
going up to there in the
current pass), they aren't
worth it.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.2.3 Tutorial 13: Multi dimensional Array

*Save as in C:\Librararies\Documents\Programming C\Tutorial13\

Koperasi SMKTS menjual 2 jenis disket iaitu bersaiz: 3 1/2” dan 51/4”. Setiap disket adalah dalam kapasiti:
“single-sided double density”,”double-sided double density”,”single-sided high density” dan “double-
sided high density”.

Harga bagi disket tersebut adalah seperti berikut:

Saiz Double Density High Density


disket Single sided Double sided Single sided Double sided
3” 2.30 2.75 3.20 3.50
5” 1.75 2.10 2.60 2.95

Anda dikehendaki menulis satu aturcara pendek di dalam C bagi memudahkan menyimpan nilai-nilai
harga bagi setiap kategori disket seperti di atas.

Contoh Output:
RM2.30

RM2.75

RM3.20

RM3.50

RM1.75

RM2.10

RM2.10

RM2.60

RM2.95

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.3 Passing Arrays as Function Arguments

If you want to pass a single-dimension array as an argument in a function, you would have to
declare a formal parameter in one of following three ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going to be
received.
Similarly, you can pass multi-dimensional arrays as formal parameters.

6..3.1 Way-1
Formal parameters as a sized array −

void myFunction (int param [10])

6.3.2 Way-3
Formal parameters as an unsized array −

void myFunction (int param [])

6.3.3 Tutorial 14: Passing Arrays

*Save as in C:\Librararies\Documents\Programming C\Tutorial14\

Now, consider the following function, which takes an array as an argument along with another
argument and based on the passed arguments, it returns the average of the numbers passed through
the array as follows –

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

double getAverage (int arr [], int size)


{
int i;
double avg;
double sum = 0;

for (i = 0; i < size; ++i)


{
sum += arr[i];
}
avg = sum / size;
return avg;
}

Now, let us call the above function as follows –

#include <stdio.h>
/* function declaration */
double getAverage (int arr [], int size);

int main ()
{
/* an int array with 5 elements */
int balance [5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */


avg = getAverage (balance, 5);

/* output the returned value */


printf (“Average value is: %f ", avg);

return 0;
}
When the above code is compiled together and executed, it produces the following result −
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C
performs no bounds checking for formal parameters.

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.4 Tutorial 15: Arrays

*Save as in C:\Librararies\Documents\Programming C\Tutorial15\

1. // without Array 1 dimensional

#include<stdio.h>
void main ()
{
int student1, student2, student3, student4, student5, student6;
student1 = 78;
student2 = 98;
student3 = 86;
student4 = 80;
student5 = 75;
student6 = 70;

printf ("Mark student1 = %d\n", student1);


printf ("Mark student2 = %d\n", student2);
printf ("Mark student3 = %d\n", student3);
printf ("Mark student4 = %d\n", student4);
printf ("Mark student5 = %d\n", student5);
printf ("Mark student6 = %d\n", student6);
}

2. // Array 1 dimensional

#include<stdio.h>
void main ()
{
int mark [6] = {78,98,86,80,75,70};
int i;

for (i=0; i<6; i++)


printf ("Mark student %d [%d] = %d\n", i+1, i, mark[i]);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

3. // Array 1 dimensional with parameters

#include<stdio.h>

void SumArray (int []);

void main ()
{
int mark [5];
int i;

for (i=0; i<5; i++)


{ printf ("Enter mark %d: ", i+1);
scanf ("%d", &mark[i]);
}
SumArray(mark);
}
void SumArray (int mark [])
{
int i;
for (i=0; i<5; i++)
printf ("\nIn array, mark[%d] %d", i, mark[i]);
}

4. // Array 1 dimensional

#include<stdio.h>

void main ()
{
int mark [6];
int i;

for (int counter=0; counter < 6; counter++)


{ printf ("Please enter mark student %d: ", counter+1 );
scanf ("%d", &mark[counter]);
}
for (i=0; i<6; i++)
printf ("Mark student %d [%d] = %d\n", i+1,i, mark[i]);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

5. #include <stdio.h>

main () {

int i, num [5];

// Input data
printf ("Input 5 scores \n");
printf ("Input scores from 0 to 100\n");

for (i=0; i<4; i++) {scanf ("%d”, &num[i]);}

// Show the data


for (i=0; i<4; i++) {printf ("score %d = %d\n”, i+1, num [i]);}

return (0);
}

6. // Bubble Sort

#include<stdio.h>

void main ()
{
int num [5];

printf ("Enter 5-digit number. \n\n");


for (int a=0; a<5; a++)
{ printf ("Number %d: ", a+1);
scanf ("%d", &num[a]);
}
//Sorting
for (int b=0; b < (5-1); b++)
{
for (int c=1; c<5; c++)
if (num[c]<num[c-1])
{ int temp;
temp = num[c];
num[c] = num[c-1];
num[c-1] =temp;
}
}

printf ("\nAscending order is ");


for (int d=0; d<5; d++)
printf ("%d “, num[d]);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

7. // Bubble Sort -descending

#include<stdio.h>

void main ()
{
int num [5];

printf ("Enter 5-digit number. \n\n");


for (int a=0; a<5; a++)
{ printf ("Number %d: ", a+1);
scanf ("%d", &num[a]);
}
//Sorting
for (int b=0; b < (5-1); b++)
{
for (int c=1; c<5; c++)
if (num[c]>num[c-1])
{ int temp;
temp = num[c];
num[c] = num[c-1];
num[c-1] =temp;
}
}

printf ("\nAscending order is ");


for (int d=0; d<5; d++)
printf ("%d “, num[d]);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

6.3 Structures

C Structure is a collection of different data types which are grouped together and each element in a C
structure is called member.
If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and memory will be allocated for
each separately.
It is a best practice to initialize a structure to null while declaring, if we don’t assign any values
to structure members.

6.31 Difference between C Variable, C Array and C Structure

A normal C variable can hold only one data of one data type at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types and Data types can be int, char, float,
double and long double etc.

C Structure:
struct student
{
Syntax int a;
char b [10];
}

a = 10;
Example
b = “Hello”;

C Variable:
Syntax: int a;
int Example: a = 20;

Syntax: char b;
char Example: b=’Z’;

C Array:

int Syntax: int a [3];


Example:

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

a [0] = 10;
a [1] = 20;
a [2] = 30;
a [3] = ‘\0’;

Syntax: char b [10];


char Example:
b= “Hello”;

6.3.2 Table Explains Following Concepts in C Structure

1. How to declare a C structure?


2. How to initialize a C structure?
3. How to access the members of a C structure?

Using normal variable

Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};

Example:
struct student
{
int mark;
char name [10];
float average;
};

Declaring structure using normal variable:


struct student report;

Initializing structure using normal variable:


struct student report = {100, “Mani”, 99.5};

Accessing structure members using normal


variable:
report.mark;
report.name;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

report.average;
6.3.3 Example of Structure

Structure is used to represent a record. Suppose you want to store record of Student which consists of
student name, address, roll number and age. You can define a structure to hold this information.

Defining a structure
struct keyword is used to define a structure. struct define a new data type which is a collection of
different type of data.
Syntax:
struct structure_name
{
//Statements
};

Example of Structure
struct Book
{
char name [15];
int price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which consists of three data fields,
namely name, price and pages. These fields are called structure elements or members. Each member
can have different data type, like in this case, name is of char type and price is of int type etc. Book is
the name of the structure and is called structure tag.

Declaring Structure Variables


It is possible to declare variables of a structure, after the structure is defined. Structure variable
declaration is similar to the declaration of variables of any other data types. Structure variables can be
declared in following two ways.

1) Declaring Structure variables separately

struct Student
{
char [20] name;
int age;
int rollno;
};

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

struct Student S1, S2; //declaring variables of Student

2) Declaring Structure Variables with Structure definition

struct Student
{
char [20] name;
int age;
int rollno;
} S1, S2;
Here S1 and S2 are variables of structure Student. However, this approach is not much recommended.

Accessing Structure Members

Structure members can be accessed and assigned values in number of ways. Structure member has no
meaning independently. In order to assign a value to a structure member, the member name must be
linked with the structure variable using dot. operator also called period or member access operator.

struct Book
{
char name [15];
int price;
int pages;
} b1, b2;

b1. price=200; //b1 is variable of Book type and price is member of Book

We can also use scanf () to give values to structure members through terminal.

scanf (" %s ", b1.name);


scanf (" %d ", &b1.price);

Structure Initialization
Like any other data type, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};

struct Patient p1 = {180.75, 73, 23}; //initialization


or
struct patient p1;
p1.height = 180.75; //initialization of each member separately

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

p1.weight = 73;
p1.age = 23;
Array of Structure

We can also declare an array of structure. Each element of the array representing
a structure variable. Example: struct employee emp [5];
The above code defines an array emp of size 5 elements. Each element of array emp is of
type employee

#include<stdio.h>
#include<conio.h>
struct employee
{
char ename [10];
int sal;
};

struct employee emp [5];


int i, j;
void ask ()
{
for (i=0; i<3; i++)
{
printf ("\nEnter %dst employee record\n”, i+1);
printf ("\nEmployee name\t");
scanf ("%s”, emp[i]. ename);
printf ("\nEnter employee salary\t");
scanf ("%d”, &emp[i]. sal);
}
printf ("\nDisplaying Employee record\n");
for (i=0; i<3; i++)
{
printf ("\nEmployee name is %s”, emp[i].ename);
printf ("\nSlary is %d”, emp[i].sal);
}
}
void main ()
{
clrscr ();
ask ();
getch ();
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

Nested Structures

Nesting of structures, is also permitted in C language.

Example:

struct student
{
char [30] name;
int age;
struct address
{
char [50] locality;
char [50] city;
int pincode;
};
};

Structure as function arguments

We can pass a structure as a function argument in similar way as we pass any other variable or array.

Example:

#include<stdio.h>
#include<conio.h>

struct student
{
char name [10];
int roll;
};

void show (struct student st);

void main ()
{
struct student std;

clrscr ();

printf ("\nEnter student record\n");

printf ("\nstudent name\t");


scanf ("%s”, std.name);

printf ("\nEnter student roll\t");


scanf ("%d”, &std.roll);

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

show(std);
getch ();
}

void show (struct student st)


{
printf ("\nstudent name is %s”, st.name);
printf ("\nroll is %d”, st.roll);
}

6.3.4 Tutorial 15: Structure

*Save as in C:\Librararies\Documents\Programming C\Tutorial15\

1. #include<stdio.h>

struct car
{
char maker [40];
char model [40];
int year;
};
Struct car FirstCar= {"Proton", "Perdana", 2000};

int main ()
{

struct car SecondCar;

printf ("%20s%s, %s, %d\n", "First Car:”, FirstCar.maker, FirstCar.model, FirstCar.year);

SecondCar=FirstCar;

printf ("%20s%s, %s, %d\n", "Second Car:”, SecondCar.maker, SecondCar.model,


SecondCar.year);

printf ("%20s is %d bytes\n", "size of FirstCar:”, sizeof (FirstCar));

printf ("%20s is %d bytes\n", "size of SecondCar:”, sizeof (SecondCar));

return 0;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

2. #include<stdio.h>
struct date
{
int day,
int month,
int year;
} Me
main ()
{

Me.day = 5;
Me.month = 1;
Me.year = 1979;

printf ("I was born: %d/%d/%d\n", Me.day, Me.month, Me.year);


return 0;
}

3. #include<stdio.h>
struct card
{
char *face;
char *suit;
}a;

main( )
{
a.face = “Queen”;
a.suit = “Hearts”;

printf(“%s of %s\n”, a.face, a.suit);

return 0;
}

4. #include<stdio.h>

struct plus
{
char colour[10];
float price;
};

struct car
{

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

char maker[40];
char model[40];
int year;
struct plus more;
};
struct car FirstCar = {"Proton", "Perdana", 2005,{"White", 98000.00}};

int main( )
{

printf("First Car:%s, %s, %d, %s, RM%.2f\n", FirstCar.maker, FirstCar.model,


FirstCar.year, FirstCar.more.colour, FirstCar.more.price);

return 0;
}

5. #include <stdio.h>
#define MAX 10

struct book
{
char title[81];
char author[81];
char category[41];
};

int menu(void);

struct book add(void);

void list(book sp[ ],int size);

int main( )
{
struct book library[MAX];

int choice,count = 0;

do
{
choice = menu();
switch (choice)
{
case 0: puts("\nThank You"); break;
case 1: if(count<MAX)
{
library[count]=add();
count++;

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

}
else
puts("Library has reached maximum capacity");
break;
case 2:{
list(library,count);
break;
}
default: puts("Wrong selection.Try again.");
};

}while (choice !=0);


return 0;
}

int menu(void)
{
int choice;

puts("\n<<Main Menu>>");
puts("\t0:exit");
puts("\t1:add a book");
puts("\t2:list all books");

printf ("enter your selection:");


scanf("%d",&choice);

return choice;
}

struct book add(void)


{
struct book temp;

fflush(stdin);

puts("\n << Add Menu >>");

printf("title?");
gets(temp.title);

printf("author?");
gets(temp.author);

printf("category?");
gets(temp.category);

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

return temp;
}

void list(book sp[ ],int size)


{
int i;

putchar('\n');

puts("<<BookList>>");

for (i=0;i<size;++i)

{
printf("%d:%s by %s--%s\n",i+1,sp[i].title, sp[i].author,sp[i].category);
}

//while(cin.get()!='q');
return;
}

6. //Penggunaan struct bertatasusunan(array)

#include<stdio.h>
#include<string.h>

#define BIL 1

// penakrifan struct bersama pengumpukan nilai awalan


struct pekerja
{
char nama[30];
int no_pek;
char gred_gaji[5];
float gaji;
char jawatan[30];
}emp[BIL];

void main( )
{

// input papan kekunci


printf("\nSISTEM REKOD PEKERJA SYARIKAT XYZ\n");

for (int i=0; i<BIL; i++)


{
printf("\nMasukkan rekod pekerja %d\n", i+1);

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

printf("Nama pekerja\t:");
scanf("%s",emp[i].nama);

printf("Gred gaji\t:");
scanf("%s",emp[i].gred_gaji);

printf("Jawatan\t\t:");
scanf("%s",emp[i].jawatan);

printf("No. Pekerja\t:");
scanf("%d", &emp[i].no_pek);

printf("Gaji\t\t:RM");
scanf("%f",&emp[i].gaji);
}

// mencetak maklumat rekod


printf("\n\n****Kandungan Rekod Syarikat XYZ****\n");

for(i=0; i<BIL; i++)


{
printf("\nRekod pekerja %d\n", i+1);
printf("\nNama\t\t:%s\n", emp[i].nama);
printf("No. Pekerja\t:%d\n", emp[i].no_pek);
printf("Gred Gaji\t:%s\n", emp[i].gred_gaji);
printf("Gaji\t\t:RM%.2f\n", emp[i].gaji);
printf("Jawatan\t\t:%s\n", emp[i].jawatan);
}
}

7. /* latihan-→modify aturcara di atas.


1. Tanya berapa rekod mahu dimasukkan
2. Buat kawalan ke atas input
3. Tanya nak papar rekod atau tidak. */

© Nar | Nisrin Ahmad Ramly \(^o^)/


2nd Semester: Programming (C Language) – 3rd Edition 2020

7. References

1. C_How_to_Program_7th_Edition_by_Paul_Dei.pdf
2. https://www.tutorialspoint.com/cprogramming/
3. https://www.w3schools.in/c-tutorial/
4. http://study.com/academy/lesson/pseudocode-definition-examples-quiz.html
5. http://www.programiz.com/article/flowchart-programming
6. http://newb6.u-strasbg.fr/~siebert/pages/teaching/INFO-L2/Exercise_C_L2STUE.pdf
7. http://programmingclangauge.weebly.com/control-structure.html
8. http://www.di.uniba.it/~lanubile/fisica/ch05.pdf
9. http://fresh2refresh.com/c-programming/c-decision-control/
10. https://www.programtopia.net/c-programming/docs/nested-loop
11. http://www.programmingsimplified.com/c-program-print-stars-pyramid
12. http://www.studytonight.com/c/user-defined-functions-in-c.php
13. https://www.programiz.com/c-programming/c-arrays
14. http://fresh2refresh.com/c-programming/c-array/
15. http://www.brucemerry.org.za/manual/algorithms/sorting.html
16. https://www.w3schools.in/c-tutorial/

© Nar | Nisrin Ahmad Ramly \(^o^)/

You might also like