The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

Note and Tutorial C Programming BI v3

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by sekolah-142, 2021-04-09 07:59:47

Module C Programming BI v3

Note and Tutorial C Programming BI v3

Keywords: Module C Programming

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

THE

C PROGRAMMING LANGUAGE

Student Name: __________________________________________

Class : __________________________________________

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

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

Table of Content

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
LibraryFunctions ...................................................................................................................................... 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 2021

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

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
 FlowDiagram ................................................................................................................................. 113
 Example ........................................................................................................................................ 114
4.3.1 for loop............................................................................................................................ 115
 Syntax........................................................................................................................................... 115
 FlowDiagram ................................................................................................................................. 115
 Example ........................................................................................................................................ 116
4.3.2 do...while loop................................................................................................................. 117
 Syntax........................................................................................................................................... 117
 FlowDiagram ................................................................................................................................. 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 2021

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 2021

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 2021

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 2021

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
Machine language makes All operation codes have to
Lowest level of programming fast and efficient use of the be remembered
language computer
All memory addresses have
first programming language It requires no translator to to be remembered
translate the code. It is
Use machine code, binary directly understood by the Code is difficult to edit and
digits (bits) 0 and 1. computer update

The symbol 0 stands for the Code cannot be ported to
absence and the 1 stands for other systems and has to
the presence of an electric be rewritten
pulse.
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 2021

Assembly Code 2GL Object Code
000100110100
LDA A Assembly Language 001000000101
ADD #5 001100110100
STA A -> Assembler -> 010000000011
JMP #3

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

It is easily modified

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

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

3GL

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

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

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

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

4GL

Structure Query Language (SQL)

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

5GL

PROLOG

Features / Characteristics / Description Advantages / Benefit Disadvantages /
Weaknesses
The fifth-generation programming Logic based languages
language or visual programming are able to represent the It can be very difficult to
language is also known as natural real world more design a database that
language accurately accurately represents
relationships
Provides a visual or graphical Prolog is able to derive
interface, called a visual new rules from the Prolog is not best suited
programming environment, for existing rules contained to solving complex
creating source codes within the knowledge arithmetical
base computations
Fifth generation programming
allows people to interact with Prolog programs are not
computers without needing any best suited to the
specialized knowledge current PC architecture
(sequential execution)
People can talk to computers and and are best optimised
the voice recognition systems can on parallel architectures
convert spoken sounds into written (fifth generation
words computers)

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 2021

Summary Generation Programming Language

Generation First Second Third Fourth

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

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

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

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

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 2021

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

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

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 2021
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 2021
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 2021
1.3.4 Compiler VS Interpreter

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

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

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

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 2021

Summary: The C Environment Source file
Edit: (myprog.c)

Create / modify Object file
source code (myprog.obj)

Compile:
Generates machine
instruction

Yes
Error?

No
Link:
Link library files

Yes Object file
Error? (myprog.exe)

No
Execute:
Run the program

No
Yes

Error?

No
Success!

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

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

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 2021

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 2021

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 2021

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 2021

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 2021

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 2021

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

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
scanf () and hexadecimal values onto the output screen
getc () This function is used to read a character, string, numeric data from keyboard.
It reads character from file

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

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

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 2021

Function Description
floor ()
This function returns the nearest integer which is less than or equal to the
round () argument passed to this function.
This function returns the nearest integer value of the float/double/long
ceil () 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
sin () returns the integer value greater than the argument.
cos () This function returns nearest integer value which is greater than or equal to the
cosh () argument passed to this function.
exp () This function is used to calculate sine value.
tan () This function is used to calculate cosine.
tanh () This function is used to calculate hyperbolic cosine.
sinh () This function is used to calculate the exponential “e” to the xth power.
log () This function is used to calculate tangent.
log10 () This function is used to calculate hyperbolic tangent.
sqrt () This function is used to calculate hyperbolic sine.
pow () This function is used to calculates natural logarithm.
trunc () This function is used to calculates base 10 logarithm.
This function is used to find square root of the argument passed to this function.
This is used to find the power of the given number.
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 2021

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 2021

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 2021

}

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 2021

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 2021

}

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 2021

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 ()
getch () This function is used to clear the output screen.
getche ()
It reads character from keyboard
textcolor ()
textbackground () It reads character from keyboard and echoes to
o/p screen
This function is used to change the text color

This function is used to change text background

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

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

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

1 int isalnum (int c)
This function checks whether the passed character is alphanumeric.

2 int isalpha (int c)
This function checks whether the passed character is alphabetic.

3 int iscntrl (int c)
This function checks whether the passed character is control character.

4 int isdigit (int c)
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.

6 int islower (int c)
This function checks whether the passed character is lowercase letter.

7 int isprint (int c)
This function checks whether the passed character is printable.

8 int ispunct (int c)
This function checks whether the passed character is a punctuation character.

9 int isspace (int c)
This function checks whether the passed character is white-space.

10 int isupper (int c)
This function checks whether the passed character is an uppercase letter.

11 int isxdigit (int c)
This function checks whether the passed character is a hexadecimal digit.

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

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

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

No Function & Description

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

2 int toupper (int c)
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 2021

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 2021

Data Qualifiers User- Storage Loop
types defined Classes • for
• signed • typedef • while
• int • unsigned • enum • auto • do
• char • short • extern
• float • long Jump • register Function
• double • goto • static • void
Decision • continue • return
Other • break Derived
• if
• const • else • auto
• volatile • switch • extern
• sizeof • case • register
• default • static

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 2021

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
continue any remaining code in the body of the loop
Goto Used to take the control to the beginning of the loop bypassing the statements inside the
loop
Used to take the control to required place in the program

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

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

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 2021

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 2021

Floating type

Floating types are used to store real numbers.

Size and range of Integer type on 16-bit machine

Type Size(bytes) Range
3.4E-38 to 3.4E+38
Float 4 with six digits of 1.7E-308 to 1.7E+308
double 8prwecitihsiotenn digits of 3.4E-4932 to 1.1E+4932
long double precision10

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
unsigned char 1 -128 to 127

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 2021

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 2021

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 2021

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^)/


Click to View FlipBook Version