You are on page 1of 154

C Programming Language

CSC-110

© BISHWO PRAKASH POKHAREL [1]


C Programming Language

TABLE OF CONTENTS
SYLLABUS ............................................................................................................................................ 5
PROBLEM SOLVING WITH COMPUTER ............................................................................................... 7
1.1 Problem analysis ........................................................................................................................... 8
1.2 Algorithms and Flowchart, ........................................................................................................... 8
1.3 Coding, ........................................................................................................................................ 12
1.4 Compilation and Execution,........................................................................................................ 12
1.5 Computer program and programming language ......................................................................... 12
1.6 Introduction and History of C, .................................................................................................... 15
1.7 Structure of C program, .............................................................................................................. 16
1.8 Debugging, .................................................................................................................................. 18
1.9 Testing and Documentation ........................................................................................................ 18
ELEMENTS OF C .................................................................................................................................. 20
2.1 C Standards( ANSI C and C99), ................................................................................................. 20
2.2 C Character Set, .......................................................................................................................... 21
2.3 C Tokens, Escape sequence, ....................................................................................................... 21
2.4 Delimiters, Variables, Data types ............................................................................................... 22
2.5 Constants/ Literals, ..................................................................................................................... 27
2.6 Expressions, ................................................................................................................................ 29
2.7 C Comments................................................................................................................................ 30
INPUT AND OUTPUT............................................................................................................................ 31
3.1 Conversion specification, ............................................................................................................ 31
3.2 Reading and writing a character,................................................................................................. 31
3.3 I/O operations,............................................................................................................................. 32
3.4 Formatted I/O .............................................................................................................................. 33
OPERATORS AND EXPRESSION ....................................................................................................... 35
4.1 Arithmetic operator, .................................................................................................................... 35
4.2 Relational operator, ..................................................................................................................... 36
4.3 Logical or Boolean operator, ...................................................................................................... 37
4.4 Assignment Operator, ................................................................................................................. 38
4.5 Bitwise operator, ......................................................................................................................... 38
4.6 Increment or Decrement operator, .............................................................................................. 41
4.7 Conditional/Ternary operator...................................................................................................... 42
4.8 Special Operators(sizeof and comma), ....................................................................................... 42
4.9 Operator Precedence and Associativity. ..................................................................................... 43

© BISHWO PRAKASH POKHAREL [2]


C Programming Language

CONTROL STATEMENT ...................................................................................................................... 45


5.1 Sequential Statements ................................................................................................................. 45
5.2 Decision Making and Branching,................................................................................................ 46
5.3 Looping, ...................................................................................................................................... 52
5.4 Exit function,............................................................................................................................... 54
5.5 Break and Continue..................................................................................................................... 54
ARRAYS............................................................................................................................................... 66
6.1 Introduction to Array, ........................................................................................................... 66
6.2 Types of Array (Single Dimensional and Multidimensional), .............................................. 67
6.3 Declaration and Memory Representation of Array, ............................................................. 68
6.4 Initialization of array, ............................................................................................................ 68
6.5 Character Array and Strings, ................................................................................................. 77
6.6 Reading and Writing Strings, ................................................................................................ 78
6.7 Null Character ....................................................................................................................... 81
6.8 String Library Functions ....................................................................................................... 81
FUNCTIONS .......................................................................................................................................... 89
7.1 Library Functions, ....................................................................................................................... 89
7.2 User defined functions, ............................................................................................................... 90
7.3 Function prototype, Function call, and Function Definition, ...................................................... 90
7.4 Nested and Recursive Function,.................................................................................................. 94
7.5 Function Arguments and Return Types, ..................................................................................... 97
7.6 Passing Arrays to Function, ...................................................................................................... 101
7.7 Passing Strings to Function, ...................................................................................................... 107
7.8 Passing Arguments by Value, ................................................................................................... 108
7.9 Passing Arguments by Address,................................................................................................ 108
7.10 Scope visibility and lifetime of a variable, ............................................................................. 109
7.11 Local and Global Variable, ..................................................................................................... 109
STRUCTURE AND UNION .................................................................................................................. 114
8.1 Introduction, .............................................................................................................................. 114
8.2 Array of structure, ..................................................................................................................... 115
8.3 Passing structure to function, .................................................................................................... 119
8.4 Passing array of structure to function, ...................................................................................... 119
8.5 Structure within structure ( Nested Structure), ......................................................................... 120
8.6 Union, ....................................................................................................................................... 121
8.7 Pointer to structure .................................................................................................................... 122

© BISHWO PRAKASH POKHAREL [3]


C Programming Language

POINTERS .......................................................................................................................................... 125


9.1 Introduction, .............................................................................................................................. 125
9.2 The & and * operator, ............................................................................................................... 126
9.3 Declaration of pointer, .............................................................................................................. 126
9.4 Chain of Pointers,...................................................................................................................... 128
9.5 Pointer Arithmetic, .................................................................................................................... 129
9.6 Pointers and Arrays, .................................................................................................................. 130
9.7 Pointers and Character Strings, ................................................................................................. 132
9.8 Array of Pointers, ...................................................................................................................... 133
9.9 Pointers as Function Arguments, .............................................................................................. 134
9.10 Function Returning pointers,................................................................................................... 134
9.11 Dynamic Memory Allocation ................................................................................................. 135
FILE HANDLING IN C......................................................................................................................... 140
10.1 Concept of File,....................................................................................................................... 140
10.2 Opening and closing of File, ................................................................................................... 141
10.3 Input Output Operations in File, ............................................................................................. 142
10.4 Random access in File, ........................................................................................................... 148
10.5 Error Handling in Files ........................................................................................................... 150
INTRODUCTION TO GRAPHICS ........................................................................................................ 152
11.1 Concepts of Graphics, ............................................................................................................. 152
11.2 Graphics Initialization and Modes, ......................................................................................... 152
11.3 Graphics Function ................................................................................................................... 153

© BISHWO PRAKASH POKHAREL [4]


C Programming Language

SYLLABUS
Course Title: C Programming Full Marks: 60 + 20 + 20
Course No: CSC110 Pass Marks: 24 + 8 + 8
Nature of the course: Theory + Lab Credit Hrs.: 3
Semester: I

Course Description: This course covers the concepts of structured programming using C
programming language.

Course Objective: This course is designed to familiarize students to the techniques of


programming in C.

Course Contents:

Unit 1: Problem Solving with Computer (2 Hrs.)


Problem analysis, Algorithms and Flowchart, Coding, Compilation and Execution, History
of C, Structure of C program, Debugging, Testing and Documentation

Unit 2: Elements of C (4 Hrs.)


C Standards( ANSI C and C99), C Character Set, C Tokens, Escape sequence, Delimiters,
Variables, Data types (Basic, Derived, and User Defined), Structure of a C program,
Executing a C program, Constants/ Literals, Expressions, Statements and Comments.

Unit 3: Input and Output (2 Hrs.)


Conversion specification, Reading a character, Writing a character, I/O operations, Formatted
I/O

Unit 4: Operators and Expression (4 Hrs.)


Arithmetic operator, Relational operator, Logical or Boolean operator, Assignment Operator,
Ternary operator, Bitwise operator, Increment or Decrement operator, Conditional operator,
Special Operators(sizeof and comma), Evaluation of Expression, Operator Precedence and
Associativity.

Unit 5: Control Statement (4 Hrs.)


Conditional Statements, Decision Making and Branching, Decision Making and Looping,
Exit function, Break and Continue.

Unit 6: Arrays (6 Hrs.)


Introduction to Array, Types of Array (Single Dimensional and Multidimensional),
Declaration and Memory Representation of Array, Initialization of array, Character Array
and Strings, Reading and Writing Strings, Null Character, String Library Functions( string
length, string copy, string concatenation, string compare)

Unit 7: Functions (5 Hrs.)


Library Functions, User defined functions, Function prototype, Function call, and Function
Definition, Nested and Recursive Function, Function Arguments and Return Types, Passing
Arrays to Function, Passing Strings to Function, Passing Arguments by Value, Passing
Arguments by Address, Scope visibility and lifetime of a variable, Local and Global
Variable,

© BISHWO PRAKASH POKHAREL [5]


C Programming Language

Unit 8: Structure and Union (5 Hrs.)


Introduction, Array of structure, Passing structure to function, Passing array of structure to
function, Structure within structure ( Nested Structure), Union, Pointer to structure

Unit 9: Pointers (6 Hrs.)


Introduction, The & and * operator, Declaration of pointer, Chain of Pointers, Pointer
Arithmetic, Pointers and Arrays, Pointers and Character Strings, Array of Pointers, Pointers
as Function Arguments, Function Returning pointers, Pointers and Structures, Dynamic
Memory Allocation

Unit 10: File Handling in C (4 Hrs.)


Concept of File, Opening and closing of File, Input Output Operations in File, Random
access in File, Error Handling in Files

Unit 11: Introduction to Graphics (3 Hrs.)


Concepts of Graphics, Graphics Initialization and Modes, Graphics Function

Laboratory Works:
This course requires a lot of programming practices. Each topic must be followed by a
practical session. Some practical sessions include programming to:
 Create, compile and run simple C programs, handle different data types available in
C, perform arithmetic operations in C, perform formatted input and output operations,
perform character input and output operations.
 Perform logical operations, create decision making programs, create loops to repeat
task.
 Create user-defined functions, create recursive functions, work with automatic, global
and static variables, create, manipulate arrays and matrices (single and
multidimensional), work with pointes, dynamically allocate de-allocate storage space
during runtime, manipulate strings (character arrays) using various string handling
functions.
 Create and use structures and files to keep record of students, employees etc.

Text Books:
1. Byron Gottfried: "Programming with C," , Second Edition, McGraw Hill Education.
2. Herbert Schildt, C The Complete Reference, Fourth Edition, Osborne/McGrawHill
Publication.

Reference Books:
1. Paul Deitel, Harvey Deitel, C: How to Program, Eighth Edition, Pearson Publication.
2. Al Kelley, Ira Pohl: "A Book on C", Fourth Edition, Pearson Education.
3. Brian W. Keringhan, Dennis M. Ritchiem, The C programming Language, Second
Edition, PHI Publication.
4. Ajay Mittal, Programming in C: A Practical Approach, Pearson Publication
5. Stephen G. Kochan, Programming in C, CBS publishers & distributors.
6. E. Balagurusamy, Programming in ANSI C, Third Edition, TMH publishing

© BISHWO PRAKASH POKHAREL [6]


C Programming Language

PROBLEM SOLVING WITH COMPUTER


CHAPTER OUTLINE
1.1 Problem analysis
1.2 Algorithms and Flowchart
1.3 Coding
1.4 Compilation and Execution
1.5 History of C
1.6 Structure of C program
1.7 Debugging
1.8 Testing and Documentation

Introduction:
There are number of problems occurs in our daily life. These problems should be solved
carefully to get the desired solution. Sometimes, we may have to calculate simple interest, we
may have to prepare mark sheet, salary sheet and may have to do numerous sophisticated
calculations.

A computer is a dumb machine which cannot do anything alone without our instructions. We
have to give instructions to the computer to do certain specific tasks. So, there should be
software and the software is the collection of programs, where programs are the set of
instructions which are given by the users. The software is written to solve a particular
problem that takes some input from users, process it and give the meaningful result as output.
If the instructions are not correct then the computer gives wrong result.

Just writing code is not sufficient to solve a problem. Program must be planned before coding
in any computer language available. There are many activities to be done before and after
writing code for the software development.

Stages while solving a problem using computer:


1. Problem Analysis
2. Algorithm Development
3. Flowcharting
4. Coding
5. Compilation and Execution
6. Debugging and Testing
7. Documentation

© BISHWO PRAKASH POKHAREL [7]


C Programming Language

Fig: Steps in problem solving

1.1 Problem analysis


Problem analysis is the process of becoming familiar with the problem. We need to analyze
and understand it well before solving a problem. The user’s requirements cannot be fulfilled
without clear understanding of his/her problem in depth. Inadequate identification of problem
may cause program less useful and insufficient. In this phase, we determine the requirements
like variables, functions, etc. to solve the problem. That means we gather the required
resources to solve the problem defined in the problem definition phase. We also determine
the bounds of the solution. For example: Banking solution, Hospital Medical study etc.

1.2 Algorithms and Flowchart,

Algorithm:
An algorithm is a finite set of steps defining the solution of a particular problem. An
algorithm is expressed in pseudo code - something resembling C language or Pascal, but with
some statements in English rather than within the programming language. Developing an
efficient algorithm requires lot of practice and skill. It must be noted that an efficient
algorithm is one which is capable of giving the solution to the problem by using minimum
resources of the system such as memory and processor’s time. Algorithm is a language
independent, well structured and detailed. It will enable the programmer to translate into a
computer program using any high-level language.

Features of Algorithm:
Following features should be present in an algorithm:
1. Proper understanding of the problem
2. Use of procedures/functions to emphasize modularity
3. Choice of variable names
4. Documentation of the program

© BISHWO PRAKASH POKHAREL [8]


C Programming Language

Criteria to be following by an algorithm:


The following is the criteria to be followed by an algorithm:
 Input: There should be zero or more values which are to be supplied.
 Output: At least one result is to be produced.
 Definiteness: Each step must be clear and unambiguous.
 Finiteness: If we trace the steps of an algorithm, then for all cases, the algorithm must
terminate after a finite number of steps.
 Effectiveness: Each step must be sufficiently basic that a person using only paper and
pencil can in principle carry it out. In addition, not only each step is definite, it must
also be feasible.

Example 1: Algorithm to compute and display the sum of two numbers.


1. Start
2. Read two numbers a and b
3. Calculate the sum of a and b and store it in sum.
4. Display the value of sum.
5. Stop

Example 2: Algorithm to computer the average of three numbers.


1. Start
2. Read three numbers a, b and c
3. Calculate the sum of a, b and c then divide the sum by 3 and store it in average.
4. Display the value of average
5. Stop

Example 3: Algorithm to calculate the factorial of a given number.


1. Start
2. Read the number n
3. Initialize i=1, fact=1
4. Is i = = n?
if yes, goto step 7
if no, go to step 5
5. fact = fact * i
6. i = i + 1, go to step 4
7. Print fact
8. Stop

Example 4: Algorithm to check whether the given number is odd or even.


1. Start
2. Read the number n
3. If n%2= = 0?
If yes, Print “The number is Even”
If no, Print “The number is odd”
4. Stop

Flowchart:
Flowchart is the graphical representation of an algorithm using the standard geometric
symbols. It includes a set of various standard shaped boxes that are interconnected by flow
lines. Flow lines have arrows (direction of flow) which determine the flow of data from one
place to another place. It also determines the control of program flow. All the activities are

© BISHWO PRAKASH POKHAREL [9]


C Programming Language

written within boxes in English language. The main goal of flowchart is to communicate
between programmers and business persons.

Advantages of flowchart:
 Communication: Quickly provide logic, ideas and descriptions of algorithms.
 Effective analysis: Clear overview of the entire problem.
 Proper documentation: Documents the steps followed in an algorithm. It helps us
understand its logic in future.
 Efficient coding: More ease with comprehensive flowchart as a guide.
 Easy in debugging and maintenance: debugging and maintenance of program is
easy.

Fig: Symbols used in flowchart

Example 1: Flowchart to calculate sum of two numbers.

© BISHWO PRAKASH POKHAREL [10]


C Programming Language

Example 2: Flowchart to find the factorial of a given number.

© BISHWO PRAKASH POKHAREL [11]


C Programming Language

Check Your Progress


1. Write algorithm and draw flowchart to find the largest number among three numbers.
2. Draw the flowchart for the solution of a quadratic equation and write algorithm and
explain it.
3. Write an algorithm and flowchart to determine whether a given integer is odd or even
and explain it.
4. Write an algorithm and flowchart to find out whether a given integer is zero, positive,
negative and explain it.
5. What is algorithm? Write an algorithm to check whether the given number is prime or
composite.
6. Write algorithm and flow chart to check whether the number entered by user is
exactly divisible by 5 or by 11.

1.3 Coding,
Coding is the process of transforming the program logic design into computer language
format. It is an act of transforming operations in each box of the flowchart in terms of the
statement of the program. The code written using programming language is also known as
source code. Coding is not the only task to be done to solve a problem using computer.
Coding/programming is writing instructions for a computer to perform. The instructions,
called source code, are written in special languages that are unlike natural human languages.
It also involves planning, testing, and debugging source code.

1.4 Compilation and Execution,


Compilation:
The process of changing high level language into machine level language is called
compilation. It is done by the special software called compiler. The compilation process tests
the program whether it contains syntax errors or not. If syntax errors are present, compiler
cannot compile the code. Compiler converts whole line of codes at a time. It only detects
error at last after compilation.

Execution:
Once, the compilation is completed, then the program is linked with other object programs
needed for execution, there by resulting in a binary program and then the program is loaded
into the memory for the purpose of execution and finally it is executed.

The program may ask user for inputs and generates outputs after processing the input.

1.5 Computer program and programming language

Program:
The set of sequenced instructions which command the computer to perform particular
operation or a specific task is called a program. Program is written in a programming
language then translated into machine code by a language processor so that the computer can
execute tasks. The programming language statements are the source program or source code.
Then we compile the source code and the result is called an object code.

Qualities of good program:


 A program should be correct
 A program should be easy to understand

© BISHWO PRAKASH POKHAREL [12]


C Programming Language

 A program should be easy to maintain and update.


 It should be reliable.
 It should be flexible.

Programming:
The process of writing a program following the grammar of the programming language is
called programming. When we write a program, we’ve to follow the grammatical rules so as
to write the statement in a program.

Programming language:
The programming language is used to communicate with the computer. It provides the set of
symbols, characters, strings, numbers, variable, constant etc. that helps us to make the
statement. A statement is used to express the task what we want to perform that’s why we
need programming language. It is simply the coded language used by programmers to write
instructions that a computer can understand to do what the user wants.

Types of programming language:


There are two types of programming languages, which can be categorized into the following
ways:
1. Low level language: This language is the most understandable language used by
computer to perform its operation. It can be further categorized into two types:
a. Machine Language (1GL): It consists of string of binary numbers (i.e. 0s and
1s) and it is the only one language, the processor directly understands.
Machine Language has an advantage of very fast execution speed and efficient
use of primary memory. Use of this language is very tedious, difficult and the
time consuming. This language is a low level language where detail
knowledge of how the machine works should be known. It is very difficult to
debug the error.
b. Assembly language (2GL): It is machine oriented language. It uses
mnemonics codes in place of 0s and 1s. The program is converted into
machine code by assembler. The resulting program is referred to as an object
code. Although assembly language saves time, reduce errors and easy to
debug, it has certain limitations like, the programmer must know its opcodes
or mnemonics codes to perform any task.
2. High level language: Instructions of this language’s is closely resemble to human
language or English like words or sentences, problem oriented and mathematical
notations to perform the task. The high level language is easier to learn. It requires
less time to write and is easier to maintain the errors. The high level language is
converted into machine language by one of the two different languages translator
programs, interpreter or compiler. Examples of high level languages are BASIC,
FORTRAN, ALGOL, COBOL, PL/1, PASCAL, C etc. High level language can be
further categorized as:
a. Procedural oriented language (3GL): General-purpose programming
language is called procedural languages or third generation language (3GL). It
includes languages such as Pascal, BASIC, COBOL, C FORTRAN etc. These
languages are designed to express the logic and the procedure of a problem.
Because of their flexibility, procedural languages are able to solve a variety of
problems.
b. Problem-oriented language (4GL): 4GL is a non-procedural or problem-
oriented language. It allows the users to specify what the output should be,

© BISHWO PRAKASH POKHAREL [13]


C Programming Language

without describing all the details of how the data should be manipulated to
produce the result. This is one step ahead from 3GL. These are result oriented
and include database query languages. For example, Visual Basic, C#, PHP
etc. The objectives of 4GL include:
 Increase the speed of developing programs.
 Minimize user’s effort to obtain information from computer.
 Reduce errors while writing programs that are easy to maintain.
c. Natural Language (5GL): Natural languages are still in developing stage
where we could write statements that would look like normal sentences.
Computer scientists are working hard for developing such languages.
However, a programming language named PROLOG is in use, which would
support 5GL to some extent.

Language Translator:
Language translator is a program that translates instructions written in assembly or high level
language (source code) into machine language (object code). Program is developed in
assembly or high level language for the convenience of the programmer, but computer doesn't
understand these statements directly. So, translator program is used which converts that
statements in computer executable format. There are mainly three types of language
translator:
a. Assembler: Assembler is a translator that converts code of assembly language into
the machine language. The resulting program can be executed only when the
assembly process is completed. It also generates diagnostic error messages. It is so
called because in addition to translating, it also assembles the machine language
program in memory of the computer, and makes it ready for execution.
b. Compiler: A compiler is a translator which translates high level program (source
code) into machine instructions (object code) at once and then it can be immediately
executed anytime thereafter. This is the fastest method of translating a program. In
compiler, the syntax errors are found only after the compilation of the complete
program.
c. Interpreter: An interpreter is a translator which translates high level language into a
machine language, one line at a time and executes line of the program after it has been
translated. Since, the interpreter needs to evaluate the program letter by letter, then
word by word, and then line by line, its speed is incredibly slow. In interpreter, syntax
errors can be trapped after translation of every line.
Difference between compiler and interpreter
S.No. Compiler S.No. Interpreter
1 It translates the whole program into 1 It translates one line or single
machine code at a time. statement of a program into
machine code at a time.
2 It traps the errors after compiling the 2 It traps the errors after translating a
complete program. line of the program at a time.
3 The compiling process is incredibly 3 The translating process is slower.
faster.
4 Compiler based program is difficult to 4 Interpreter based program is easy to
code and debug. code and debug.
5 It creates the object code. 5 It does not create object code.
6 Compiler based programming 6 Interpreter based programming
language are C, C++ etc. language are Basic, Visual Basic
etc.

© BISHWO PRAKASH POKHAREL [14]


C Programming Language

1.6 Introduction and History of C,

Introduction of 'C'
C is a programming language developed by Denis Ritchie in 1972 at AT&T. In the late 70's,
C began to replace more familiar languages of that time like PL/I, ALGOL, FORTRAN etc.
No one was there for promoting and advertising C, but it became official language in Bells
Labs. Surprisingly, most of the programmers refer C language because it is simple, reliable
and easy to use. At that time, PASCAL was used as pure programming language. PASCAL
has similar features with C, most programmer shift to C because of robustness and platform
independence.

All the programming language broadly categorized into two types: High level language
(HLL) and Low level language (LLL). High level languages are designed to give better
efficiency, faster development and user-friendly development environment. Low level
language are designed to give better machine efficiency, faster program execution and low
processor overload. C stands in between HLL and LLL. Hence, C language is often called
Middle Level language (MLL). It has relatively good programming efficiency, faster
development and user-friendly like HLL and relatively better machine efficiency, faster
program execution and low processor overload like LLL.

History of 'C'
By 1960 a large number of computer languages had come into existence. Most of these for a
specific purpose like COBOL was used for commercial purposes, FORTRAN was used for
scientific purposes, and ALGOL was used for algorithmic conversion. For the sake of general
purpose programming language, CPL (Combined Programming Language) was introduced
by Cambridge University. But this programming language was hard to learn and difficult to
implement. BCPL (Basic Combined Programming Language) came to emerge as simplified
version of CPL. At the same time, a language called B was written by Ken Thompson at
AT&T's Bells Lab. It was too further simplification of CPL. Just like BCPL, B too turned out
to be very specific. Denis Ritchie writes a programming language by inheriting the features
of B, BCPL and his own concept to develop C. Its name became C because it was the
immediate predecessor of B language. Unlike BASIC and Pascal, C was not written as
teaching language, but as an implementation language.

Features of C:
It is broadly used all around the world, from palmtop to mainframe computer and even in
supercomputers. The C programming languages has the following features:
i. It has small size.
ii. It has extensive use of function call.
iii. It is a strong structural language having powerful data definition methods.
iv. It has low level (bit wise) programming available.
v. It can handle low level activities.
vi. Pointer makes it very strong for memory manipulations.
vii. It has high level constructors.
viii. It can produce efficient programs.
ix. It can be compiled on variety of computers.

© BISHWO PRAKASH POKHAREL [15]


C Programming Language

Advantages and Disadvantages of C:


Advantages:
i. It is machine independent programming language.
ii. It is easy to learn and implement C language.
iii. It an be implemented from mobile device to mainframe computers.
iv. It is the mother of all modern programming languages, Python is fully written in
C.
Disadvantages:
i. There is no runtime checking.
ii. It has poor error detection system.
iii. There is no strict type checking int data type to float variables.
iv. It does not support modern programming methodologies oriented programming
language.

1.7 Structure of C program,


1. #include<stdio.h>

2. #include<conio.h>
In most of simple C program, it is fixed. It is just like start
3. main() in algorithm.

4. {
It is used to display text enclosed “………”
5. printf(“Welcome in first C program”);
except some format specifier on the
6. printf(“You are learning C in lab”); output screen.

7. getch(); It is used to hold output screen until you pressed any key from
keyboard
8. }
It is the termination of C program. It is equivalent to End in
Algorithm.

Compiling process of C:
Compiler is a program that transforms all the source code written in C language into object
code prior to execution of that program. The compilation of the program begins with saving
the source code with extension .c. This source code will not understand by the computer. The
next step is to convert the source code into machine language (object code). This task is
performed by a software or program known as a compiler. The first step that the compiler
does is it sends our source code through the C preprocessor. The compiler converts the source
code into assembly code and then only assembler converts the object code. The object code is
just a machine code in the form of 0 and 1, which machine understands.

© BISHWO PRAKASH POKHAREL [16]


C Programming Language

Source Code
Preprocessor

Compiler
Assembly Code
Assembler
Object Code Libraries
Link Editor

Executable Code

Preprocessor and Header files:

Preprocessor: It is a separate program invoked by the compiler as the first part of translation.
The preprocessor handles directives for source file inclusion (#include), macro definitions
(#define), conditional inclusion (#if, #ifdef, #elif, #endif) and miscellaneous directives
(#pragma, #undef, #error). Preprocessor commands are considered as a language within C
language. The preprocessor offers several feature called preprocessor directives. There are
three types of preprocessor directives:
i. File inclusion: This is the main preprocessor directive on C program. This directive is
causes one file to be included in another C program source code. This causes the
entire content of file is inserted or included to the program. It is declared by using
#include keyword. It is defined as two ways: #include<filename> and #include
"filename".
ii. Macro Define: The declaration of variable by using #define is called macro define.
Macro is used to declare variables within program. If we declare macro Pi as
#define Pi 3.1415, it is just like the mathematical notation 'let Pi=3.1415.
iii. Conditional inclusion: This type of condition is often used where two different
computer types implement a feature in different ways. It allows the programmer
to produce a program by using conditional parameter like #if, #endif, #else, #elif
etc.

Header file: A file that is defined to be included at the beginning of a program in C language
that contains the definitions of data types and declarations of variables used by the function in
the program is called header file. It allow programmers to separate certain elements of a
program's source code into reusable files. It has the extension .h. Generally it is used to define
constants, variables, macros and functions that may be common to several applications. The
updating and reading data of any function can be performed by using the header files. Some
of the frequent used header files are explain below:
S.No. Header File Description Main Functions
1 stdio.h Standard input and output fopen(), fclose(), rename(),
gets(), puts(), getchar(),
scanf(), printf() etc.
2 conio.h Old MS-DOS compiler header file getch(), getche()
used for console input output
3 math.h Mathematical calculation in C sin(x), cos(x), log(x),
program pow(x,2), sqrt(x), cbrt(x),

© BISHWO PRAKASH POKHAREL [17]


C Programming Language

ceil(x), floor(x) etc.


4 complex.h Complex arithmetic cpow(x,p), csqrt(x), ctan(x),
ctanh(x), cabs(x) etc.
5 string.h String/words manipulation function strlen(y), strcpy(z,y),
strcmp(z,y), strcat(z,y),
strupr(y), strlwr(y) etc.
6 ctype.h Character manipulation type header toupper(y), tolower(y),
file isupr(y), isspace(), isalnu(y),
toascii(y) etc.
7 stdlib.h General purpose standard library rand(), malloc(), calloc(),
abort(), exit(), abs(), free()
etc.

1.8 Debugging,
Debugging is a process of detecting, locating, and removing error in a program. Mistakes
may be syntax error or logical error or run-time error.

Syntax error:
Syntax error is the error in th program's grammatical rule or in writing format. If a program
contains syntax error, the program will not be executed and will not produce output. This
error is detected by translator during translation so, it is easier to correct. For example in C
language whenever we do not use semicolon in a simple statement causes syntax error.

Logical error (Semantic error):


A logical error is an error (bug) in the concept or logic of the program. It causes a program to
operate incorrectly. If a program contains only a logical error, the program will be executed
and will also produce output, but the output will not be accurate. For example, to calculate
the simple interest the formula is i=(p*t*r)/100 but if we write i=(p*t*r)/10 then it will
produce semantic error, because it is syntactically correct but it produce undesired output.

Run-Time error:
When a program is running, or executing, it is said to be in run time. A run-time error is an
error that is generated while the program is being executed. For example, a memory leak,
where the program takes up excessive amounts of system memory, then it may generate run-
time error as it may allow other programs to be loaded in the memory.

1.9 Testing and Documentation


Testing ensures that program performs correctly the required task. Verification ensures that
program does what the programmer intends to do. Validation ensures that the program
produces the correct results for a set of test data. Test data are supplied to the program and
output is observed. The expected output should be error free.

Program documentation:
Program documentation helps to those who use, maintain and extend the program in future. A
program may be difficult to understand even to programmer who wrote the code after some
days. Properly documented program is necessary which will be useful and efficient in
debugging, testing, maintenance and redesign process.
There are two types of documentations:

© BISHWO PRAKASH POKHAREL [18]


C Programming Language

1. Programmer’s documentation (Technical documentation): It is maintained by the


programmer or developer which contains the information of maintain, redesign and
upgrade of program.
2. User documentation (User manual): It support to the end user of the program. It
contains the instructions for installation of the program.

Exercise:
1. Why flowchart is required? Explain different symbols used in the flowchart and
explain with suitable example.
2. Draw the flowchart for the solution of a quadratic equation and write an algorithm and
explain it.
3. Explain the structure of C-Program with example.

© BISHWO PRAKASH POKHAREL [19]


C Programming Language

ELEMENTS OF C
CHAPTER OUTLINE
2.1 C Standards( ANSI C and C99),
2.2 C Character Set,
2.3 C Tokens, Escape sequence,
2.4 Delimiters, Variables, Data types (Basic, Derived, and User Defined),
2.5 Structure of a C program,
2.6 Executing a C program,
2.7 Constants/ Literals,
2.8 Expressions,
2.9 Statements and Comments.

2.1 C Standards( ANSI C and C99),


ANSI C:
ANSI C, ISO C and Standard C refer to the successive standards for the C programming
language published by the American National Standards Institute (ANSI) and
the International Organization for Standardization (ISO). Historically, the names referred
specifically to the original and best-supported version of the standard (known as C89 or C90).
Software developers writing in C are encouraged to conform to the standards, as doing so
helps portability between compilers.

C99:
In March 2000, ANSI adopted the ISO/IEC 9899:1999 standard. This standard is commonly
referred to as C99. Some notable additions to the previous standard include:
 New built-in data types: long long , _Bool , _Complex , and _Imaginary
 Several new core language features, including static array indices, designated
initializers, compound literals, variable-length arrays, flexible array members,
variadic macros, and restrict keyword
 Several new library headers, including stdint.h , <tgmath.h> , fenv.h , <complex.h>
 Improved compatibility with several C++ features, including inline functions, single-
line comments with // , mixing declarations and code, and universal character names
in identifiers
 Removed several dangerous C89 language features such as implicit function
declarations and implicit int

Three technical corrigenda were published by ISO for C99:


 ISO/IEC 9899:1999/Cor.1:2001(E)
 ISO/IEC 9899:1999/Cor.2:2004(E)
 ISO/IEC 9899:1999/Cor.3:2007(E), notable for deprecating the standard library
function gets

© BISHWO PRAKASH POKHAREL [20]


C Programming Language

2.2 C Character Set,


C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain
special characters as building blocks to form basic program elements (e.g., constants,
variables, operators, expressions, etc.). The special characters are listed below.
+ - * / = % & # ! ? ^ “
‘ ~ \ | < > ( ) [ ] { }
: ; . , _ (blank space)

Most versions of the language also allow certain other characters, such as @ and $, to be
included within strings and comments. C uses certain combinations of these characters, such
as \b, \n and \t, to represent special conditions such as backspace, newline and horizontal tab,
respectively. These character combinations are known as escape sequences.

2.3 C Tokens, Escape sequence,


C Tokens:
In a passage of text, individual words and punctuation marks are called tokens. Similarly, in a
C program the smallest individual units are known as C tokens. The basic elements
recognized by the C compiler are known as “C tokens”. E.g. of C tokens are: keywords (e.g.
float, while), identifiers (e.g. num, sum), constants (e.g. -15.5, 100), string literals (e.g.
“ABC”, “year”), operators (e.g. +,-,*,/) and special symbols (e.g. [], {}, (), ,).

Escape sequences:
It is a character combination consisting of a backslash (\) followed by a letter or a digit.
Escape sequences always represent single character, however they are written in terms of two
characters. Escape sequences has a single ASCII value. Escape sequences are useful for
formatting input and output.
Escape Sequence Use
\a Audible Alert or beep sound
\b Backspace delete on character to the left
\n Move cursor to the Next or New line of the screen
\v Vertical tab
\t Horizontal tab
\’ Single quote
\” Double quote
\\ Backslash
\0 Null character

Keywords and Identifiers:


Every C word is classified as either a keyword or an identifier. Keywords are predefined
words in C programming language. All keywords have fixed meaning and these meanings
cannot be changed. Keywords are also called reserved words because they are used for pre-
defined purposes and cannot be used as identifiers.

ANSI C Keywords:
auto break case char const
continue default do double else
enum extern float for goto
if int long register return

© BISHWO PRAKASH POKHAREL [21]


C Programming Language

short signed sizeof static struct


switch typedef union unsigned void
volatile while
Note: Keywords are written in lower case.

Identifiers:
 Every word used in C program to refer to the names of variables, functions, arrays,
pointers and symbolic constants are called identifiers.
 These are user-defined names and consist of a sequence of letters and digits, with a
letter as the first character.
 Both uppercase and lowercase letters can be used, although lowercase letters are
commonly preferred.
 The underscore character can also be used to link between two words in long
identifiers.

Rules for identifiers:


1) First character must be an alphabet (or underscore).
2) Must consist of only letters, digits or underscore.
3) Must not contain white space. Only underscore is permitted.
4) Keywords cannot be used.
5) Only first 31 characters are significant.
6) It is case-sensitive, i.e. uppercase and lowercase letters are not interchangeable.
Check Your Progress
1. Determine which of the following are valid identifiers? If invalid, explain the reason.
(a) keyword (b) n1+n2 (c) file_3 (d) #ph_no (e) double
(f) Rs2000 (g) doubles (h) first_name (i) 2var (j) first-name
(k) $1000 (l) return (m) _1 (n) inta
2. Determine which of the following are valid identifiers? If invalid, explain why.
a) record1 b) 1record c) file_3 d) return e) #tax f) name
g) goto h) name and address i) name-and-address j) 123-45-6789
k) void l) name_address

2.4 Delimiters, Variables, Data types


Delimiters:
A delimiter is one or more characters that separate text strings.
Common delimiters are commas (,), semicolon (;), quotes ( “, ' ), braces ({}), pipes (|),
or slashes ( / \ ). When a program stores lots of data it may use a delimiter to separate each of
the data values. For example, "john|doe" has a pipe as its delimiter, a program or script could
distinguish between the first and last name in a string of text.

Data Types:
A C language programmer has to tell the system before-hand, the type of numbers or
characters he is using in his program. These are data types. There are many data types in C
language. A C programmer has to use appropriate data type as per his requirement.
Primary data type:
All C compilers accept the following fundamental data types:
1 Integer Int
2 Character Char
3 Floating Point Float

© BISHWO PRAKASH POKHAREL [22]


C Programming Language

4 Double precision floating point Double


5 Void Void

Integer type: Integers are whole numbers with a machine dependent range of values. A good
programming language as to support the programmer by giving a control on a range of
numbers and storage space. C has 3 classes of integer storage namely short int, int and long
int. All of these data types have signed and unsigned forms. A short int requires half the
space than normal integer values. Unsigned numbers are always positive and consume all the
bits for the magnitude of the number. The long and unsigned integers are used to declare a
longer range of values.
 Integers occupy 16-bits in memory, so the size of the integer value is limited to the
-32768 to +32767 (i.e. -215 to +215-1). This is because one bit is used for sign and
other 15-bits for magnitude.
 Note: By default all integers are signed unless explicitly specified
 Negative numbers are represented in 2’s complement form.
 In C, integers are divided into three classes:
 Integer (int)
 Short Integer (short int)
 Long Integer (long int)
in both signed and unsigned forms.

Signed integer:
 By default, all integers are signed i.e. it represents both positive and negative integers.
 The data type qualifier is signed int or int.
E.g. Variables are defined as-
signed int a;
int b;
 It reserves 16-bits (2 bytes) in memory.
 Range: -32768 to 32767 i.e. -215 to 215-1.
 The conversion character is d.

Unsigned integer:
 Unsigned integers have to be declared explicitly.
 Represents only positive integers.
 The data type qualifier is unsigned int or unsigned.

E.g. Variables are defined as-


unsigned int a;
unsigned b;
 It reserves 16-bits (2 bytes) in memory.
 Range: 0 to 216-1, i.e. 0 to 65535.
 The conversion character is u.

Signed short integer:


 By default all short integers are signed i.e. it represents both positive and negative
integers.
 The data type qualifier is signed short int or short int or short.

E.g. Variables are defined as-


signed short int a;

© BISHWO PRAKASH POKHAREL [23]


C Programming Language

short int b;
short c;
 It reserves 16-bits (2 bytes) in memory.
 Range: -215 to 215-1, i.e. -32768 to 32767.
 The conversion character is d or i.

Unsigned short integer:


 Unsigned short integers have to be declared explicitly.
 It represents only positive integers.
 The data type qualifier is unsigned short int or unsigned short.
E.g. Variables are defined as-
unsigned short int a;
unsigned short b;
 It reserves 16-bits (2 bytes) in memory.
 Range: 0 to 216-1, i.e. 0 to 65535.
 The conversion character is u.

Signed long integer:


 By default, all long integers are signed i.e. it represents both positive and negative
integers.
 The data type qualifier is signed long int or long int or long.
E.g. Variables are defined as-
signed long int a;
long int b;
long c;
 It reserves 32-bits (4 bytes) in memory. One bit is used for sign and the other 15 bits
for magnitude of the integer.
 Range: -231 to 231-1, i.e. -2147483648 to 2147483647.
 The conversion character is ld.

Unsigned long integer:


 Unsigned long integers have to be declared explicitly.
 It represents only positive integers.
 The data type qualifier is unsigned long int or unsigned long.
E.g. Variables are defined as-
unsigned long int a;
unsigned long b;
 It reserves 32-bits (4 bytes) in memory.
 The range for unsigned long integers is 0 to 232-1, i.e. 0 to 4294967295.
 The conversion character is lu.

Floating Point type: Floating point number represents a real number with 6 digits precision.
Floating point numbers are denoted by the keyword float. When the accuracy of the floating
point number is insufficient, we can use the double to define the number.
 The data type qualifier is float.
E.g. Variables are defined as-
float a;
 Floating numbers reserve 32 bits (i.e. 4 bytes) of storage, with 6 digits of precision.
 Range: -3.4e38 to +3.4e38.
 The conversion character is f.

© BISHWO PRAKASH POKHAREL [24]


C Programming Language

Double type:
 When the accuracy provided by a float number is not sufficient, the type double is
used to define the number.
 A double data type number uses 64 bits (8 bytes) giving a precision of 14 digits. So,
these are called double precision numbers.
 Range: -1.7e308 to +1.7e308.
 The data type qualifier is double.
E.g. Variables are defined as-
double a;
 Its conversion character is lf.
 To extend the precision further, long double can be used which uses 80 bits (10 bytes)
giving 18 digits of precision.
 Range: -1.7e4932 to +1.7e4932.
 The data type qualifier is long double.
E.g. Variables are defined as-
long double a;
 Its conversion character is Lf.

Character Type : A single character can be defined as a defined as a character type of data.
Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned
can be explicitly applied to char.
 A single character can be defined as a character type data.
 Characters are stored in 8 bits (1 byte).
 The data type qualifier is char.
 The qualifier signed or unsigned may be used with char.
 The unsigned char has values between 0 and 255 while signed char has values from -
128 to 127.
 The conversion character is c.
 In character data type, each character is represented by an ASCII (American Standard
Code for Information Interchange) value internally.
 For e.g. the character ‘A’ is represented by 65, ‘B’ by 66 and so on for others.
 When a character is displayed using the conversion character d, it will display ASCII
value; and when it is displayed using the conversion character c, it will display
character.

Void Type : Using void data type, we can specify the type of a function. It is a good practice
to avoid functions that does not return any values to the calling function.
Size and range of data types:

© BISHWO PRAKASH POKHAREL [25]


C Programming Language

Variables:
A variable is a value that can change any time. It is a memory location used to store a data
value. A variable name should be carefully chosen by the programmer so that its use is
reflected in a useful way in the entire program. Variable names are case sensitive. Example of
variables names are:
Sun
Number
Salary
Emp_name
average1

Any variable declared in a program should confirm to the following


a. They must always begin with a letter, although some systems permit
underscore as the first character.
b. The length of a variable must not be more than 8 characters.
c. White space is not allowed and
d. A variable should not be a Keyword
e. It should not contain any special characters.
Examples of Invalid Variable names are:
123
(area)
6th
%abc

Variable declaration:
Variables should be declared before using it in a program.

Syntax:
data_type variable_name;
Where, variable_name is the name of the variable.

For example:
int a;
float radius;
char gender;
int x1, x2, x3;

© BISHWO PRAKASH POKHAREL [26]


C Programming Language

2.5 Constants/ Literals,


A constant value is the one which does not change during the execution of a program. C
supports several types of constants.
1. Integer Constants
2. Real Constants
3. Single Character Constants
4. String Constants

Integer Constants: An integer constant is a sequence of digits. There are 3 types of integers
namely decimal integer, octal integers and hexadecimal integer.

Decimal Integers consists of a set of digits 0 to 9 preceded by an optional + or - sign. Spaces,


commas and non digit characters are not permitted between digits. Example for valid decimal
integer constants are:
123
-31
0
562321
+ 78

Some examples for invalid integer constants are


15 750
20,000
Rs. 1000
Octal Integers constant consists of any combination of digits from 0 through 7 with a O at
the beginning. Some examples of octal integers are
O26
O
O347
O676

Hexadecimal integer constant is preceded by OX or Ox, they may contain alphabets from A
to F or a to f. The alphabets A to F refers to 10 to 15 in decimal digits. Example of valid
hexadecimal integers are
OX2
OX8C
OXbcd
Ox

Real Constants: Real Constants consists of a fractional part in their representation. Integer
constants are inadequate to represent quantities that vary continuously. These quantities are
represented by numbers containing fractional parts like 26.082. Example of real constants are
0.0026
-0.97
435.29
+487.0

Real Numbers can also be represented by exponential notation. The general form for
exponential notation is mantissa exponent. The mantissa is either a real number expressed in

© BISHWO PRAKASH POKHAREL [27]


C Programming Language

decimal notation or an integer. The exponent is an integer number with an optional plus or
minus sign.

A Single Character constant: represent a single character which is enclosed in a pair of


quotation symbols.

Example for character constants are


'5'
'x'
';'
''
All character constants have an equivalent integer value which are called ASCII Values.

String Constants: A string constant is a set of characters enclosed in double quotation


marks. The characters in a string constant sequence may be a alphabet, number, special
character and blank space. Example of string constants are
"BISHWO"
"1234"
"God Bless"
"!.....?"

In addition, C has other two types of constants:


1. Literal constant: A literal constant is a value that is typed directly into the source
code wherever it is needed. It is the basic and commonly used constant compared to
symbolic constant.
A literal constant is defined by writing:
area=3.14*r*r; /*3.14 is the constant value of pie*/
2. Symbolic constant: A symbolic constant is a name that substitutes for a sequence of
characters. The characters may represent a numeric constant, a character constant or a
string constant. Thus, s symbolic constant allows a name to appear in place of
numeric constant, a character constant or a string. When a program is compiled, each
occurrence of a symbolic constant is replaced by its corresponding character
sequence.

Symbolic constant is usually defined at the beginning of a program. It may appear


later in the program in place of the numeric constants, character constants or string
constant.

A symbolic constant is defined by writing:


#define PI 3.14

Where PI represents a symbolic constant, typically written in uppercase letters, and


3.14 represents the sequence of digits that is associated with the symbolic constant PI.

Note that the text does not end with a semicolon, since a symbolic constant definition
is not a true C statement. Moreover, if text were to end with a semicolon, this
semicolon would be treated as though it were a part of the numeric constant, character
constant or string constant that is substituted for the symbolic constant.

© BISHWO PRAKASH POKHAREL [28]


C Programming Language

2.6 Expressions,
Arithmetic Expressions
An expression is a combination of variables constants and operators written according to the
syntax of C language. In C every expression evaluates to a value i.e., every expression results
in some value of a certain type that can be assigned to a variable. Some examples of C
expressions are shown in the table given below.

Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;

Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and then replaces the previous value of the variable on the left hand side. All
variables used in the expression must be assigned values before evaluation is attempted.

Example of evaluation statements are


x=a*b–c
y=b/c*a
z = a – b / c + d;

The following program illustrates the effect of presence of parenthesis in expressions:


#include<stdio.h>
#include<conio.h>
main()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (“x = %f”,x);
printf (“y = %f”,y);
printf (“z = %f”,z);
getch();
}
Output
x = 10.00 y = 7.00 z = 4.00

© BISHWO PRAKASH POKHAREL [29]


C Programming Language

2.7 C Comments
 Used for program documentation.
 Comments are not compiled.
 The C syntax for writing comment is
/*
Anything written in between slash and asterisk and asterisk and slash is comment
*/
 Another way to write comment in C
// Using double slash (This line only)

© BISHWO PRAKASH POKHAREL [30]


C Programming Language

INPUT AND OUTPUT


CHAPTER OUTLINE
3.1 Conversion specification,
3.2 Reading a character,
3.3 Writing a character,
3.4 I/O operations,
3.5 Formatted I/O
Data input and output:
 Generally, a program reads input data from keyboard (standard input device), the C
program then processes the input data and the result is displayed on the screen
(standard output device).
 In C, there are a number of input and output functions to do these tasks.
 When a program needs data, it takes the data through the input functions and then
sends the results to output devices through the output functions.
 The standard input functions are
scanf(), getchar(), getche(), getch(), gets(), etc.
 The standard output functions are
printf(), putchar(), putch(), puts(), etc.

NOTE: In C, the standard library, <stdio.h> provides functions for input and output.

3.1 Conversion specification,


Conversion Character Meaning
%c Prints a single character
%d Prints a decimal integer
%i Prints a signed decimal integer
%u Prints an unsigned decimal integer
%f Prints a floating point value
%e Prints a floating point value in exponent form
%o Prints an octal integer, without leading zero
%x Prints a hexadecimal integer, without leading 0x

3.2 Reading and writing a character,

Single character input:


Single characters can be entered into the computer using the C library function getcher. The
getcher function is a part of the standard C I/O library. It returns a single character from a
standard input device (typically a keyboard). The function does not require any arguments,
though a pair of empty parentheses must follow the word getcher.
In general terms, a function reference would be written as:
Character variable = getchar();
Where, character variable refers to some previously declared character variable.

© BISHWO PRAKASH POKHAREL [31]


C Programming Language

Single character output:


Single characters can be displayed (Le, written out of the computer) using the C library
function putchar. This function is complementary to the character input function getchar. The
putchar function, like getchar, is a part of the standard C I/O library. It transmits a single
character to a standard output device (typically a TV monitor). The character being
transmitted will normally be represented as a character-type variable. It must be expressed as
an argument to the function, enclosed in parentheses, following the word putchar.
In general, a function reference would be written as:
putchar(character variable)
Where, character variable refers to some previously declared character variable.

3.3 I/O operations,


Entering input data – the scanf function:
Input data can be entered into the computer from a standard input device by means of the C
library function scanf. This function can be used to enter any combination of numerical
values, single characters and strings. The function returns the number of data items that have
been entered successfully.

In general terms, the scanf function is written as:


scanf(control string, arg1, arg2, …, argn)
where control string refers to a string containing certain required formatting information, and
argl, arg2, . . . argn are arguments that represent the individual input data items. (Actually, the
arguments represent pointers that indicate the addresses of the data items within the
computer's memory.

Writing output data – the printf function:


Output data can be written from the computer onto a standard output device using the library
function printf. This function can be used to output any combination of numerical values,
single characters and strings. It is similar to the input function scanf, except that its purpose is
to display data rather than to enter it into the computer. That is, the printf function moves data
from the computer’s memory to the standard output device, whereas the scanf function enters
data from the standard input device and stores it in the computer’s memory.
In general terms, the printf function is written as:
printf(control string, arg1, arg2, …. , argn)
where control string refers to a string that contains formatting information, and arg1, arg2, . . .
, argn are arguments that represent the individual output data items. The arguments can be
written as constants, single variable or array names, or more complex expressions. Function
references may also be included.

The gets and puts functions:


C contains a number of other library functions that permit some form of data transfer into or
out of the computer. The gets and puts functions facilitate the transfer of strings between the
computer and the standard input/output devices.

Each of these functions accepts a single argument. The argument must be a data item that
represents a string. (e.g., a character array). The string may include whitespace characters. In
the case of gets, the string will be entered from the keyboard, and will terminate with a
newline character (i.e., the string will end when the user presses the Enter key).
S.No. Function Description
1 getc() Input macro to read a character from a file.

© BISHWO PRAKASH POKHAREL [32]


C Programming Language

2 getch() Reads one keystroke without echoing input character


3 getchar() Input function to read a character from keyboard.
4 getche() Read one keystroke with echoing input character.
5 gets() Reads strings or words declared inside <string.h> header file
6 printf() Output from computer system.
7 putc() Output macro to print a character on the file
8 putchar() Output function to print a character on the monitor.
9 puts() Output words or strings in monitor.
10 scanf() Input from keyboard, different data can be entered like int,
float, char, string etc.

3.4 Formatted I/O


 These allow the input read from the keyboard or the output displayed on screen to be
formatted according to our requirements.
 Example, the input function printf() and the output function scanf() fall under
formatted functions.

Formatted input:
 Formatted input refers to an input data that has been arranged in a particular format.
 scanf() function can be used to enter input data from a standard input device.
 The general form of scanf() is, scanf(“control string”, &arg1, &arg2, …, &argN);
 The general form of a control string is:
 [whitespace character][ordinary character]%[field width]conversion character
 [ ]-----optional
Note: The programs succeeding this slide clarify the use of formatted input.

For example:
1.
void main()
{
int day, month, year;
clrscr();
printf("Enter day, month, year in DD-MM-YYYY format:");
scanf(" %d-%d-%d", &day, &month, &year);
printf("\n Day: %d \t Month: %d \t Year:%d", day, month, year);
getch();
}
2.
void main()
{
int n100;
clrscr();
printf("Enter a number of max 5 digits:");
scanf("%5d",&n100);
printf("Number: %d",n100);
getch();
}

© BISHWO PRAKASH POKHAREL [33]


C Programming Language

3.
#include<stdio.h>
#include<conio.h>
#include <math.h>
void main()
{
double p, t, r, si, ci, sa, ca;
printf("Enter principal in Rs:");
scanf("%lf", &p);
printf("\n Enter time in year:");
scanf("%lf", &t);
printf("\n Enter rate in percent per annum:");
scanf("%lf", &r);
si=(p*t*r)/100;
printf("\n Simple interest:%.2lf", si);
ci=p*(pow(1+r/100,t)-1);
printf("\n Compound interest:%.2lf", ci);
sa=p+si;
printf("\n Simple amount:%.2lf", sa);
ca=p+ci;
printf("\nCompound amount:%.2lf", ca);
printf("\n The difference between compound and simple amount:%.2lf", ca-sa);
getch();
}

Formatted Output:
 Formatted output refers to the output of data that has been arranged in a particular
format.
 printf() function is used to output data onto a standard output device i.e. screen.
 The general form of printf() is, printf(“control string”, arg1, arg2, …, argN);
 The control string has the form,
 %[flag][field width][.precision]conversion character
 Flags
 Flags may be
 - (left justified)
 + (sign precedes)
 0 (leading 0s)
 blank space (preceding space)
 # (causes octal and hex items to be preceded by 0 and 0x)
 Field Width
 The field width is an integer that indicates the minimum output field width.
 If the no. of characters in the data item is less than field width, then the data
item is preceded by appropriate leading blanks to fill the specified field.
 If the no. of characters in the data item is greater than field width, then extra
space is allocated to the data item so that the entire data item is displayed.
 Any integer no. can be displayed in a desired width using the format,
%wd
where w is the minimum field width for the output and d specifies that the value is an
integer.

© BISHWO PRAKASH POKHAREL [34]


C Programming Language

OPERATORS AND EXPRESSION


CHAPTER OUTLINE
4.1 Arithmetic operator,
4.2 Relational operator,
4.3 Logical or Boolean operator,
4.4 Assignment Operator,
4.5 Ternary operator,
4.6 Bitwise operator,
4.7 Increment or Decrement operator,
4.8 Conditional operator,
4.9 Special Operators(sizeof and comma),
4.10 Evaluation of Expression,
4.11 Operator Precedence and Associativity.

Operator:
• An operator is a symbol that is used in programs to perform certain mathematical or
logical manipulations.
• E.g. in the simple expression 1+2, the symbol + is called an operator which operates
on two data items 1 and 2.
• The data items that operators act upon are called operands.

Expression:
• An expression is a combination of operands (variables, constants) and operators
written according to the syntax of the language.
• General syntax: operand operator operand
• Examples: 1+2
a+b
a-b*c
a<=b
a*b/c
4.1 Arithmetic operator,
• C provides all the basic arithmetic operators.
• Arithmetic operators perform arithmetic operations.
• There are five arithmetic operators in C.
Operator Meaning Example (Arithmetic Output
Expression) (int a=11, b=5)
+ Addition a+b 16
- Subtraction a-b 6
* Multiplication a*b 55
/ Division a/b 2
% Modulo Division a%b 1

© BISHWO PRAKASH POKHAREL [35]


C Programming Language

Note:-
▫ The operands acted upon by arithmetic operators must be numeric values (int,
float, etc.).
▫ The division operator requires that the second operand be non-zero.
▫ Integer division truncates any fractional part.
▫ The modulo division operator (remainder operator) requires that both operand
be integers and that the second operand be non-zero.
▫ The unary minus operator multiplies its single operand by -1.

Integer arithmetic, real arithmetic and mixed-mode arithmetic:


• When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression, and the operation is called integer
arithmetic.
• An arithmetic operation involving only real operands is called real arithmetic.
• When one of the operands is real and the other is integer, the expression is called a
mixed-mode arithmetic expression.
Note:-
▫ Integer arithmetic always yields an integer value.
▫ The operator % cannot be used with real operands.
▫ For Integer Division, when both operands are of same sign, the result is
truncated towards 0.
E.g. 6/7=0 and -6/-7=0.
▫ However, when one of the operand is negative, then the truncation is machine-
dependent i.e. -6/7 may be 0 or -1.
▫ For modulo division, the sign of the result is always the sign of the first
operand (the dividend).
E.g. -14 % 3 = -2
-14%-3 = -2
14 % -3 = 2
▫ Division Rule for Integer Arithmetic, Real Arithmetic and Mixed-mode
Arithmetic
 int / int = int
 float / float = float
 int / float = float
 float / int = float

4.2 Relational operator,


• Relational operators are used to compare two similar operands, and depending on
their relation, take some actions.
• Relational operators compare their LHS operand with their RHS operand for lesser
than, greater than, lesser than or equal to, greater than or equal to, equal to or not
equal to relations.
• The value of a relational expression is either 1 (if condition is true) or 0 (if condition
is false).
Operator Meaning Example (Relational Output
Expression) (int a=15, b=7)

< Lesser Than a<b 0


> Greater Than a>b 1

© BISHWO PRAKASH POKHAREL [36]


C Programming Language

<= Lesser Than or Equal To a <= b 0


>= Greater Than or Equal To a >= b 1
== Equal To a == b 0
!= Not Equal To a != b 1

Note:-
▫ The operators == and != are also called equality operators.
▫ When arithmetic expressions are used on either side of a relational operator,
the arithmetic expressions will be evaluated first and then the results are
compared.
▫ Arithmetic operators have high priority than Relational operators.
▫ Relational operators are used in decision making statements like if…..else
statements.
For example:
#include <stdio.h>
#include <conio.h>
main()
{
int a=10,b=28,c=10;
printf("a<b => %d \t a>b => %d \t a==c => %d", a<b, a>b, a==c);
printf("\na<=b => %d \t a>=b => %d \t a!=b => %d", a<=b, a>=b, a!=b);
getch();
}

4.3 Logical or Boolean operator,


• Logical operators are used to compare or evaluate logical and relational expressions.
The operands of these operators must produce either 1 (True) or 0 (False). The whole
result produced by logical operators is thus either True or False.
• Logical operators are also used in decision making statements.
• There are 3 logical operators in C:
&& logical AND
|| logical OR
! logical NOT
The following Truth Table summarizes the outcome of logical expressions:
Op1 Op2 Op1 && Op2 Op1 || Op2 !Op1 !Op2
0 0 0 0 1 1
0 1 0 1 1 0
1 0 0 1 0 1
1 1 1 1 0 0
Note:- 1 implies True
0 implies False

For example:
#include <stdio.h>
#include <conio.h>
main()
{
int a=10,b=5,c=20;

© BISHWO PRAKASH POKHAREL [37]


C Programming Language

printf(“\n a<b && a<c => %d”, (a<b && a<c));


printf(“\n a>b && b<c => %d”, (a>b && b<c));
printf(“\n a<b || a<c => %d”, (a<b || a<c));
printf(“\n a>b || b<c => %d”, (a>b || b<c));
printf(“\n a>c || b>c => %d”, (a>c || b>c));
getch();
}

4.4 Assignment Operator,


• Assignment operators are used to assign the result of an expression to a variable.
• The assignment operator is =.
• E.g. x = (a+b)/2;
/* Here the result of the expression (a+b)/2 is assigned to the variable x */
• In addition, C has a set of shorthand assignment operators of the form:
v op= exp;
/* Here v is a variable, exp is an expression and op is a C binary arithmetic operator. The
operator op= is called shorthand assignment operator. */
• The assignment statement v op= exp; is equivalent to v = v op (exp);
Statement with simple assignment operator Statement with shorthand operator
a=a+1 a += 1
a=a–1 a -= 1
a = a * (n + 1) a *= n+1
a = a / (n + 1) a /= n+1
a=a%b a %= b

4.5 Bitwise operator,


• Bitwise operators are used for manipulating data at bit level.
• These operators are used for testing the bits, or shifting them to the left or to the right.
• Bitwise operators can be applied only to integer-type operands (signed or unsigned)
and not to float or double.
• There are 3 types of bitwise operators-
• Bitwise logical operators
• Bitwise shift operators
• One’s complement operator
1. Bitwise Logical operators:
• Bitwise logical operators perform logical tests between two integer-type operands.
• These operators work on their operands bit-by-bit starting from the LSB (i.e. the
rightmost bit).
• There are three logical bitwise operators:
▫ Bitwise AND (&)
▫ Bitwise OR (|)
▫ Bitwise Exclusive OR / Bitwise XOR (^)

Bitwise AND (&):


• The bitwise AND performs logical ANDing between two operands.
• The result ANDing operation is 1 if both the bits have a value of 1; otherwise it is 0.
• E.g. If
num1 = 0101 0000 0000 0010

© BISHWO PRAKASH POKHAREL [38]


C Programming Language

num2 = 0001 0010 1100 1010


Then
num = (num1 & num2);
Gives
0001 0000 0000 0010

Bitwise OR ( | ):
• The bitwise OR performs logical ORing between two operands.
• The result of ORing operation is 1 if at least one of the bits have a value of 1;
otherwise it is 0.
• E.g. If
num1 = 0101 0000 0000 0010
num2 = 0001 0010 1100 1010
Then
num = (num1 | num2);
Gives
0101 0010 1100 1010
Bitwise Exclusive OR (^):
• The bitwise XOR performs logical XORing between two operands.
• The result of XORing operation is 1 only if one of the bits have a value of 1;
otherwise it is 0.
• E.g. If
num1 = 0101 0000 0000 0010
num2 = 0001 0010 1100 1010
Then
num = (num1 ^ num2);
Gives
0100 0010 1100 1000
For example:
#include <stdio.h>
#include <conio.h>
main()
{
int num1 = 50;
int num2 = 100;
int AND, OR, XOR;
AND = num1 & num2;
OR = num1 | num2;
XOR = num1 ^ num2;
printf(“AND=> %d\n”, AND);
printf(“OR=> %d\n”, OR);
printf(“XOR=> %d”, XOR);
getch();
}

2. Bitwise Shift Operators:


• Bitwise shift operators are used to move bit patterns either to the left or to the right.
• There are two bitwise shift operators:
▫ Left shift (<<)

© BISHWO PRAKASH POKHAREL [39]


C Programming Language

▫ Right shift (>>)

Left shift (<<):


• The left-shift operation causes the operand to be shifted to the left by some bit
positions.
• The general syntax of left-shift operation is: operand << n;
• Here, the bits in the operand are shifted to the left by n positions.
• The leftmost n bits in the original bit pattern will be lost and the rightmost n bits
empty positions will be filled with 0s.
• E.g. Let
num1 = 57; //0000 0000 0011 1001
Then if we execute the statement
num2 = num1 << 3;
Then num2 becomes 456.

Right shift (>>):


• The right-shift operation causes the operand to be shifted to the right by some bit
positions.
• The general syntax of right-shift operation is: operand >> n;
• Here, the bits in the operand are shifted to the right by n positions.
• The rightmost n bits in the original bit pattern will be lost and the leftmost n bits
empty positions will be filled with 0s.
• E.g. Let
num1 = 57; //0000 0000 0011 1001
Then if we execute the statement
num2 = num1 >> 3;
Then num2 becomes 7.

For example:
#include <stdio.h>
#include <conio.h>
main()
{
int num1 = 57;
int left, right;
left = num1 << 3;
right = num1 >> 3;
printf(“Left=> %d”, left);
printf(“\nRight=> %d”, right);
getch();
}

3. One’s Complement operator (~):


• Bitwise one’s complement operator is a unary operator which inverts all the bits of its
operand.
• All 0s become 1s and all 1s become 0s.
• E.g. Let
num1 = 57; //0000 0000 0011 1001
Then if we execute the statement

© BISHWO PRAKASH POKHAREL [40]


C Programming Language

num2 = ~num1;
Then num2 becomes 65478 //1111 1111 1100 0110

4.6 Increment or Decrement operator,


• The increment and decrement operators are: ++ and --
• The operator ++ adds 1 to the operand while the operator -- subtracts 1 from the
operand.
• These are unary operators and take the following form:
++m; or m++;
--m; or m--;
• ++m; is equivalent to m=m+1; (or m+=1;)
• --m; is equivalent to m=m-1; (or m-=1;)

For example:
#include <stdio.h>
#include <conio.h>
main()
{
int y, m=5, x, l=5;
y=++m; /*A prefix operator first adds 1 to the
printf("\n %d",m); operand and then the result is
printf("\n %d",y); assigned to the variable on left*/
x=l++; /*A postfix operator first assigns
printf("\n %d",l); the value to the variable on left,
printf("\n %d",x); and then adds 1 to the operand*/
getch();
}
Check Your Progress
1. Find the value of a in each of the following statements:
int i=3, j=4, k=8;
float a=4.5, b=6.5, c=3.5;
(a) a = b – i/k + c/k
(b) a = (b-k)/j + (j+c)/k
(c) a = c – (( i + j)/(k+i))*b
(d) a = c – i + j/k + i*b
(e) a = c + j%2 +b
(f) a = (b+1)%(c+1).
2. Find the error in the given program and explain it. Write correct program.
#include<stdio.h>
include<math.h>
main
{
float p, r, n;
printf(“Please enter a value for the principle (P):”);
scanf(“%f”, &p);
printf(“Please enter a value for the interest rate (R)”);
scanf(“%f”, &r);
printf(“Please enter a value for the number of years (n):”):
scanf(“%f”, n);

© BISHWO PRAKASH POKHAREL [41]


C Programming Language

f = p * pow + r/100),n);
printf(\n The final value (F) is: %. 2f\n”, f);
3. What are the basic four data types used in C programming? What are its size and
range? Explain.

4.7 Conditional/Ternary operator


• The operator pair “? :” is known as conditional operator.
• It has three operands, so is called ternary operator.
• The C syntax for this operator is:
exp1 ? exp2 : exp3
where exp1, exp2 and exp3 are expressions.
• Here, exp1 is evaluated first. If exp1 is true, the value of exp2 is the value of the
conditional expression. If exp1 is false, the value of exp3 is the value of the
conditional expression.

For example:
#include <stdio.h>
#include <conio.h>
main()
{
int n1,n2,larger;
printf("Enter two numbers:");
scanf("%d %d",&n1,&n2);
larger = n1>n2 ? n1 : n2;
printf("The larger number is:%d",larger);
getch();
}

4.8 Special Operators(sizeof and comma),


• C supports some special operators such as comma operator (,), sizeof operator, pointer
operators (& and *) and member selection operators (. and ->).
• We discuss comma and sizeof operator here.

Comma Operator:
• Comma operator is used to link related operations together.
• A comma-linked list of expressions are evaluated from left-to-right and the value of
right-most expression is the value of the combined expression.
• E.g. the statement
value = (x=10, y=5, x+y);
first assigns the value 10 to x, then assigns 5 to y and finally assigns 15 (i.e. 10+5) to
value.
• Since comma operator has the lowest precedence of all operators, the parentheses are
necessary.

Sizeof Operator:
• The sizeof operator is used with an operand to return the number of bytes the operand
occupies.
• It is a compile time operator.

© BISHWO PRAKASH POKHAREL [42]


C Programming Language

• The operand may be a constant, variable or a data type qualifier.


For example:
#include <stdio.h>
#include <conio.h>
main()
{
int num;
printf("integer Occupies=> %d bytes\n", sizeof(num));
printf("double Constant Occupies=> %d bytes\n", sizeof(16.18));
printf("long int Data Type Qualifier Occupies=> %d bytes\n", sizeof(15L));
printf("float Data Type Occupies=> %d bytes", sizeof(float));
getch();
}

4.9 Operator Precedence and Associativity.


Operator in the same cell are evaluated with the same precedence, in the given direction and
associativity. The C syntax i.e. grammar specifies the precedence of operators in the
evaluation of an expression. The operators written in the same line have the same priority.
The higher precedence operators are written first.
Precedence Operators Associativity
1 ++, --, +, -, !, ~, *, & sizeof right to left
2 *, / and %
3 + and -
4 ++, --
5 << and >>
6 <, <=, > and >=
left to right
7 == and !=
8 &
9 |
10 &&
11 ||
12 ?:
=, +=, -=, *=, /=, %=, <<=, right to left
13
>>=, &=, ^=, |=
14 , left to right

Expressions:
Expressions are the representation of code inside C text editor which is recognized by
compiler. An expression in C consists of syntactically valid combination of operators and
operands that computes to a value. The C expressions are not a statement. The expressions
are the basic building blocks of statement. The C expressions are slightly differ than
mathematical expressions. An expression is a combination of variables, constants and
operators written according to the syntax of C language. For example:
Algebraic expression C expression Name of expression
ab-c a*b-c arithmetic
a=b&c a=b&c logical
a=(b<c)&&(c<d) a=(a<c)&&(c<d) mixed type
3x2+2x+1 3*x^2+2*x+1 arithmetic
I=PTR/100 I=P*T*R/100 Arithmetic

© BISHWO PRAKASH POKHAREL [43]


C Programming Language

Check Your Progress


1.What is operator? List any six operators used in C-programming language. Write a
program to find least number between any two numbers using ternary operator.
2.Find the value of following expression. Use the value initially assigned to the variables
for each expressions.
int a = 8, b = 5;
float x = 0.005, y = -0.01;
1) 2 * ((a / 5) + 4 * (b – 3)) % (a + b - 2));
2) (x > y) && (a > 0) || (b < 5);
3) (a > b)?a:b;
3. Explain the relational operator and Increment/decrement operator with example.
Type casting and conversions:
The changing an entity of one data type into another is called type casting or coercion. This is
performed to take advantage of certain features of type representations. In general,
fundamental data types can be converted. The word coercion is used to denote an implicit
type casting. There are two types of casting:
i. Implicit type casting: The conversion of data is performed either during compilation or
run time is called implicit type casting. It is the automatic type conversion process
performed by compiler itself. The data can be lost during this type of type casting.
The conversion from float to int can cause lost of fractional part, double to float
causes rounding of digits and long to int can causes loss of higher order bits. For
example:
#include<stdio.h>
#include<conio.h>
main()
{
int p,t,r,I;
printf("Enter principal, time and rate:");
scanf("%d%d%d",&p,&t,&r);
i=p*t*r/100.00;
printf("%d",i);
getch();
}
Here the variables are declared as integer but in the calculation i=p*t*r/100.00, after
dividing by 100.00 the value of i will change in to float variable.
ii. Explicit type casting: Explicit type conversion can either performed by built-in
functions or by a special syntax generated by coder. These syntax changes one
data type to other by using conversion keyword. It is a secure manner of changing
variables from one data type to other. For example:
#include<stdio.h>
#include<conio.h>
main()
{
int a=97, b=65;
printf("%c%c", (char)a, (char)b); // it will print a A as output
getch();
}
Here, the ASCII value of a and A are 97 and 65 respectively. So, we print the
value after type casting from integer to character.

© BISHWO PRAKASH POKHAREL [44]


C Programming Language

CONTROL STATEMENT
CHAPTER OUTLINE
5.1 Conditional Statements,
5.2 Decision Making and Branching,
5.3 Decision Making and Looping,
5.4 Exit function,
5.5 Break and Continue.

Control Structure:
Control structures are the statements that determine the flow of control in a program and
enable us to specify the order in which the various instructions in a program are to be
executed by computer. The control structures are the very core part of programming
language. It allows the flow of control that execute based on different conditions in the
program like input taken from the user, the internal state of the machine etc.

5.1 Sequential Statements


It means executing one instruction after another, in order the source code occurs. This is
usually built into the language as a default action of C. If an instruction is not a control
statement then the next instruction is executed in sequence.
Syntax:
Start
Instruction 1
Instruction 2
……………………….
……………………………..
Instruction N
End
Flow Chart:

Start

Instruction 1

Instruction 2

Instruction N

End

© BISHWO PRAKASH POKHAREL [45]


C Programming Language

For example: WAP to read two numbers and find the sum of their square.
#include<stdio.h>
#include<conio.h>
main()
{
int a,b, sum=0;
printf("Enter two numbers:");
scanf("%d%d",&a,&b);
sum=a*a+b*b;
printf("\n The sum of square of %d and %d is : %d", a,b,sum);
getch();
}

5.2 Decision Making and Branching,


In decision control structure, different sections of code are executed depending on a specific
condition or the value of a variable. This allows a program to take different courses of action
depending on different conditions. A decision causes a one-time jump to a different part of
the program, depending on the value of an expression. There are various decision control
structures:
i. if (): It is used to execute an instruction or block of instructions only if a condition is
fulfilled.
Syntax:
if(condition)
{
statements;
}
If condition is true, then statement is executed otherwise the statement is
ignored and the program continues on the next instruction.

For example:
WAP to input a number and check whether it is odd or even.
#include<stdio.h>
#inclue<conio.h>
main()
{
int a,r;
printf("Enter a number:");
scanf("%d",&a);
r=a%2;
© BISHWO PRAKASH POKHAREL [46]
C Programming Language

if(r==0)
{
printf("\n%d is even number.",a);
}
if(r==1)
{
printf("\n%d is odd number.",a);
}
getch();
}
ii. if…else: If condition is true then if portion statements are evaluated otherwise else
part of the statement is evaluated. There are only two choices provided in the
program statement.
Syntax:
if(condition)
{
block of statement;
}
else
{
block of statement;
}
For example:
WAP to input a number and check the entered number is negative or non-
negative.
#include<stdio.h>
#include<conio.h>
main()
{
int a;
printf("Enter a number:");
scanf("%d",&a);
if(a>=0)
{
printf("\n %d is non-negative number.",a);
}
else
{
printf("\n%d is negative number.",a);
}
getch();
}
iii. Nested if….else: The if….else statement is entirely inserted inside other if or in
else block are called nested if …else statement. This types of control statement is
used to check condition within condition.
Syntax:
if(condition1)
{
if(condition2)
{

© BISHWO PRAKASH POKHAREL [47]


C Programming Language

instruction 1;
}
else
{
instruction2;
}
}
else
{
instruction3;
}

For example:
WAP to input any three numbers and find the greatest number among them.
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
printf("Enter any three numbers:");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
{
printf("%d is greatest number.",a);
}
else if(b>a && b>c)
{
printf("%d is greatest number.",b);
}
else
{
printf("%d is greatest number.",c);
}
getch();
}
iv. if…else…if….else: It is useful only when the number of choices is larger than
two then this type of if…else…if…else control structure is used. It is a multi-way
decision based conditional structure. This works by cascading of several
comparisons. As soon as one of the conditions is true, the statement or block of
statements following them is executed and no further condition is checked.
Syntax:
if(condition1)
{
block of statement1
}
else if(condition2)
{
block of statement2
}
………………………

© BISHWO PRAKASH POKHAREL [48]


C Programming Language

……………………
else
{
block of statement N
}

Example:
WAP to read 5 subject marks and calculate percentage as follows if passed.
1. Percentage >=75, Distinction with percentage
2. Percentage >=60 and <75 First division with percentage.
3. Percentage >=45 and <60 Second division with percentage.
4. Percentage >35 and <45 Pass division with percentage.
5. Otherwise Fail
#include<stdio.h>
#include<conio.h>
main()
{
float en, ec, ac, bm, co, total, per;
printf("Enter five subject marks:");
scanf("%f%f%f%f%f", &en, &ec, &ac, &bm, &co);
if(en>=35 && ec>=35 && ac>=35&& bm>=35 && co>=35)
{
total=en+ec+ac+bm+co;
per=total/5;
if(per>=75)
{
printf("\n Distinction with %.2f percentage",per);
}
else if(per>=60)
{
printf("\n First division with %.2f percentage",per);
}
else if(per>=45)
{
printf("\n Second division with %.2f percentage",per);
}
else
{
printf("\n Pass division with %.2f percentage",per);
}
}
else
{
printf("\n You are failed",per);
}
getch();
}
v. switch(): It is used to check several possible constant values for an expression. The
switch statement can be used instead of multiple if…else conditional statements. It
is mainly used to generate menu based programs.

© BISHWO PRAKASH POKHAREL [49]


C Programming Language

Syntax:
switch(expression1)
{
case 1: statements
………….
break
case 2: statements
………....
break
case N: statements
…………..
break
default: default statement
}

For example:
WAP to print names of days according as number input from keyboard such as
1 for Sunday, 2 for Monday, ……… 7 for Saturday and other for wrong input.
#include<stdio.h>
#include<conio.h>
main()
{
int a;
printf("\n Enter any number:");
scanf("%d",&a);
switch(a)
{
case 1:
{
printf("\n Today is sunday");
break;
}
case 2:
{
printf("\n Today is Monday");
break;
}
case 3:
{
printf("\n Today is Tuesday");
break;
}
case 4:
{
printf("\n Today is Wednesday");
break;
}
case 5:

© BISHWO PRAKASH POKHAREL [50]


C Programming Language

{
printf("\n Today is Thursday");
break;
}
case 6:
{
printf("\n Today is Friday");
break;
}
case 7:
{
printf("\n Today is Saturday");
break;
}
default:
{
printf("\n Invalid input");
}
}
getch();
}
Q] Write a C program to read the values of coefficients a, b and c of a quadratic
equation and find the real roots of the equation. Use if…else statement and If the roots
are imaginary, display the message “roots are imaginary”. Calculate imaginary roots
too.
#include<stdio.h>
#include<conio.h>
#include <math.h>
main()
{
float a, b, c, d, root1, root2, real, img;
printf("\nEnter values a, b and c of the quadratic equation:");
scanf("%f %f %f", &a, &b, &c);
d = b*b-4*a*c;
if(d<0)
{
printf("\n Imaginary Roots.");
d = sqrt(fabs(d)); //compute absolute value of discriminant
real = -b/(2*a);
img = d/(2*a);
printf("\nRoot1 = %.2f +i %.2f", real, img);
printf("\nRoot2 = %.2f -i %.2f", real, img);
}
else
{
printf("\n Roots are real.");
d = sqrt(d);
root1 = (-b+d)/(2*a);
root2 = (-b-d)/(2*a);
printf("\nRoot1 = %.2f \t Root2 = %.2f", root1, root2);

© BISHWO PRAKASH POKHAREL [51]


C Programming Language

}
getch();
}
Check Your Progress
1. Write a program to read two integers from keyboard and check whether the first
integer is exactly divisible by the second or not.
2. Write a program that asks a number from keyboard and tests whether it is a multiple
of 7 or not.

5.3 Looping,
It is also called repetitive or iterative control structure. It is used for execution of the same
section of code for more than once. A loop is a way of repeating a statement a number of
times. Loops are used to repeat a block of code. A loop let us write a very simple statement to
produce a significantly greater result simply by repetition. The main advantage of loop is that
it makes the program very simple and short to produce a significantly greater result simply by
repetition. C provides three looping control structure:

i. For: It is one of the broadly used loop in programming language. The execution of for
loop until the condition is true. It is a entry control loop because it checks the
condition at entry point. It doesn't execute even a single statement if the
termination condition is set false.
Syntax:
for(initialization, terminating_condition, increment/decrement)
{
block of statements
}
For example:
WAP to read your name and display it 5 times.
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char name[30];
printf("Enter your name:");
scanf("%s",&name);
for(i=0;i<5;i++)
{
printf("\n$s",name);
}
getch();
}
ii. While: It is also called entry control loop. The while loop must initialize variable
before the loop begins. The termination condition consists inside while
parentheses. The increment/decrement performed inside the body of the loop.
Syntax:
initialization
while(termination condition)
{
statements

© BISHWO PRAKASH POKHAREL [52]


C Programming Language

……
increment/decrement
}

For example:
WAP to print the number from 1 to 100.
#include<stdio.h>
#include<conio.h>
main()
{
int i;
i=1;
while(i<=100)
{
printf("%d\t",i);
i++;
}
getch();
}

iii. Do..while: This loop is an exit control loop. It runs at least once even though the
termination condition is set to false. This loop test the condition at exit point
hence it is called exit control loop.
Syntax:
initialization
do
{
statements
……….
increment/decrement
} while(termination condition)

For example:
WAP to print even numbers from 100 to 0.
#include<stdio.h>
#include<conio.h>
main()
{
int i=100;
do
{
printf("%d\t",i);
i=i-2;
}
while (i>=0);
getch();
}

© BISHWO PRAKASH POKHAREL [53]


C Programming Language

Difference between for and while loop:


for loop while loop
1.It is definite loop 1.It may be definite and may not be
definite.
2.The loop expression is within a one 2.The loop expression is scattered
block. throughout the program.
3.It used the keyword for. 3.It use the keyword while.
4.It contains three expressions. 4.It contain only one expression.
5.Syntax: 5.Syntax:
for(init; condition; inc/dec) initial value;
{ while(condition)
statements; {
} statements;
increment/decrement;
}

Difference between while and do while loop:


while loop do while loop
1.In the while loop test condition is 1.In do-while loop the test condition is
evaluated before the loop is executed. evaluated after the loop is executed.
2.It is an entry controlled loop. 2. It is an exit controlled loop.
3.It has a keyword while. 3. It has two keyword do and while.
4.Loop is not terminated with semicolon. 4. Loop is terminated with a semicolon.
5.It doesn't execute the body of loop until 5. Body of the loop will always executed at
and unless the condition is true. least once since the test condition is not
checked until the end of the loop.
6.Syntax: 6. Syntax:
initial value; initial value;
while(condition) do
{ {
statements; statements;
increment/decrement; increment/decrement;
} }while(condition);

5.4 Exit function,


This function is used to exit from the loop.
5.5 Break and Continue.
The jump statements includes break, continue and goto statements.
1. break statement:
The break statement is used to exit from a while, for, do..while or switch structure. It
can only be used inside the body of a for, while, do..while, or switch statement.

The break statement is written simply as break; without any embedded expressions or
statements. The program execution continues with the first statement after the
structure.
if(x<0)
{
printf("Value can't be negative");
break;

© BISHWO PRAKASH POKHAREL [54]


C Programming Language

}
If a break statement is used inside nested while, do..while, for or switch statements, it
will cause a transfer of control out of inner enclosing structure only.

For example:
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=1; i<=5; i++)
{
if(i==3)
break;
printf("%d", i);
}
getch();
}
Output: 1 2

2. continue statement:
It skip the remaining statements in the body of a while, for or do..while structure. It
proceeds with the next iteration of the loop. The continue statement can be included
within a while, do..while or a for statement.

It is written simply as continue; without any embedded statements or expressions.


Loop continuation test is evaluated immediately after the continue statement is
executed. But in the case of for loop, increment/decrement expression is executed,
then the loop continuation test is evaluated if increment/decrement is declared on the
same line of the loop.

Difference between break and continue:


break statement continue statement
1. The break statement is used to 1. The continue statement is used to
terminate the control from the bypass the execution of the further
switch..case structure as well in statements.
the loop.
2. When the break statement 2. When the continue statement is
encountered it terminates the encountered it bypasses single
execution of the entire loop or pass of the loop.
switch case.
3. It doesn't by pass the current loop 3. It is used to bypass the current
though it transfers the control out pass through a loop.
of the loop.
4. The loop terminates when a break 4. The loop doesn't terminate when
is encountered. continue is encountered.
5. Syntax: 5. Syntax:
break; break;

© BISHWO PRAKASH POKHAREL [55]


C Programming Language

3. goto statement:
The goto statement is used to alter the normal sequence of program execution by
transferring control to some other part of the current function. The goto statement is
written as:
goto label;
where label is an identifier that is used to label the target statement to which control
will be transferred.

Control may be transferred to any other statement within the current function. The
target statement will appear as:
label: statement
Each label statement within the current function must have a unique name. The use of
goto must be avoided because the structure theorem says there must be only one entry
point and only one exit point in a program.

However, goto can helpful when you want to exit from a doubly nested loop. This can
be done with two if-break statements, though this would be awkward.

For example:
/* A program to input a number and find out if it is even or odd using goto
statement*/
#include<stdio.h>
#include<conio.h>
main()
{
int num;
printf("Enter a number:");
scanf("%d", &num);
if(num%2==0)
goto label1;
else
goto label2;
label1:
printf("%d is even number",num);
label2:
printf("%d is odd number", num);
getch();
}
Check Your Progress
1. Write a program to read an integer number n from keyboard and display the message
“Get Well Soon” n times.
2. Write a program to calculate the factorial of a number using for loop.
3. Write a program that asks an integer number n and calculate sum of all natural
numbers from 1 to n.
4. Compute 12+22+32+…+n2 using for loop (Take n from user).

© BISHWO PRAKASH POKHAREL [56]


C Programming Language

/* Program to read a number from keyboard until a zero or negative number is entered.
Finally, calculating the sum and average of entered numbers.*/
#include<stdio.h>
#include<conio.h>
main()
{
int num, count=0;
float sum=0, avg;
do
{
printf("\n Enter number:\t");
scanf("%d", &num);
sum = sum + num;
count++;
}while(num>0);
sum=sum-num;
avg=(sum)/(count-1);
printf("\n The sum is:\t %f", sum);
printf("\n The average is:\t %f", avg);
getch();
}

The Nested Loops:


C allows loops to be nested, that is, one loop may be inside another. The program given
below illustrates the nesting of loops.

Let us consider a program to illustrate nested loops,


Write a program to generate the following pattern given below:
1
1 2
1 2 3
1 2 3 4
/* Program to print the pattern */
#include <stdio.h>
#include<conio.h>
main( )
{
int i,j;
for (i=1;i<=4;++i)
{
printf("%d\n",i);
for(j=1;j<=i;++j)
printf("%d\t",j);
}
getch();
}
Here, an inner for loop is written inside the outer for loop. For every value of i, j takes the
value from 1 to i and then value of i is incremented and next iteration of outer loop starts
ranging j value from 1 to i.

© BISHWO PRAKASH POKHAREL [57]


C Programming Language

Check Your Progress


1. Explain the Output???
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=1;i<10;i++)
{
printf("%d\t", i);
if(i==5)
{
break;
}
}
getch();
}
2. Explain the Output???
#include<stdio.h>
#include<conio.h>
main()
{
int i, j;
for(i=0;i<10;i=i+3)
{
for(j=1;j<10;j=j+2)
{
printf("%d %d\n", i, j);
break;
}
}
getch();
}

Q] Program to test whether an entered number is prime or not


#include<stdio.h>
#include<conio.h>
main()
{
int i, num;
printf("\n Enter a number:");
scanf("%d", &num);
for(i=2;i<num;i++)
{
if(num%i==0)
{
printf("\n Not Prime.");
break;
}

© BISHWO PRAKASH POKHAREL [58]


C Programming Language

}
if(i==num)
{
printf("\n Prime Number.");
}
getch();
}

Q] Program to Print even numbers only


#include<stdio.h>
#include<conio.h>
main()
{
int i, num;
printf("\n Enter a number:");
scanf("%d", &num);
printf("\n The even numbers from 2 to %d are:\n", num);
for(i=1;i<=num;i++)
{
if(i%2!=0)
{
continue;
}
printf("%d\t", i);
}
getch();
}

Q] Program to ask two numbers and display message “Either number is negative”, if
one of the numbers is negative; otherwise display message “Both numbers are positive”
*/
#include<stdio.h>
#include<conio.h>
main()
{
int i, num1, num2;
printf("Enter first no:");
scanf("%d", &num1);
if(num1<0)
{
goto negative;
}
printf("\n Enter second number:");
scanf("%d", &num2);
if(num2<0)
{
goto negative;
}
printf("\n Both numbers are positive");
getch();

© BISHWO PRAKASH POKHAREL [59]


C Programming Language

return;
negative: printf("\n Either number is negative");
getch();
}

Q] /*Program to add, subtract, multiply and divide two complex numbers using switch
statement*/
#include<stdio.h>
#include<conio.h>
main()
{
int a, b, x, y, real, img;
char opr;
printf("\n Enter first complex number of the form (a+ib):");
scanf("%d+i%d", &a, &b);
printf("\n Enter second complex number of the form (x+iy):");
scanf("%d+i%d", &x, &y);
printf("\n Enter one of the operators among +, -, *, /:\t");
scanf(" %c", &opr);
switch(opr)
{
case '+':
real = a+x;
img = b+y;
printf("\n The addition is:%d+i%d.", real, img);
break;
case '-':
real = a-x;
img = b-y;
printf("\n The subtraction is:%d+i%d.", real, img);
break;
case '*':
real = a*x-b*y;
img = a*y+b*x;
printf("\n The multiplication is:%d+i%d", real, img);
break;
case '/':
real = (a*x+b*y)/(x*x+y*y);
img = (b*x-a*y)/(x*x+y*y);
printf("\n The division is:%d+i%d", real, img);
break;
default:
printf("\n Invalid Operator.");
}
getch();
}

Q] Program for Armstrong number


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

© BISHWO PRAKASH POKHAREL [60]


C Programming Language

main()
{
int num, digit, sum=0;
int temp;
printf("\n Enter number to be checked:\t");
scanf("%d", &num);
temp=num;
while(num!=0)
{
digit = num % 10;
sum += digit*digit*digit;
num /= 10;
}
if(temp==sum)
printf("\n Armstrong Number!!!");
else
printf("Not Armstrong Number.");
getch();
}

Q] Program for reversing a number


#include<stdio.h>
#include<conio.h>
main()
{
int n, digit;
printf("\n Enter number you want to reverse:");
scanf("%d", &n);
printf("\n The reverse of the entered number is:");
while(n!=0)
{
digit=n%10;
printf("%d", digit);
n=n/10;
}
getch();
}

Q] Program to compute sum of digits of an integer


#include<stdio.h>
#include<conio.h>
main()
{
int num, rem, q, sum=0;
printf("\n Enter number to be checked:\t");
scanf("%d", &num);
do
{
q = num / 10;
rem = num % 10;

© BISHWO PRAKASH POKHAREL [61]


C Programming Language

num = q;
sum += rem;
}while(q!=0);
printf("\n The sum of digits is:\t%d", sum);
getch();
}

Q] Program to reverse a number


#include<stdio.h>
#include<conio.h>
main()
{
long int num, rev=0;
int digit;
printf("\n Enter number to be reversed:\t");
scanf("%ld", &num);
while(num!=0)
{
digit = num%10;
rev = rev*10+digit;
num = num/10;
}
printf("\n The reversed number is:%ld", rev);
getch();
}

Q] /*Program to read a number from keyboard and check whether it is a palindrome or


not*/
#include<stdio.h>
#include<conio.h>
main()
{
int num, rev=0, digit, temp;
printf("\n Enter number to be checked:\t");
scanf("%d", &num);
temp = num;
while(num!=0)
{
digit = num%10;
rev = rev*10 + digit;
num = num/10;
}
if(temp==rev)
{
printf("\n The number is a palindrome");
}
else
{
printf("\n The number is not a palindrome");
}

© BISHWO PRAKASH POKHAREL [62]


C Programming Language

getch();
}

Q] Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …


#include<stdio.h>
#include<conio.h>
main()
{
int fib1,fib2,prev,next,num;
fib1=1;
fib2=1;
prev=fib1;
printf("\n Enter number up to which you want Fibonacci sequence:\t");
scanf("%d", &num);
printf("%d", fib1);
do
{
next=fib2+prev;
prev=fib2;
fib2=next;
printf(",%d", prev);
}while(num>next);
getch();
}
Check Your Progress
1. What will be the output?
i) main()
{
int i;
for(i=0;i>0;i++) // change i=0 to 1……what happens???
{
printf("%d\n", i);
}
getch();
}

ii) main()
{
int i;
while(1)
{
printf("%d\n", i);
i++;
}
getch();
}
iii) main()
{
int i, j;
for(i=1; i<=5; i++)

© BISHWO PRAKASH POKHAREL [63]


C Programming Language

{
for(j=1; j<=i; j++)
{
printf("%d\t", i*j);
}
printf("\n");
}
getch();
}
iv) main()
{
char c='x';
switch(c)
{
case 'v':
printf("\n I am in case v.");
break;
case 'c':
printf("\n I am in case c.");
break;
case 'x':
printf("\n I am in case x.");
break;
default:
printf("\n I am in default.");
}
getch();
}

2. Problem: The following is a segment of a program:


x = 1;
y = 1;
if(n > 0)
x = x + 1;
y = y - 1;
printf(“%d %d”, x, y);
What will be the values of x and y if n assumes a value of
(a) 1
(b) 0
Q] Write a program to display data in following format and to show their sum.
1
11 21
31 41 51
61 71 81 91
#include<stdio.h>
#include<conio.h>
main()
{
int i, j=1,k;
int sum=0;

© BISHWO PRAKASH POKHAREL [64]


C Programming Language

for(i=1;i<=4;i++)
{
for(k=1;k<=i; j=j+10,k++)
printf("%d\t", j);
printf("\n");
}
for(i=1;i<100;i=i+10)
{
sum=sum + i;
}
printf("\n Sum=%d",sum);
getch();
}

The Power of C
 The following code will shut down your computer running Windows 7 in 1 minute.
 Just compile the code and run its EXE file.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf("Do you want to shutdown your computer right now(y/n)");
scanf("%c", &ch);
if(ch=='y'||ch=='Y')
system("C:\\WINDOWS\\System32\\shutdown /s");
}

© BISHWO PRAKASH POKHAREL [65]


C Programming Language

ARRAYS
CHAPTER OUTLINE
6.1 Introduction to Array,
6.2 Types of Array (Single Dimensional and Multidimensional),
6.3 Declaration and Memory Representation of Array,
6.4 Initialization of array,
6.5 Character Array and Strings,
6.6 Reading and Writing Strings,
6.7 Null Character,
6.8 String Library Functions( string length, string copy, string concatenation, string compare)

6.1 Introduction to Array,


C language provides four basic data types - int, char, float and double. These basic data types
are very useful; but they can handle only a limited amount of data. As programs become
larger and more complicated, it becomes increasingly difficult to manage the data. Variable
names typically become longer to ensure their uniqueness. And, the number of variable
names makes it difficult for the programmer to concentrate on the more important task of
correct coding. Arrays provide a mechanism for declaring and accessing several data items
with only one identifier, thereby simplifying the task of data management.

Many programs require the processing of multiple, related data items that have common
characteristics like list of numbers, marks in a course, or enrolment numbers. This could be
done by creating several individual variables. But this is a hard and tedious process. For
example, suppose you want to read in five numbers and print them out in reverse order. You
could do it the hard way as:
main()
{
int al,a2,a3,a4,a5;
scanf(“%d %d %d %d %d”,&a1,&a2,&a3,&a4,&a5);
printf(“%d %d %d %d %d”',a5,a4,a3,a2,a1);
}
Does it look good if the problem is to read in 100 or more related data items and print them in
reverse order? Of course, the solution is the use of the regular variable names a1, a2 and so
on. But to remember each and every variable and perform the operations on the variables is
not only tedious a job and disadvantageous too. One common organizing technique is to use
arrays in such situations. An array is a collection of similar kind of data elements stored in
adjacent memory locations and are referred to by a single array-name. In the case of C, you
have to declare and define array before it can be used. Declaration and definition tell the
compiler the name of the array, the type of each element, and the size or number of elements.
To explain it, let us consider to store marks of five students. They can be stored using five
variables as follows:

© BISHWO PRAKASH POKHAREL [66]


C Programming Language

int ar1, ar2, ar3, ar4, ar5;

Now, if we want to do the same thing for 100 students in a class then one will find it difficult
to handle 100 variables. This can be obtained by using an array. An array declaration uses its
size in [ ] brackets. For above example, we can define an array as:

int ar [100];

where ar is defined as an array of size 100 to store marks of integer data-type. Each element
of this collection is called an array-element and an integer value called the subscript is used to
denote individual elements of the array. An ar array is the collection of 200 consecutive
memory locations referred as below:

In the above figure, as each integer value occupies 2 bytes, 200 bytes were allocated in the
memory.

6.2 Types of Array (Single Dimensional and Multidimensional),


One dimensional (1-D) Array:
A list of items can be given one variable name using only one subscript (or dimension or
index) and such a variable is called a single-subscripted variable or a one-dimensional array.
The value of the single subscript or index from 0 to n-1 refers to the individual array
elements; where n is the size of the array.

For example: The declaration int a[4]; is a 1-D array of integer data type with 4 elements:
a[0], a[1], a[2] and a[3].

Multidimensional array:
 Multidimensional arrays are those having more than one dimension. Multidimensional
arrays are defined in the same way as one dimensional arrays, except that a separate
pair of square brackets is required for each subscript or dimension or index.
 Thus a 2-D (two dimensional) array requires two pairs of square brackets, a 3-D array
requires three pairs of square brackets and so on.
 Syntax for defining multidimensional array is:
storage_class data_type array_name[dim1][dim2]…[dimN];

Here, dim1, dim2,…,dimN are positive valued integer expressions that indicate the number of
array elements associated with each subscript. Thus, total no. of
elements=dim1*dim2*…*dimN

For E.g.
int survey[3][5][12];
Here, survey is a 3-D array that can contain 3*5*12=180 integer type data. This array survey
may represent a survey data of rainfall during last three years (2009,2010,2011) from months
Jan. to Dec. in five cities. Its individual elements are from survey[0][0][0] to
survey[2][4][11].

© BISHWO PRAKASH POKHAREL [67]


C Programming Language

 E.g.
int matrix[2][3];
Here, matrix is a 2-D array that can contain 2*3=6 elements. This array matrix can represent
a table having 2 rows and 3 columns from matrix[0][0] to matrix[1][2].
Column1 Column2 Column3
Row1 matrix[0][0] matrix[0][1] matrix[0][2]
Row2 matrix[1][0] matrix[1][1] matrix[1][2]

6.3 Declaration and Memory Representation of Array,


Declaration of 1-D Array:
 Syntax:
storage_class data_type array_name[size];
 storage_class refers to the storage class of the array. It may be auto, static, extern and
register. It is optional. (Will be studied later!!)
 data_type is the data type of array. It may be int, float, char,…, etc. (Note: An int type array
stores all data items of integer type.)
 array_name is the name of the array. Any valid name of a variable can be provided.
 size of the array is the number of elements in the array and is mentioned within square
bracket. The size must be an integer constant like 100 or a symbolic constant (if symbolic
constant size is defined as #define SIZE 100, then array can be defined as int a[SIZE];)

Examples:
 long marks[8]; i.e. marks is a long integer array of size 8. It can store 8 long values in
marks[0], marks[1],…, marks[7].
 float salary[50]; i.e. salary is a float array of size 50. It can store 50 fractional numbers in
salary[0], salary[1],…, salary[49].
 char name[10]; i.e. name is a character array of size 10. It can store 10 characters.
Note: “character array is also known as string”

Declaration of 2D array:
You can declare an array of two dimensions as follows:

datatype array_name[size1][size2];

In the above example, variable_type is the name of some type of variable, such as int. Also,
size1 and size2 are the sizes of the array’s first and second dimensions, respectively. Here is
an example of defining an 8-by-8 array of integers, similar to a chessboard. Remember,
because C arrays are zero-based, the indices on each side of the chessboard array run 0
through 7, rather than 1 through 8. The effect is the same: a two-dimensional array of 64
elements.

int chessboard [8][8];

To pinpoint an element in this grid, simply supply the indices in both dimensions.

6.4 Initialization of array,


Initialization of 1-D Array:
 In an uninitialized array (declared only), the individual array elements contain
garbage values.
 Assigning specific values to the individual array elements, at the time of array
declaration, is known as array initialization.

© BISHWO PRAKASH POKHAREL [68]


C Programming Language

 Since an array has multiple elements, braces are used to denote the entire array and
commas are used to separate the individual values assigned to the individual elements
in the array.
 The syntax for array initialization is:
storage_class data_type array_name[size]={value1, value2,…, valueN};
where, value1 is value of first element, value2 is value of second element and so on.

E.g.
int a[5]={21, 13, 54, 5, 101};
Here, a is an integer type array which has 5 elements. Their values are initialized to 21, 13,
54, 5 and 101 (i.e. a[0]=21, a[1]=13, a[2]=54, a[3]=5 and a[4]=101). These array elements
are stored sequentially in separate memory locations.
 Note:
int b[]={12, 75, 321};
Here, size of array b is not given, the compiler can automatically set its size according to
the number of values given. Thus, the size of array b is 3 with its elements b[0], b[1] and
b[2] initialized to values 12, 75, and 321 respectively. Therefore,
int b[]={12, 75, 321}; ≡ int b[3]={12, 75, 321};
 Note:
int c[10]={6 , 7, 12, 43, 0};
Here, size of array c is 10 but only 5 elements are assigned values at the time of
initialization. In this case, all individual elements that are not assigned values contain zero
as initial values. Thus, the value of c[5], c[6], c[7], c[8] and c[9] is zero.

Example: WAP to read 10 integers, store it in array and display them.


#include<stdio.h>
#include<conio.h>
main()
{
int p, a[10];
printf("\n Enter 10 numbers:");
for(p=0;p<10;p++)
{
scanf("%d",&a[p]);
}
printf("\n The numbers are:");
for (p=0;p<10;p++)
{
printf("%d\t",a[p]);
}
getch();
}
Q] WAP to input the n numbers and sort them in descending order.
#include<stdio.h>
#include<conio.h>
main()
{
int nums[100], i, j, n, temp;
printf("\nHow many numbers you want to sort?:\t");
scanf("%d", &n);

© BISHWO PRAKASH POKHAREL [69]


C Programming Language

for(i=0;i<n;i++)
scanf("%d", &nums[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(nums[i]>nums[j])
{
temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
}
printf("\nThe numbers in ascending order are:\n");
for(i=0;i<n;i++)
printf("\t%d", nums[i]);
getch();
}

How sorting works?


Example:
Let's use the following unsorted array: 6, 3, 1, 8, 2, 4
We would like the array to look like this: 1, 2, 3, 4, 6, 8
On the first pass, we'll compare the numbers one at a time, and we know that after one pass
we should have the smallest number all the way to the left, so in this case, that will be 1.
For our example, the ^ sign will point to the spot in the array that we are currently
examining.
6, ^3, 1, 8, 2, 4
 Pass 1, Step 1) Compare the 6 and the 3. 6 is greater than 3, so we'll swap them.
3, 6, ^1, 8, 2, 4
 Pass 1, Step 2) Compare the 3 and the 1. 3 is greater than 1, so we'll swap them.
1, 6, 3, ^8, 2, 4
 Pass 1, Step 3) Compare the 1 and the 8. 1 is less than 8, so nothing happens.
1, 6, 3, 8, ^2, 4
 Pass 1, Step 4) Compare the 1 and the 2. 1 is less than 2, so nothing happens.
1, 6, 3, 8, 2, ^4
 Pass 1, Step 5) Compare the 1 and the 4. 1 is less than 4, so nothing happens.
1, 6, 3, 8, 2, 4
 And we're done with the first pass!
 1, 6, 3, 8, 2, 4 is hardly a sorted array, but we can see that, as promised, the 1 is on the
left of the array. Trace yourself what the array looks like after each of the 5 passes.
 Pass 2: 1, 2, 6, 8, 3, 4
Pass 3: 1, 2, 3, 8, 6, 4
Pass 4: 1, 2, 3, 4, 8, 6
Pass 5: 1, 2, 3, 4, 6, 8 //sorting complete

© BISHWO PRAKASH POKHAREL [70]


C Programming Language

Initialization of two-dimensional arrays:


If you have an m x n array, it will have m * n elements and will require m*n*elementsize
bytes of storage. To allocate storage for an array you must reserve this amount of memory.
The elements of a two-dimensional array are stored row wise. If table is declared as:
int table [ 2 ] [ 3 ] = { 1,2,3,4,5,6 };
It means that element table
[0][0] = 1;
table [0][1] = 2;
table [0][2] = 3;
table [1][0] = 4;
table [1][1] = 5;
table [1][2] = 6;

Example: WAP to read a matrix, store it in array and display it.


#include<stdio.h>
#include<conio.h>
main()
{
int p,q,matrix[3][4];
printf("\n Enter a matrix of 3x4:\n\n");
for(p=0;p<3;p++)
{
for(q=0;q<4;q++)
{
scanf("%d",&matrix[p][q]);
}
}
printf("\n The elements of matrix are:\n\n");
for(p=0;p<3;p++)
{
for(q=0;q<4;q++)
{
printf("%d\t",matrix[p][q]);
}
printf("\n");
}
getch();
}
Q] Program to read a matrix of size M*N from user and display it on screen
#include<stdio.h>
#include<conio.h>
#define M 2
#define N 4
main()
{
int matrix[M][N], i, j;
printf("\nEnter the matrix elements:\t");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)

© BISHWO PRAKASH POKHAREL [71]


C Programming Language

{
scanf("%d", &matrix[i][j]);
}
}
printf("\nThe entered matrix is:\n");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
getch();
}

Q] Program to read two M*N matrices and display their sum/difference*/


#include <stdio.h>
#include <conio.h>
#define M 3
#define N 3
main()
{
int matrix1[M][N], matrix2[M][N], sum[M][N], i, j;
printf("\nEnter the elements of first matrix:\t");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
scanf("%d", &matrix1[i][j]);
}
}
printf("\nThe first matrix is:\n");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("%d\t", matrix1[i][j]);
}
printf("\n");
}
printf("\nEnter the elements of second matrix:\t");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
scanf("%d",&matrix2[i][j]);
}
}
printf("\nThe second matrix is:\n");

© BISHWO PRAKASH POKHAREL [72]


C Programming Language

for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("%d\t",matrix2[i][j]);
}
printf("\n");
}
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
sum[i][j]=matrix1[i][j]+matrix2[i][j];
}
}
printf("\nThe sum of the matrices is:\n");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("\t%d", sum[i][j]);
}
printf("\n");
}
getch();
}

Q] Program to find transpose of a matrix


#include <stdio.h>
#include <conio.h>
#define M 3
#define N 3
main()
{
int matrix[M][N],transpose[N][M],i,j;
printf("\nEnter the elements of matrix:\t");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
scanf("%d", &matrix[i][j]);
}
}
printf("\nThe matrix to be transposed is:\n");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("%d\t", matrix[i][j]);
}

© BISHWO PRAKASH POKHAREL [73]


C Programming Language

printf("\n");
}
/*finding transpose matrix*/
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
transpose[j][i]=matrix[i][j];
}
}
printf("\nThe transpose matrix is:\n");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("%d\t",transpose[i][j]);
}
printf("\n");
}
getch();
}

Q] Program to find the sum of squares in a diagonal of a square matrix


#include <stdio.h>
#include <conio.h>
main()
{
int matrix[10][10],i,j,sum=0,M,N;
printf("\nEnter order of square matrix (less than 10*10):\t");
scanf("%d %d",&M,&N);
if(M>10 || N>10)
{
printf("\nThe order is out of range.\n");
getch();
exit();
}
if(M!=N)
{
printf("Not square matrix.\n");
getch();
exit();
}
printf("\nEnter the elements of matrix:\t");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
scanf("%d",&matrix[i][j]);
}
}

© BISHWO PRAKASH POKHAREL [74]


C Programming Language

printf("\nThe matrix is:\n");


for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("%d\t",matrix[i][j]);
}
printf("\n");
}
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
if(i==j)
sum = sum + matrix[i][j]*matrix[i][j];
}
}
printf("\nThe sum of squares of elements on a diagonal is:%d", sum);
getch();
}

Q] /*Program to compute the product of two matrices if possible*/


#include <stdio.h>
#include <conio.h>
main()
{
int matrix1[10][10],matrix2[10][10],i,j,k,product[10][10],M,N,P,Q;
int row_mul_col=0;
printf("\nEnter order of first matrix (less than 10*10):\t");
scanf("%d %d",&M,&N);
printf("\nEnter order of second matrix (less than 10*10):\t");
scanf("%d %d",&P,&Q);
if(N!=P)
{
printf("\nThe matrices are unsuitable for multiplication.\n");
getch();
exit();
}
printf("\nEnter the elements of first matrix:\t");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
scanf("%d",&matrix1[i][j]);
}
}
printf("\nThe first matrix is:\n");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)

© BISHWO PRAKASH POKHAREL [75]


C Programming Language

{
printf("%d\t",matrix1[i][j]);
}
printf("\n");
}
printf("\nEnter the elements of second matrix:\t");
for(i=0;i<P;i++)
{
for(j=0;j<Q;j++)
{
scanf("%d",&matrix2[i][j]);
}
}
printf("\nThe second matrix is:\n");
for(i=0;i<P;i++)
{
for(j=0;j<Q;j++)
{
printf("%d\t",matrix2[i][j]);
}
printf("\n");
}
/*multiply two matrices*/
for(i=0;i<M;i++) //first row
{
for(j=0;j<Q;j++) //second col
{
for(k=0;k<N;k++) //first col
{
row_mul_col += matrix1[i][k]*matrix2[k][j];
}
product[i][j]=row_mul_col;
row_mul_col=0;
}
}
printf("\nThe matrix after multiplication is:\n");
for(i=0;i<M;i++)
{
for(j=0;j<Q;j++)
{
printf("%d\t",product[i][j]);
}
printf("\n");
}
getch();
}

© BISHWO PRAKASH POKHAREL [76]


C Programming Language

6.5 Character Array and Strings,


Strings in C are group of characters, digits, and symbols enclosed in quotation marks or
simply we can say the string is declared as a “character array”. The end of the string is
marked with a special character, the ‘\0’ (Null character), which has the decimal value 0.
There is a difference between a character stored in memory and a single character string
stored in a memory. The character requires only one byte whereas the single character string
requires two bytes (one byte for the character and other byte for the delimiter).

Declaration of strings:
A string in C is simply a sequence of characters. To declare a string, specify the data type as
char and place the number of characters in the array in square brackets after the string name.
The syntax is shown as below:
char string-name[size];

For example,
char name[20];
char address[25];
char city[15];

Initialization of strings:
The string can be initialized as follows:

char name[ 8] = {‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’, ‘\0’};

Each character of string occupies 1 byte of memory (on 16 bit computing). The size of
character is machine dependent, and varies from 16 bit computers to 64 bit computers. The
characters of strings are stored in the contiguous (adjacent) memory locations.

The C compiler inserts the NULL (\0) character automatically at the end of the string. So
initialization of the NULL character is not essential.

Array of strings:
Array of strings are multiple strings, stored in the form of table. Declaring array of strings is
same as strings, except it will have additional dimension to store the number of strings.
Syntax is as follows:

char array-name[size][size];

For example,
char names[5][10];

where names is the name of the character array and the constant in first square brackets will
gives number of string we are going to store, and the value in second square bracket will
gives the maximum length of the string.

For example:
char names [3][10] = {“martin”, “phil”, “collins”};

© BISHWO PRAKASH POKHAREL [77]


C Programming Language

It can be represented by a two-dimensional array of size[3][10] as shown below:

6.6 Reading and Writing Strings,


Reading strings from terminal:
 The input function scanf can be used with %s format specification to read in a string
of characters.
 E.g.
char name[20];
scanf(“%s”, name);
 No ampersand(&) is required before variable name.
 Problem:
“scanf() terminates its input on the first white space it encounters”

#include<stdio.h>
#include<conio.h>
main()
{
char name[20];
printf("\n Enter your name:");
scanf("%s", name);
printf("\n Your name is %s", name);
getch();
}
 Some versions of scanf() support the following conversion specification for strings:
%[characters]
%[^characters]
 The specification %[characters] means that only the characters specified within the
brackets are allowed in the input of string. If the input string contains any other
characters, the reading of string will be terminated at the first encounter of such a
character.
 The specification %[^characters] means that the characters specified after the caret(^)
are not allowed in the string and reading will be terminated.

Writing strings to screen:


 The printf() function with %s format is used to print strings to the screen.
 The format %s can be used to display an array of characters that is terminated by the
null character.
 E.g.
char name[25]=“Bishwo Prakash Pokharel”;
printf(“%s”, name);
 The format specification for outputting strings is of the form,
% w.p s
where w specifies the field width for display and p instructs that only the first p
characters of the string are to be displayed.

© BISHWO PRAKASH POKHAREL [78]


C Programming Language

 By default, the display is right-justified.


 When the field width is less than the length of the string, the entire string is printed.
 The integer value on the right side of the decimal point specifies the number of
characters to be printed.
 When the number of characters to be printed is specified as zero, nothing is printed.
 The minus sign in the specification causes the string to be printed left-justified.
 The specification %.ns prints the first n characters of the string (left-justified).

Using gets() and puts() function:


 The gets() function is used to read a string of text, containing whitespaces, until a
newline character is encountered.
 Syntax: gets(variable_name);
 It takes a string from user and stores in a string variable variable_name.
 The puts() function is used to display the string onto the screen.
 Syntax: puts(variable_name);

#include<stdio.h>
#include<conio.h>
main()
{
char text[100];
printf("\n Write whatever:\t");
gets(text);
printf("\n You have typed:\t");
puts(text);
getch();
}

Counting length of strings:


#include <stdio.h>
#include <conio.h>
main()
{
char input_string[50];
int i=0, length=0;
printf("\nEnter your text:\t");
gets(input_string);
while(input_string[i]!='\0')
{
length++;
i++;
}
printf("\nThe length of your text is: %d character(s)", length);
getch();
}

Using strlen() function:


 The function strlen() returns an integer which denotes the length of the string passed
into the function.

© BISHWO PRAKASH POKHAREL [79]


C Programming Language

 The length of the string is defined as the number of characters present in the string,
excluding the null character.
 Syntax:
integer_variable=strlen(input_string);
 Use header file <string.h>.

#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char input_string[50];
int length;
printf("\n Enter your text:\t");
gets(input_string);
length=strlen(input_string);
printf("\n The length of your text is: %d character(s)", length);
getch();
}

Program: WAP to read string from keyboard and count the number of vowels, consonants,
spaces, semicolons and commas in that string.
#include<stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char s[80];
int len, i, space=0, vowel=0, consonant=0, semicolon=0, comma=0;
printf("Enter string:\t");
gets(s);
len=strlen(s);
for(i=0;i<len;i++)
{
if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u')
vowel++;
else if(s[i]==';')
semicolon++;
else if(s[i]==',')
comma++;
else if(s[i]==' ')
space++;
else
consonant++;
}
printf("\n The number of vowel(s):%d", vowel);
printf("\n The number of semicolon(s):%d", semicolon);
printf("\n The number of comma(s):%d", comma);
printf("\n The number of space(s):%d", space);
printf("\n The number of consonant(s):%d", consonant);

© BISHWO PRAKASH POKHAREL [80]


C Programming Language

getch();
}

Q] /*Program to read your name from keyboard and output a list of ASCII codes that
represent your name*/
#include <stdio.h>
#include <conio.h>
#include<string.h>
main()
{
char name[30];
int len, i;
printf("Enter your name:\t");
gets(name);
len=strlen(name);
printf("\n The ASCII values of characters in the name %s are:\n", name);
for(i=0;i<len;i++)
printf("%c = %d\n", name[i], name[i]);
getch();
}

6.7 Null Character


Null characters are represented by '\0'.

6.8 String Library Functions


The header file <string.h> contains some string manipulation functions. The following is a
list of the common string managing functions in C.

strlen():
The strlen function returns the length of a string. It takes the string name as argument. The
syntax is as follows: n = strlen (str);
where str is name of the string and n is the length of the string, returned by strlen function.

For example: Write a program to read a string from the keyboard and to display the length of
the string on to the monitor by using strlen( ) function.
/* Program to illustrate the strlen function to determine the length of a string */
#include <stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char name[80];
int length;
printf(“Enter your name: ”);
gets(name);
length = strlen(name);
printf(“Your name has %d characters\n”, length);
getch();
}

© BISHWO PRAKASH POKHAREL [81]


C Programming Language

OUTPUT
Enter your name: BISHWO
Your name has 6 characters

strcpy:
In C, you cannot simply assign one character array to another. You have to copy element by
element. The string library <string.h> contains a function called strcpy for this purpose. The
strcpy function is used to copy one string to another. The syntax is as follows:
strcpy(str1, str2);
where str1, str2 are two strings. The content of string str2 is copied on to string str1.

Example:
Write a program to read a string from the keyboard and copy the string onto the second string
and display the strings on to the monitor by using strcpy( ) function.
/* Program to illustrate strcpy function*/
#include <stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char first[80], second[80];
printf(“Enter a string: ”);
gets(first);
strcpy(second, first);
printf(“\n First string is : %s, and second string is: %s\n”, first, second);
getch();
}
OUTPUT
Enter a string: PUSHPA
First string is: PUSHPA, and second string is: PUSHPA

Another technique:
#include<stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char copy[50], paste[50];
int i;
printf("\n Enter your name (to copy):\t");
gets(copy);
for(i=0;copy[i]!='\0';i++)
{
paste[i]=copy[i];
}
paste[i]='\0';
printf("\n The name is (pasted as):\t");
puts(paste);
getch();

© BISHWO PRAKASH POKHAREL [82]


C Programming Language

strcmp:
The strcmp function in the string library function which compares two strings, character by
character and stops comparison when there is a difference in the ASCII value or the end of
any one string and returns ASCII difference of the characters that is integer. If the return
value zero means the two strings are equal, a negative value means that first is less than
second, and a positive value means first is greater than second. The syntax is as follows:
n = strcmp(str1, str2);
where str1 and str2 are two strings to be compared and n is returned value of differed
characters.

For example:
Write a program to compare two strings using string compare function.
/* The following program uses the strcmp function to compare two strings. */
#include <stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char first[80], second[80];
int value;
printf(“Enter a string: ”);
gets(first);
printf(“Enter another string: ”);
gets(second);
value = strcmp(first,second);
if(value == 0)
puts(“The two strings are equal”);
else if(value < 0)
puts(“The first string is smaller ”);
else if(value > 0)
puts(“the first string is bigger”);
getch();
}

OUTPUT
Enter a string: HARI
Enter another string: RAMAN
The first string is smaller

strcat:
The strcat function is used to join one string to another. It takes two strings as arguments; the
characters of the second string will be appended to the first string. The syntax is as follows:
strcat(str1, str2);
where str1 and str2 are two string arguments, string str2 is appended to string str1.

Example:
Write a program to read two strings and append the second string to the first string.

© BISHWO PRAKASH POKHAREL [83]


C Programming Language

/* Program for string concatenation*/


#include <stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char first[80], second[80];
printf(“Enter a string:”);
gets(first);
printf(“Enter another string: ”);
gets(second);
strcat(first, second);
printf(“\nThe two strings joined together: %s\n”, first);
getch();
}
OUTPUT
Enter a string: BISHWO
Enter another string: PRAKASH
The two strings joined together: BISHWOPRAKASH

strlwr:
The strlwr function converts upper case characters of string to lower case characters. The
syntax is as follows:
strlwr(str1);
where str1 is string to be converted into lower case characters.

Example:
Write a program to convert the string into lower case characters using in-built function.
/* Program that converts input string to lower case characters */
#include <stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char first[80];
printf("Enter a string: ");
gets(first);
printf("Lower case of the string is %s”, strlwr(first));
getch();
}
OUTPUT
Enter a string: SADHANA
Lower case of the string is sadhana

strrev:
The strrev funtion reverses the given string. The syntax is as follows:
strrev(str);
where string str will be reversed.

© BISHWO PRAKASH POKHAREL [84]


C Programming Language

Example:
Write a program to reverse a given string.
/* Program to reverse a given string */
#include <stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char first[80];
printf(“Enter a string:”);
gets(first);
printf(“\n Reverse of the given string is : %s ”, strrev(first));
getch();
}

OUTPUT
Enter a string: NISHA
Reverse of the given string is: AHSIN

strupr:
The strupr function converts lower case characters of the string to upper case characters. The
syntax is as follows:
strupr(str1);
where str1 is string to be converted into upper case characters.

Summary:

Q] WAP to reverse a string without string handling function:


#include <stdio.h>
#include <conio.h>
main()
{
char string[25], reverse_string[25];
int length, i, j;

© BISHWO PRAKASH POKHAREL [85]


C Programming Language

printf("\n Input string to be reversed:");


gets(string);
length=strlen(string);
for(j=0,i=length-1;j<length;j++,i--)
reverse_string[j]=string[i];
reverse_string[j]='\0';
puts(reverse_string);
getch();
}

Q] WAP to count number of words in a sentence.


#include<stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char sentence[80];
int i, words=1;
printf("Enter text:");
gets(sentence);
for(i=0;sentence[i]!='\0';i++)
{
if(sentence[i]==' '||sentence[i]=='\t')
words++;
}
printf("\n The number of words=%d", words);
getch();
}

Q] /*Program to sort name of 5 persons in ascending order*/


#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char names[5][10],temp[10];
int i, j;
printf("\n Enter name of 5 persons:");
for(i=0;i<5;i++)
gets(names[i]);
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(strcmp(names[i], names[j])>0)
{
strcpy(temp, names[i]);
strcpy(names[i], names[j]);
strcpy(names[j], temp);
}

© BISHWO PRAKASH POKHAREL [86]


C Programming Language

}
}
printf("\nNames in ascending order:\n");
for(i=0;i<5;i++)
puts(names[i]);
getch();
}

Check Your Progress


What is the output?
#include <stdio.h>
#include <conio.h>
void main()
{
char s[]="Nepal";
clrscr();
printf("%s", s);
printf("%c", s[4]);
printf("%s\r%c", s, s[4]);
getch();
}

Q] Write a program that reads character and perform following operation according to
the choice inputted by the user.
a. Display it is numeric character or alphabetic character.
b. Display the ASCII value of the character.
c. Display the character in uppercase if it is alphabetic character.

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char c, ch;
printf("\n Enter the character:\t");
scanf("%c", &c);
printf("\n What do you want to do?");
printf("\n a--Display it is numeric character or alphabet");
printf("\n b--Display the ASCII value of the character");
printf("\n c--Display character in uppercase if it is alphabet");
printf("\n Enter a,b or c:\t");
scanf(" %c", &ch);
switch(ch)
{
case 'a':
if((c>=65 && c<=90) || (c>=97 && c<=122))
printf("\n It is an alphabetic character.");
else if(c>=48 && c<=57)

© BISHWO PRAKASH POKHAREL [87]


C Programming Language

printf("\nIt is a numeric character");


else
printf("\n Neither numeric nor alphabetic character");
break;
case 'b':
printf("\n The ASCII value of the character %c is %d", c, c);
break;
case 'c':
if((c>=65 && c<=90) || (c>=97 && c<=122))
printf("The uppercase equivalent of alphabet=%c", toupper(c));
break;
default:
printf("\n You entered wrong option.");
}
getch();
}

© BISHWO PRAKASH POKHAREL [88]


C Programming Language

FUNCTIONS
CHAPTER OUTLINE
7.1 Library Functions,
7.2 User defined functions,
7.3 Funciton prototype, Function call, and Function Definition,
7.4 Nested and Recursive Function,
7.5 Function Arguments and Return Types,
7.6 Passing Arrays to Function,
7.7 Passing Strings to Function,
7.8 Passing Arguments by Value,
7.9 Passing Arguments by Address,
7.10 Scope visibility and lifetime of a variable,
7.11 Local and Global Variable,
7.1 Library Functions,
Introduction to function:
A function is a self- contained block of executable code that can be called from any other
function .In many programs, a set of statements are to be executed repeatedly at various
places in the program and may with different sets of data, the idea of functions comes in
mind. You keep those repeating statements in a function and call them as and when required.
When a function is called, the control transfers to the called function, which will be executed,
and then transfers the control back to the calling function (to the statement following the
function call). Let us see an example as shown below:

/* Program to illustrate a function*/


#include <stdio.h>
#include<conio.h>
main ()
{
void sample( );
printf(“\n You are in main”);
getch();
}
void sample( )
{
printf(“\n You are in sample”);
}

OUTPUT
You are in sample
You are in main

© BISHWO PRAKASH POKHAREL [89]


C Programming Language

Here we are calling a function sample ( ) through main( ) i.e. control of execution transfers
from main( ) to sample( ) , which means main( ) is suspended for some time and sample( ) is
executed. After its execution the control returns back to main( ), at the statement following
function call and the execution of main( ) is resumed.

Syntax:
return data type function_name (list of arguments)
{
datatype declaration of the arguments;
executable statements;
return (expression);
}
where,
 return data type is the same as the data type of the variable that is returned by the
function using return statement.
 a function_name is formed in the same way as variable names / identifiers are
formed.
 the list of arguments or parameters are valid variable names as shown below,
separated by commas: (data type1 var1,data type2 var2,…….. data type n var n)
for example (int x, float y, char z).
 arguments give the values which are passed from the calling function.
 the body of function contains executable statements.
 the return statement returns a single value to the calling function.

Library Functions:
Library functions (Built-in functions) are provided in the programming language and we can
directly use them as required. However, the function’s name, return type, number of
arguments and types must be known in advance. For e.g. printf(), scanf(), sqrt(), getch(), etc.
7.2 User defined functions,
 User-defined functions: These functions are written by the user. The user selects the
name of the function, return type, number of arguments and types.
 Note: main() is a user defined function. However the name of the function is defined
or fixed by the programming language.

7.3 Function prototype, Function call, and Function Definition,


Function definition:
 The collection of program statements that describes the specific task to be done by the
function is called a function definition.
 Function definition consists of function header (function’s name, return type, and
number and types of arguments) and function body (block of code or statements
enclosed in parentheses).
 Syntax:
return_type function_name(data_type variable1, …,data_type variableN)
{
…………………;
…………………;
statements;
}
 return_type is optional. The default value is integer.

© BISHWO PRAKASH POKHAREL [90]


C Programming Language

 Whenever return_type is provided, a value must be returned using return statement


except for void case.
 function_name is a user-defined name given to the function. (Same as identifier
naming)
 variable1, …,variableN are called formal arguments or formal parameters that are
passed to the function. Also these are local variables for the function.

Example of function definition:


#include <stdio.h>
#include<conio.h>
int add(int c, int d)
{
int sum;
sum = c+d;
return sum;
}
main()
{
………;
}

Calling function through main():


 A function can be called by specifying the function’s name, followed by a list of
arguments enclosed in parentheses and separated by commas.
 For example, the function add() can be called with two arguments from main()
function as:
add(a, b);
 These arguments appearing in the function call are called actual arguments or actual
parameters.
 In this case, main() is called calling function and add() is called called function.

Note:
 In function call, there must be one actual argument for each formal argument. This is
because the value of actual argument is transferred into the function and assigned to
the corresponding formal argument.
 If a function returns a value, the returned value can be assigned to a variable of data
type same as return type of the function to the calling function.
 When a function is called, the program control is passed to the function and once the
function completes its task, the program control is transferred back to the calling
function.

#include <stdio.h>
#include <conio.h>
int add(int, int);
main()
{
int a=50,b=100, x;
x=add(a, b);
printf(“%d”, x);
getch();

© BISHWO PRAKASH POKHAREL [91]


C Programming Language

}
int add(int c, int d)
{
int sum;
sum = c+d;
return sum;
}
Function prototype or declaration:
 The function prototype is a model or blueprint of the function.
 The function prototype is necessary if a function is used before function is defined.
 When a user-defined function is defined before the use, function prototype is not
necessary (may be given though).
 Syntax:
return_type function_name(data_type1, …,data_typeN);
 E.g.
void add(int, int);

For example:
#include <stdio.h>
#include <conio.h>
int add(int, int); //Function Prototype
main()
{
int a=12,b=5,x;
x=add(a,b);
printf("%d",x);
getch();
}
int add(int c, int d)
{
int sum;
sum=c+d;
return sum;
}

The return statement:


The return statement serves two purposes:
1. It immediately transfers the control back to the calling function (i.e. no statements
within the function body after the return statement are executed).
2. It returns the value to the calling function.

Syntax:
return (expression);
where expression, is optional and, if present, it must evaluate to a value of the data type
specified in the function header for the return_type.
Note: When nothing is to be returned, the return_type in the function definition is specified as
void. For void return_type, return statement is optional.

© BISHWO PRAKASH POKHAREL [92]


C Programming Language

Function parameters:
 Function parameters are the means for communication between the calling and the
called functions.
 Two types: formal parameters and actual parameters.
 Formal parameters are given in the function definition while actual parameters are
given in the function call.
 The name of formal and actual parameters need not be same but data types and the
number of parameters must match.
Check Your Progress
1. Write functions to add, subtract, multiply and divide two numbers a and b.

Q] /*Program using function to find the greatest number among three numbers*/
#include <stdio.h>
#include <conio.h>
int greater(int, int);
main()
{
int a, b, c, d, e;
printf("\n Enter three numbers:");
scanf("%d %d %d",&a,&b,&c);
d=greater(a, b);
e=greater(d, c);
printf("\n The greatest number is:%d", e);
getch();
}
int greater(int x, int y)
{
if(x>y)
return x;
else
return y;
}
Check Your Progress
1. Write a function which receives a float number and an integer number from main(),
finds the product of these two and returns the product which is printed in main().
2. Write a function AreaOfCircle() which accepts radius of float value and returns the
area of the circle. Use this function to calculate area of two circles having different
radii. (Use symbolic constant to define PI)

Q] Write and test the following power() function that returns x raised to the power n,
where n can be any integer:
double power (double x, int p)
#include <stdio.h>
#include <conio.h>
double power(double x, int p)
{
double a=1;
if(p==0)
return 1;
else if(p>0)

© BISHWO PRAKASH POKHAREL [93]


C Programming Language

{
while(p!=0)
{
a=a*x;
p--;
}
return a;
}
else
{
while(p!=0)
{
a=a/x;
p++;
}
return a;
}
}

main()
{
int p;
double x, z;
printf("Enter x and p:\t");
scanf("%lf %d", &x, &p);
z=power(x, p);
printf("\n x raised to power n is:%lf", z);
getch();
}

7.4 Nested and Recursive Function,


Within a function body, if the function calls itself, the mechanism is known as ‘Recursion’
and the function is known as ‘Recursive function’. Now let us study this mechanism in detail
and understand how it works.
• As we see in this mechanism, a chaining of function calls occurs, so it is necessary for
a recursive function to stop somewhere or it will result into infinite callings. So the
most important thing to remember in this mechanism is that every “recursive
function” should have a terminating condition.
• Let us take a very simple example of calculating factorial of a number, which we all
know is computed using this formula 5! = 5*4*3*2*1
• First we will write non – recursive or iterative function for this.

Example:
Write a program to find factorial of a number
#include <stdio.h>
#include<conio.h>
main ()
{
int n, factorial;

© BISHWO PRAKASH POKHAREL [94]


C Programming Language

int fact(int);
printf (“Enter any number:\n” );
scanf ("%d", &n);
factorial = fact ( n); /* function call */
printf (“Factorial is %d\n”, factorial);
}
/* Non recursive function of factorial */
int fact (int n)
{
int res = 1, i;
for (i = n; i >= 1; i--)
res = res * i;
return (res);
}
OUTPUT
Enter any number: 5
Factorial is 120

How it works?
Suppose we call this function with n = 5
Iterations:
1. i= 5 res = 1*5 = 5
2. i= 4 res = 5*4 = 20
3. i= 3 res = 20*4 = 60
4. i= 2 res = 60*2 = 120
5. i= 1 res = 120*1 = 120

Now let us write this function recursively. Before writing any function recursively, we first
have to examine the problem, that it can be implemented through recursion.
For instance, we know n! = n* (n − 1)! (Mathematical formula)
Or fact (n) = n*fact (n-1)
Or fact (5) = 5*fact (4)
That means this function calls itself but with value of argument decreased by ‘1’

Modifying the above program using recursion:


/*Program to find factorial using recursion*/
#include<stdio.h>
#include<conio.h>
main()
{
int n, factorial;
int fact(int);
printf("Enter any number: \n" );
scanf("%d",&n);
factorial = fact(n); /*Function call */
printf ("Factorial is %d\n", factorial);
getch();
}
/* Recursive function of factorial */

© BISHWO PRAKASH POKHAREL [95]


C Programming Language

int fact(int n)
{
int res;
if(n == 1) /* Terminating condition */
return(1);
else
res = n*fact(n-1); /* Recursive call */
return(res);
}
OUTPUT
Enter any number: 5
Factorial is 120

How it works?

Thus a recursive function first proceeds towards the innermost condition, which is the
termination condition, and then returns with the value to the outermost call and produces
result with the values from the previous return.

Q] Write a program to find ab using recursion.


#include<stdio.h>
#include<conio.h>
int recursion(int, int);
main()
{
int a, b, z;
printf("\n Enter a and b:\t");
scanf("%d %d",&a,&b);
z=recursion(a,b);
printf("\n %d raised to power %d=%d", a, b, z);
getch();
}
int recursion(int x, int y)
{

© BISHWO PRAKASH POKHAREL [96]


C Programming Language

if(y==1)
return x;
else
return (x*recursion(x,y-1));
}

7.5 Function Arguments and Return Types,


Types of functions:
1) Functions with no arguments and no return values
2) Functions with arguments but no return values
3) Functions with arguments and return values

1. Functions with no arguments and no return values:


 When a function has no arguments, it does not receive any data from the calling
function.
 When a function does not return a value, the calling function does not receive any
data from the called function.
 Thus, there is no data transfer between the calling function and the called function.
 Syntax: void function_name()
{
/* body of function */
}
//EXAMPLE
#include <stdio.h>
#include <conio.h>
void add();
main()
{
add();
getch();
}

void add()
{
int a,b,sum;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum=a+b;
printf("\nThe sum is:%d",sum);
}

2. Functions with arguments but no return value:


 This type of function has arguments and receives the data from the calling function.
 But after the function completes its task, it does not return any values to the calling
function.
 Syntax:
void function_name(argument_list)
{
/* body of function */

© BISHWO PRAKASH POKHAREL [97]


C Programming Language

}
//EXAMPLE
#include <stdio.h>
#include <conio.h>
void add(int, int)
main()
{
int a,b;
printf("\n Enter two numbers:");
scanf("%d %d",&a,&b);
add(a, b);
getch();
}

void add(int a, int b)


{
int sum;
sum=a + b;
printf("\n The sum is:%d", sum);
}

3. Functions with arguments and return values:


 This type of function has arguments and receives the data from the calling function.
 However, after the task of the function is complete, it returns the result to the calling
function via return statement.
 So, there is data transfer between called function and calling function using return
values and arguments.
Syntax: return_type function_name(argument_list)
{
/* body of function */
}
//EXAMPLE
#include <stdio.h>
#include <conio.h>
int add(int, int);
main()
{
int a, b, x;
printf("\n Enter two numbers:");
scanf("%d %d", &a, &b);
x=add(a, b);
printf("\n The sum is:%d", x);
getch();
}

int add(int a, int b)


{
int sum;
sum=a + b;
return sum;

© BISHWO PRAKASH POKHAREL [98]


C Programming Language

Question:Write a function to add, subtract, multiply two complex numbers (x+i*y) and
(a+i*b).
#include <stdio.h>
#include <conio.h>
void add(int, int, int, int);
void subtract(int, int, int, int);
void multiply(int, int, int, int);
main()
{
int x, y, a, b;
printf("\n Enter Ist complex number of the form (x+iy):");
scanf("%d+i%d", &x, &y);
printf("\n Enter 2nd complex number of the form (a+ib):");
scanf("%d+i%d", &a, &b);
add(x, y, a, b);
subtract(x, y, a, b);
multiply(x, y, a, b);
getch();
}
void add(int x, int y, int a, int b)
{
printf("\n The addition of the complex numbers is:%d+i%d",x+a,y+b);
}
void subtract(int x, int y, int a, int b)
{
printf("\n The subtaction of the complex numbers is:%d+i%d",x-a,y-b);
}
void multiply(int x, int y, int a, int b)
{
int real, img;
real=(a*x-b*y);
img=(a*y+b*x);
printf("\n The multiplication of the complex numbers is:%d+i%d", real, img);
}

Q] Write a function to solve a quadratic equation ax2+bx+c=0. The inputs to the


function are the values a, b and c and the outputs of the function should be stored in
variable names p and q appropriately declared.
#include <stdio.h>
#include <conio.h>
#include <math.h>
void quad(float, float, float);
main()
{
float a, b, c;
printf("\n Enter values a, b and c of the quadratic equation:");
scanf("%f %f %f", &a, &b, &c);

© BISHWO PRAKASH POKHAREL [99]


C Programming Language

quad(a, b, c);
getch();
}
void quad(float a, float b, float c)
{
float p, q;
float d;
d = b*b-4*a*c;
if(d<0)
{
printf("\n Imaginary Roots.");
d = sqrt(fabs(d)); //compute absolute value of discriminant
p = -b/(2*a);
q = d/(2*a);
printf("\nRoot1 = %.2f +i %.2f",p,q);
printf("\nRoot2 = %.2f -i %.2f",p,q);
}
else
{
printf("\n Roots are real.");
d = sqrt(d);
p = (-b+d)/(2*a);
q = (-b-d)/(2*a);
printf("\nRoot1 = %.2f \t Root2 = %.2f",p,q);
}
}
Q] Write a program to display the reverse of a number using recursion.
 Take a look at static variable use in recursion
#include<stdio.h>
#include<conio.h>
int rev(int);
main()
{
int n, r;
printf("\n Enter number you want to reverse:");
scanf("%d", &n);
r=rev(n);
printf("\n The reverse of the number is:%d", r);
getch();
}
int rev(int num)
{
static int sum=0; //sum should retain its previous value
int r;
if(num>0) //stopping condition
{
r=num%10;
© BISHWO PRAKASH POKHAREL [100]
C Programming Language

sum=sum*10+r;
rev(num/10); //recursive function call
}
return sum;
}

7.6 Passing Arrays to Function,


 It is possible to pass the value of an array element or an entire array as an argument to
a function.
 Passing array elements is similar to passing variables except that array subscripts are
needed in function call.

//Passing elements of an array


#include <stdio.h>
#include <conio.h>
void display(int, int);
main()
{
int nums[5]={1,2,3,4,5};
printf("\n The array elements passed are:\n");
display(nums[3], nums[4]);
getch();
}
void display(int n, int m)
{
printf("%d\t %d", n, m);
}

Passing 1-D array to a function:


 To pass an entire array to a function, the array name is given without square brackets
or subscripts, as an actual argument in function call statement.
 In the function definition, the corresponding formal argument must declare an array
with a pair of empty square brackets (without specifying the size of the array,
although it doesn’t matter) for a One-Dimensional array.
 The function prototype must show that the argument is an array.
 Syntax for function call: function_name(array_name);
 Syntax for function prototype:
return_type function_name(data_type array_name[]);

For example:
#include <stdio.h>
#include <conio.h>
void display(int a[]);
main()
{
int nums[5]={1,2,3,4,5};
printf("\n The contents of array is:\n");
display(nums);

© BISHWO PRAKASH POKHAREL [101]


C Programming Language

getch();
}
void display(int n[])
{
int i;
for(i=0;i<5;i++)
printf("%d\t", n[i]);
}

For example: WAP to sort a set of n numbers in ascending order using function.
#include <stdio.h>
#include <conio.h>
#define SIZE 100
void sort(int nums[], int);
main()
{
int nums[SIZE], i, n;
printf("\n How many numbers you want to sort(<100)?:\t");
scanf("%d", &n);
for(i=0;i<n;i++)
scanf("%d", &nums[i]);
sort(nums, n); //routine (function) call
getch();
}
void sort(int nums[], int n)
{
int i, j, temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(nums[i]>nums[j])
{
temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
}
printf("\n The numbers in ascending order are:\n");
for(i=0;i<n;i++)
printf("\t%d", nums[i]);
}

Q] Given three variables x, y, and z, write a function to circularly shift their values. In
other words, if x=5, y=9, and z=8, after circular shift y=5, z=9, and x=8. Call the
function with variables a, b, and c to circularly shift their values.
#include <stdio.h>
#include <conio.h>
void circularshift(int *, int*, int*);

© BISHWO PRAKASH POKHAREL [102]


C Programming Language

main()
{
int x=5, y=9, z=8;
printf("\nBefore circular shift-x, y and z are:%d\t%d\t%d",x,y,z);
circularshift(&x,&y,&z);
printf("\nAfter circular shift-x, y & z are:%d\t%d\t%d",x,y,z);
getch();
}
void circularshift(int *x, int *y, int *z)
{
int temp1, temp2;
temp1=*x;
temp2=*y;
*x=*z;
*y=temp1;
*z=temp2;
}

Passing 2-D array to a function:


Rules
1. The function must be called by passing only the array name.
2. In the function definition, we must indicate that the array has two dimensions by
including two sets of brackets.
3. The size of the second dimension must be specified.
4. The prototype declaration should be similar to the function header.
For example:
//Program to display a matrix
#include <stdio.h>
#include <conio.h>
void display(int rix[][2]);
main()
{
int matrix[2][2], i, j;
printf("Input matrix elements:\t");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d", &matrix[i][j]);
}
display(matrix);
getch();
}
void display(int mat[][2])
{
int i, j;
printf("\n The matrix is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)

© BISHWO PRAKASH POKHAREL [103]


C Programming Language

printf(" %d\t", mat[i][j]);


printf("\n");
}
}

Things to remember:
 When an entire array is passed to a function and if that function changes the values of
array elements, then these changes are actually made to the original array that is
passed to the function.
 This means that when an entire array is passed as an argument, the contents of the
array are not copied into the formal parameter; instead, information about the
addresses of array elements are passed on to the function.
 Thus, any changes made to the array elements by the function are truly reflected in the
original array in the calling function.
 However, this does not apply when an individual array element is passed as an
argument.

Example: WAP to multiply two n*n matrices using function.


#include <stdio.h>
#include <conio.h>
#define N 3
void multiply(int rix1[][N], int rix2[][N]);
main()
{
int matrix1[N][N],matrix2[N][N],i,j;
printf("Input first matrix elements of order %d*%d:\n", N, N);
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
scanf("%d",&matrix1[i][j]);
}
printf("\n The first matrix is:\n");
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf(" %d\t",matrix1[i][j]);
printf("\n");
}
printf("Input second matrix elements of order %d*%d:\n", N, N);
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
scanf("%d", &matrix2[i][j]);
}
printf("\n The second matrix is:\n");
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf(" %d\t",matrix2[i][j]);
printf("\n");

© BISHWO PRAKASH POKHAREL [104]


C Programming Language

}
multiply(matrix1,matrix2);
getch();
}//main ends here
void multiply(int mat1[][N],int mat2[][N])
{
int multiply[N][N], i, j, k, row_mul_col=0;
for(i=0;i<N;i++) //first row
{
for(j=0;j<N;j++) //second column
{
for(k=0;k<N;k++) //first column or second row
{
row_mul_col=row_mul_col+mat1[i][k]*mat2[k][j];
}
multiply[i][j]=row_mul_col;
row_mul_col=0;
}
}
printf("\n The matrix after multiplication is:\n");
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
printf("%d\t", multiply[i][j]);
}
printf("\n");
}
}

Q] Write a program to read a matrix of order m*n. Pass this matrix to a function which
increases each element of the matrix by 2.

#include<stdio.h>
#include<conio.h>
#define M 3
#define N 3
void increase_by_2(int rix[][N]);
main()
{
int matrix[M][N], i, j;
printf("Input matrix elements of order %d*%d:\n", M, N);
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
scanf("%d", &matrix[i][j]);
}
printf("\n The input matrix is:\n");
for(i=0;i<M;i++)
{

© BISHWO PRAKASH POKHAREL [105]


C Programming Language

for(j=0;j<N;j++)
printf(" %d\t", matrix[i][j]);
printf("\n");
}
increase_by_2(matrix);
printf("\n The output matrix is:\n");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
printf(" %d\t", matrix[i][j]);
printf("\n");
}
getch();
}
void increase_by_2(int mat[][N])
{
int i, j;
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
mat[i][j]=mat[i][j]+2;
}
}

Q] Write a function which will take as its input a matrix of size (m*n), where m<10, n<5
and returns the same matrix with all its elements replaced by absolute values.
#include<stdio.h>
#include <conio.h>
#include <math.h>
#define M 10
#define N 5
void absolute(int rix[][N], int, int);
main()
{
int matrix[M][N], i, j, m, n;
printf("Input size of matrix up to %d*%d:\n",M-1,N-1);
scanf("%d %d", &m, &n);
if(m>9||n>4)
{
printf("\n The order is out of range.");
getch();
exit();
}
printf("\n Enter matrix elements of order %d*%d:\n", m, n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d", &matrix[i][j]);
}
printf("\n The matrix is:\n");

© BISHWO PRAKASH POKHAREL [106]


C Programming Language

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d\t",matrix[i][j]);
printf("\n");
}
absolute(matrix,m,n);
printf("\n The absolute matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
getch();
}
void absolute(int mat[][N], int m, int n)
{
int i, j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
mat[i][j]=abs(mat[i][j]);
}
}
}

7.7 Passing Strings to Function,


 Since strings are character arrays, the rules for passing strings to functions are similar
to those for passing arrays to functions.
 Rules
1. The string to be passed must be declared as a formal argument of the function
definition in the function header.
void display(char item_name[])
{
……………
}
2. The function prototype must show that the argument is a string.
void display(char str[]);
3. A call to the function must have a string name without subscripts as its actual
argument.
display(name);
where, name is a properly declared string in the calling function.
Note: Like arrays, strings are passed by address.

© BISHWO PRAKASH POKHAREL [107]


C Programming Language

7.8 Passing Arguments by Value,


 When values of actual arguments are passed to the function as arguments, it is known
as passing by value.
 Here, the value of each actual argument is copied into corresponding formal argument
of the function definition.
 Note: The contents of the actual arguments in the calling function are not changed,
even if they are changed in the called function.
#include <stdio.h>
#include <conio.h>
void swap(int, int);
main()
{
int x=2, y=3;
printf("\n Before swap function call: x=%d and y=%d", x, y);
swap(x,y);
printf("\n After swap function call: x=%d and y=%d", x, y);
getch();
}
void swap(int a, int b)
{
int t;
t=a;
a=b;
b=t;
printf("\n Values within swap: a=%d and b=%d", a, b);
}

7.9 Passing Arguments by Address,


 When addresses of actual arguments are passed to the function as arguments (instead
of values of actual arguments), it is known as passing by address.
 Here, the address of each actual argument is copied into corresponding formal
argument of the function definition.
 In this case, the formal arguments must be of type pointers.
 Note: The values contained in addresses of the actual arguments in the calling
function are changed, if they are changed in the called function.
Small introduction of pointer:
 A pointer is a variable that stores the memory address of a variable
 Pointer naming is same as variable naming and it is declared in the same way like
other variables but is always preceded by * (asterisk) operator.
 E.g. int b, *a; //pointer declaration

© BISHWO PRAKASH POKHAREL [108]


C Programming Language

a=&b; /* address of b is assigned to pointer variable a */


#include <stdio.h>
#include <conio.h>
void swap(int *, int *);
main()
{
int a=50, b=100;
printf("\n Before swap function call: a=%d and b=%d", a, b);
swap(&a, &b);
printf("\n After swap function call: a=%d and b=%d", a, b);
getch();
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf("\n Values within swap: x=%d and y=%d", *x, *y);
}

7.10 Scope visibility and lifetime of a variable,


 Variables in C are categorized into four different storage classes according to the
scope and lifetime of variables:
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
Note:
 The scope of variable determines over what part(s) of the program a variable is
actually available for use (active).
 Lifetime refers to the period of time during which a variable retains a given value
during execution of a program (alive).
Note:
 Variables can also be broadly categorized, depending on the place of their declaration,
as internal (local) or external (global).
 Local variables are those which are declared within a particular function, while global
variables are declared outside of any function.

7.11 Local and Global Variable,


Local variable(Automatic or internal variable):
 Automatic variables are always declared inside a function or block in which they are
to be used.
 They are created when the function is called and destroyed automatically when the
function is exited, hence the name is automatic.
 The keyword auto is used for storage class specification although it is optional.
 Initial value: garbage
 Scope: local to the block where the variable is defined

© BISHWO PRAKASH POKHAREL [109]


C Programming Language

 Lifetime: till the control remains within the block where variable is defined

#include <stdio.h>
#include <conio.h>
main()
{
auto int m=10;
printf("m=%d", m);
function1();
getch();
}

void function1()
{
auto int m=20;
printf("\n m=%d", m);
}

Global variable (External variable):


 The global variables are declared outside any block or function.
 These variables are both alive and active throughout the entire program.
 Unlike local variables, global variables can be accessed by any function in the
program.
 Initial value: zero
 Scope: global (i.e. throughout the program (multifile too))
 Lifetime: throughout program’s execution

#include <stdio.h>
#include <conio.h>
int a;
main()
{
printf("%d", a);
getch();
}
//Global Variable

#include <stdio.h>
#include <conio.h>
main()
{
int a;
printf("%d", a);
getch();
}
//Local Variable

For example:
#include <stdio.h>
#include <conio.h>

© BISHWO PRAKASH POKHAREL [110]


C Programming Language

int a=100;
void function()
{
a=200;
printf("%d\n", a++);
}
main()
{
printf("%d\n", a);
function();
printf("%d", a);
getch();
}

Description
Here, once a variable is declared as global, any function can use it and change its value. Then
subsequent functions can reference only that new value. As the global variable a is
recognized by main() as well as function(), so values are printed as 100, 200 and 201.
Note: Care should be taken while using global variables. Only those variables should be
declared as global which are to be shared among different functions when it is inconvenient
to pass them as parameters.

Static variable:
 As the name suggests, the value of static variables persists till the end of the program.
 A variable is declared static using the keyword static:
static int x;
 A static variable may be either an internal type or an external type, depending on the
place of declaration.
 Initial value: zero (initialized only once)
 Scope: local (within the function) or global (within the program (single file))
 Lifetime: throughout the program for local as well as global static variables

Register variable:
 Normally, variables are stored in memory.
 However, we can instruct the compiler that a variable should be kept in one of the
CPU’s registers, instead of keeping in the memory.
 Use: A register access is much faster than a memory access. So keeping frequently
accessed variables (e.g. loop control variables) in the register will help faster
execution of the program.
 A register variable is declared using register keyword:
 Example: register int i;
 Register variables are always declared inside a function or block.
 They are allocated space upon entry to a block; and the storage is freed when the
block is exited.
 Initial value: garbage
 Scope: only in that function or block
 Lifetime: until end of function or block

© BISHWO PRAKASH POKHAREL [111]


C Programming Language

For example:
#include <stdio.h>
#include <conio.h>
main()
{
register int i;
for(i=1;i<100;i++)
printf(" %d\t", i);
getch();
}

© BISHWO PRAKASH POKHAREL [112]


C Programming Language

© BISHWO PRAKASH POKHAREL [113]


C Programming Language

STRUCTURE AND UNION


CHAPTER OUTLINE
8.1 Introduction,
8.2 Array of structure,
8.3 Passing structure to function,
8.4 Passing array of structure to function,
8.5 Structure within structure ( Nested Structure),
8.6 Union,
8.7 Pointer to structure

8.1 Introduction,
A structure is a collection of one or more variables, possibly of different data types, grouped
together under a single name for convenient handling. Structures help to organize data,
particularly in large programs, because they allow a group of related variables to be treated as
a single unit. Once the structure has been declared, we can create variable of its type. In some
language, structures are known as records and the element of structures are known as fields or
members or components.
Declaration of structure:
struct structure_name
{
data_type member1;
data_type member2;
…..
…..
…..
data_type member n
};

For example:
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[35];
int age;
float salary;
} emp1;

main()
{
struct student

© BISHWO PRAKASH POKHAREL [114]


C Programming Language

{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
struct student st1={"Bishwo Prakash Pokharel", 4, 89.5, 'M', 9845111211};
printf("Name\t\t\tRoll No.\tMarks\t\tGender\tPhone No.");
printf("\n.........................................................................\n");
printf("\n%s\t%d\t\t%f\t%c\t%ld", st1.name, st1.roll_no, st1.marks, st1.gender,
st1.phone_no);
getch();
}

Q] Create a structure named student that has name, roll, marks, and remarks as
members. Assume appropriate types and size of member. Write a program using
structure to read and display the data entered by the user.

#include<stdio.h>
#include<conio.h>
main()
{
struct student
{
char name[20];
int roll;
float marks;
char remarks;
};
struct student s;
printf("Enter name:\t");
gets(s.name);
printf("\n Enter roll:\t");
scanf("%d", &s.roll);
printf("\n Enter marks:\t");
scanf("%f", &s.marks);
printf("\n Enter remarks(P for pass or F for fail):\t");
scanf(" %c", &s.remarks);
printf("\n Name \t Roll \t Marks \t Remarks\n");
printf("\n...................................\n");
printf("\n%s\t%d\t%f\t%c", s.name, s.roll, s.marks, s.remarks);
getch();
}

8.2 Array of structure,


A collection of similar type of structure placed in a common variable name is called array of
structure.

© BISHWO PRAKASH POKHAREL [115]


C Programming Language

For example:
C program to store record of 100 books
#include<stdio.h>
#include<conio.h>
struct book
{
char name[50];
float price;
int pages;
};
main()
{
struct book b[100];
float temp;
int i;
for(i=0; i<100; i++)
{
printf("\n Enter name price and page and pages:");
scanf("%s%f%d", &b[i].name, &b[i].price, &b[i].pages);
}
for(i=0; i<100;i++)
{
printf("\n Name: %s \n Price:%f \n Pages:%d", b[i].name, b[i].price, b[i].pages);
}
getch();
}
Q] Create a structure named student that has name, roll, marks and remarks as its
members. Assume appropriate types and size of member. Use this structure to read and
display records of 10 students.

#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll;
float marks;
char remarks;
};
main()
{
struct student s[10];
int i;
float temp;
for(i=0;i<10;i++)
{
printf("\nEnter information about student%d",i+1);
printf("\nName:\t");
scanf(" %s", s[i].name);
printf("\nRoll:\t");

© BISHWO PRAKASH POKHAREL [116]


C Programming Language

scanf("%d",&s[i].roll);
printf("\nMarks:\t");
scanf(“%f",&temp);
s[i].marks=temp; //Mandatory
printf("\nRemarks(P/F):\t");
s[i].remarks=getche();
}
printf("\n\n");
printf("\nStudent name\tRoll\tMarks\t\tRemarks");
for(i=0;i<10;i++)
{
printf("\n%s\t\t %d\t%f\t%c\n", s[i].name, s[i].roll, s[i].marks, s[i].remarks);
}
getch();
}

Q] Define a structure of employee having data members name, address, age and salary.
Take the data for n employees in an array and find the average salary.

#include<stdio.h>
#include<conio.h>
#define SIZE 100
struct employee
{
char name[20];
char address[40];
int age;
float salary;
};
main()
{
struct employee e[SIZE];
int n;
int i;
float temp;
float avg_sal=0;
printf("How many emplyees are there?:\t");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter information about employee%d",i+1);
printf("\nName:\t");
scanf(" %s", e[i].name);
printf("\nAddress:\t");
scanf(" %s",e[i].address);
printf("\nAge:\t");
scanf("%d",&e[i].age);
printf("\nSalary:\t");
scanf("%f",&temp);
e[i].salary=temp;

© BISHWO PRAKASH POKHAREL [117]


C Programming Language

}
printf("\n\n");
printf("\n Employee name\t Address \t Age\t Salary");
for(i=0;i<n;i++)
printf("\n%s\t\t %s\t\t %d\t%f\n",e[i].name,e[i].address,e[i].age,e[i].salary);
for(i=0;i<n;i++)
avg_sal=avg_sal+e[i].salary;
avg_sal=avg_sal/n;
printf("\nAverage Salaray=%f",avg_sal);
getch();
}
Q] /*Write a program to read the name, address, and salary of 5 employees using array
of structure. Display information of each employee in ascending order of their name.*/

#include<stdio.h>
#include<conio.h>
#define n 5
struct employee
{
char name[20];
char address[50];
float salary;
};
main()
{
struct employee e[n];
struct employee temp;
int i;
float temp1;
int j;
for(i=0;i<n;i++)
{
printf("\n Enter information of employee%d",i+1);
printf("\n Enter name:");
scanf(" %s", e[i].name);
printf("\n Enter address:");
scanf(" %s", e[i].address);
printf("\n Enter salary:");
scanf("%f",&temp1);
e[i].salary=temp1;
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(e[i].name, e[j].name)>0)
{
temp=e[i];
e[i]=e[j];
e[j]=temp;

© BISHWO PRAKASH POKHAREL [118]


C Programming Language

}
}
}
printf("\n Employee list in ascending order of name\n");
printf("Emp. Name\t Address\t\t Salary");
for(i=0;i<n;i++)
printf("\n%s\t\t%s\t\t%.2f", e[i].name, e[i].address, e[i].salary);
getch();
}

8.3 Passing structure to function,


Like any ordinary variable, a structure variable can also be passed to a funciton. One may
either pass individual structure elements or the entire structure at once.
#include<stdio.h>
#include<conio.h>
void display(char [], float, int);
struct book
{
char name[50];
float price;
int pages;
};
main()
{
book b={"C program", 312.5, 105);
display(b.name, b.price, b.pages);
}
void display (char n[50], float pr, int pg)
{
printf("\n Nae-%s \n Page number:%d \n price:%f", n, pg, pr);
getch();
}

8.4 Passing array of structure to function,


It is possible to define a array of structures for example if we are maintaining information of
all the students in the college and if 100 students are studying in the college. We need to use
an array than single variables. We can define an array of structures as shown in the following
example:
structure information
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
} student[100];
An array of structures can be assigned initial values just as any other array can. Remember
that each element is a structure that must be assigned corresponding initial values as
illustrated below.

© BISHWO PRAKASH POKHAREL [119]


C Programming Language

#include<stdio.h>
#include<conio.h>
main()
{
struct info
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
};
struct info std[100];
int I,n;
printf(“Enter the number of students”);
scanf(“%d”,&n);
for(I=0;I<n;I++)
{
printf(“ Enter Id_no,name address combination age\m”);
scanf("%d%s%s%s%d”,&std[I].id_no,std[I].name,std[I].address,std[I].combination,
&std[I].age);
}
printf(“\n Student information”);
for (I=0;I< n;I++)
{
printf(“%d%s%s%s%d\n”,std[I].id_no,std[I].name,std[I].address,std[I].combination,
std[I].age);
}
getch();
}

8.5 Structure within structure ( Nested Structure),


Nested strctures are nothing but structure within a structure.
struct emp_add
{
int house_no;
char streetname[20];
};
The above definition could be used as a template to declare a variable address in the
employee structure.
struct employee
{
char name[35];
int age;
struct emp_add address;
char address[50];
float salary;
};
Or the two definitions could even be consolidated as:
struct employee

© BISHWO PRAKASH POKHAREL [120]


C Programming Language

{
char name[35];
int age;
struct emp_add
{
int house_no;
char streetname[30];
};address;
char address[50];
float salary;
};

8.6 Union,
Union is a user-defined data type such every union member takes memory that contains a
variety of objects. Such that the union members share space thereby resulting, coserves
storage. The size required by a union variable is the size required by the member requiring
the largest size. Lastly, only the last data member defined can be accessed.
union item
{
int m;
float p;
char c;
} code;
this declares a variable code of type union item. The union contains three members each with
a different data type. However we can use only one of them at a time. This is because if only
one location is allocated for union variable irrespective of size. The compiler allocates a piece
of storage that is large enough to access a union member we can use the same syntax that we
use to access structure members. That is
code.m
code.p
code.c
are all valid member variables. During accessing we should make sure that we are accessing
the member whose value is currently stored. For example a statement such as
code.m=456;
code.p=456.78;
printf(“%d”,code.m);
For Example:

#include<stdio.h>
#include<conio.h>
union student
{
char name[20];
int roll_no;
float marks;
char section;
};
main()
{
union student s;

© BISHWO PRAKASH POKHAREL [121]


C Programming Language

printf("Size of union=%d\n", sizeof(s));


strcpy(s.name, "Bishwo");
printf("Name=%s\t", s.name);
printf("Location=%u", s.name);
s.roll_no=10;
printf("\nRoll=%d \tLocation=%u", s.roll_no, &s.roll_no);
s.marks=91.5;
printf("\nMarks=%.2f \tLocation=%u", s.marks, &s.marks);
s.section='A';
printf("\nSection=%c \tLocation=%u", s.section, &s.section);
printf("\n\nErroneous output");
printf("\n\nName\tRoll\tMarks\tSection\n");
printf("%s\t%d\t%.2f\t%c", s.name, s.roll_no, s.marks, s.section);
getch();
}

8.7 Pointer to structure


A structure type pointer variable can be declared as:
struct book
{
char name[20];
int pages;
float price;
};
struct book *bptr;

However this declaration for a ponter to structure does not allocate any memory for a
structure but allocates only for a pointer, so that to access structures members through pointer
bptr, we must allocate the memory using malloc() function.

Now individual structure members are accessed as:


bptr -> name bptr-> pages bptr->price
OR
(*bptr).name (*bptr).pages (*bptr).price
Here -> is called arrow operator and there must be a pointer to the structure on the left side of
this operator.

Q] Write a menu driven program which performs the following jobs:


i. Create a structure named student with member variables: roll, name,
grade, gender, age.
ii. Define ten structure variables of type student and using loop take input
for all ten structure variables.
iii. Display names of all male students.
iv. Exit.

#include<stdio.h>
#include<conio.h>
#define N 10
struct student

© BISHWO PRAKASH POKHAREL [122]


C Programming Language

{
int roll;
char name[20];
int grade;
char gender;
int age;
};
main()
{
struct student s[N];
char option;
char choice='y';
int i;
printf("Menu Driven Program");
printf("\n Enter 1 for inputting student information");
printf("\n Enter 2 to display all male students");
printf("\n Enter 3 for exit");
while(choice!='n')
{
printf("\n Enter your option:\t");
scanf(" %c", &option);
switch(option)
{
case '1':
printf("\n Enter info about %d students", N);
for(i=0;i<N;i++)
{
printf("\n Info. about student%d",i+1);
printf("\n Roll:\t");
scanf("%d", &s[i].roll);
printf("\n Name:\t");
scanf("%s", s[i].name);
printf("\n Grade:\t");
scanf("%d", &s[i].grade);
printf("\n Gender(M/F):\t");
scanf(" %c", &s[i].gender);
printf("\n Age:\t");
scanf("%d", &s[i].age);
}
break;
case '2':
printf("\nList of Male Students");
for(i=0;i<N;i++)
{
if(s[i].gender=='M')
printf("\n%s\n",s[i].name);
}
break;
case '3':
exit(0);

© BISHWO PRAKASH POKHAREL [123]


C Programming Language

default:
printf("Invalid Option!!!");
}
printf("Do you want to continue?(y/n)");
scanf(" %c", &choice);
}
getch();
}

© BISHWO PRAKASH POKHAREL [124]


C Programming Language

POINTERS
CHAPTER OUTLINE
9.1 Introduction,
9.2 The & and * operator,
9.3 Declaration of pointer,
9.4 Chain of Pointers,
9.5 Pointer Arithmetic,
9.6 Pointers and Arrays,
9.7 Pointers and Character Strings,
9.8 Array of Pointers,
9.9 Pointers as Function Arguments,
9.10 Function Returning pointers,
9.11 Pointers and Structures,
9.12 Dynamic Memory Allocation

9.1 Introduction,
Pointers are basically the same as any other variable. However, what is different about them
is that instead of containing actual data, they contain a pointer to the memory location where
information can be found. This is a very important concept, and many programs and ideas
relay on pointers as the basis of their design.
Variable names are not sufficient to provide the requirements of C during manipulation.
Local variables are meaningful only within their declaring functions. However, memory
addresses are global to all functions.
A pointer is a variable that points to or references a memory location where data is stored.
Each memory cell in the computer has an address which can be used to access its location. A
pointer variable points the memory location rather than the value. It has two parts: the pointer
itself holds the address and the addresses point to a value.

Pointer declaration syntax:


pointer_type * pointer_variable_name;

For example:
int *p;

Advantages of pointer:
 Pointers increase the execution speed and thus reduce the program execution time.
 With the help of pointer we can handle any type of data structure.
 By using pointers we can access a data which is available outside a function.
 By using pointer variable we can implement dynamic memory allocation.

© BISHWO PRAKASH POKHAREL [125]


C Programming Language

 Pointers provide an efficient tool for manipulating dynamic data structures such as
structures, linked lists, queues, stacks and trees.
 Pointers reduce length and complexity of programs.

9.2 The & and * operator,


Address (&) and indirection (*) operator:
The address of (&) operator returns the address of memory location in which the variable is
stored. The indirection (*) operator is used to extract value from the memory location stored
in the particular memory location whose address is stored in pointer variable.

Syntax:
pointer_variable = &variable_name;

For example:
int *ptr, num=25;
ptr=&num;

Example: WAP to print the address.


#include<stdio.h>
#include<conio.h>
main()
{
int a;
int *aptr;
a=7;
aptr=&a;
printf("\n The address is %u", &a);
printf("\n The address of pointer is %u", aptr);
getch();
}

9.3 Declaration of pointer,


Syntax:
data_type *pointer_variable;

For example:
int *I;
float *s;
char *ch;

A program to display the address and value of a variable using pointer:


#include<stdio.h>
#include<conio.h>
main()
{
int i=3, *j;
j=&i;
printf("\n Address of i=%u", j);

© BISHWO PRAKASH POKHAREL [126]


C Programming Language

printf("\n Value of i=%d", *j);


getch();
}

Output:
Address of i = 65490
Value of i = 3

In above program two different operators have been used; & (ampersand) and * (asterisk), '&'
operator gives the address of the variable associated with it and called address of operator. '*'
operator gives the value stored at a particular address. It is called value at address operator or
also called indirection operator.

Program to show the address of variable i pointer j and its values:


#include<stdio.h>
#include<conio.h>
main()
{
int i=3, *j;
j=&i;
printf("Address of i=%u", &i);
printf("\t Address of i=%u", j);
printf("\t Address of j=%u", &j);
printf("\t Value of j=%u", j);
printf("\n Value of i=%d", i);
printf("\t Value of i=%d", *(&i));
printf("\t Value of i=%d", *j);
getch();
}

Output:
Address of i=65522 Address of i=65522 Address of j=65520 Value of j=65522
Value of i=3 Value of i=3 Value of i=3

Check Your Progress


Analyze the output:
1.main()
{
int a=10, b=5;
float c=10.5;
char d='B';
printf("\n The base address of a is:%u", &a);
printf("\n The base address of b is:%u", &b);
printf("\n The base address of c is:%u", &c);
printf("\n The base address of d is:%u", &d);
getch();
}

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

© BISHWO PRAKASH POKHAREL [127]


C Programming Language

main()
{
int x=10,*p=&x;
printf("\n The address of x is:%u", &x);
printf("\n The address of x (value of p or address pointed by p) is:%u", p);
printf("\n The value of x is:%d", x);
printf("\n The value of x (value pointed by p)is:%u", *p);
printf("\n The address of p is:%u", &p);
getch();
}

9.4 Chain of Pointers,


The concept of pointer can be extended further. As we have seen earlier, a pointer variable
can be assigned the address of an ordinary variable. Now, this variable itself could be another
pointer. This means that a pointer can contain address of another pointer. The following
program will makes you the concept clear.
For example:
/* Program that declares a pointer to a pointer */
# include<stdio.h>
#include<conio.h>
main( )
{
int i = 100;
int *pi;
int **pii;
pi = &i;
pii = &pi;
printf ("Address of i = %u \n", &i);
printf ("Address of i = %u \n", pi);
printf ("Address of i = %u \n", *pii);
printf ("Address of pi = %u \n", &pi);
printf ("Address of pi = %u \n", pii);
printf ("Address of pii = %u \n", &pii);
printf ("Value of i = %d \n", i);
printf ("Value of i = %d \n", *(&i));
printf ("Value of i = %d \n", *pi);
printf ("Value of i = %d", **pii);
getch();
}
OUTPUT
Address of i = 65524
Address of i = 65524
Address of i = 65524
Address of pi = 65522
Address of pi = 65522
Address of pii = 65520
Value of i = 100

© BISHWO PRAKASH POKHAREL [128]


C Programming Language

Value of i = 100
Value of i = 100
Value of i = 100

9.5 Pointer Arithmetic,


Pointer address can be manipulated by arithmetic operators with integer values. These
arithmetic operators are only + and – and increment and decrement operators. The increment
and decrement of pointer variable depends on its data types.

For example:
#include<stdio.h>
#include<conio.h>
main()
{
int *p;
int age=17;
p=&age;
printf("\n Value of age is %d", age);
printf("\n Increment on age is %d", ++age);
printf("\n Address of age is %u", p);
printf("\n Increment in pointer is %u", ++p);
getch();
}

NULL Pointer:
 A null pointer is a special pointer value that points nowhere or nothing.
 The predefined constant NULL in stdio.h is used to define null pointer.
 Example:
#define NULL 0
void main()
{
int *ptr=NULL; //double/float/char/void *ptr=NULL
clrscr();
if(ptr==NULL)
printf("Change NULL to 1 and there will be warnings!!!");
getch();
}
Check Your Progress
1.What happens?
main()

© BISHWO PRAKASH POKHAREL [129]


C Programming Language

{
float *f, x;
int i;
f=&x;
printf("Enter x:\t");
scanf("%f", f);
printf("\n The value of x is %f\n",*f);
printf("\n Address of x:%u\n", f);
for(i=0;i<5;i++)
printf("%u\t", f++);
getch();
}
2.What is the output?
main()
{
char *p;
printf("%d %d", sizeof(*p), sizeof(p));
getch();
}

9.6 Pointers and Arrays,


Pointers and arrays are so closely related. An array declaration such as int arr[ 5 ] will lead
the compiler to pick an address to store a sequence of 5 integers, and arr is a name for that
address. The array name in this case is the address where the sequence of integers starts. Note
that the value is not the first integer in the sequence, nor is it the sequence in its entirety. The
value is just an address.
Now, if arr is a one-dimensional array, then the address of the first array element can be
written as &arr[0] or simply arr. Moreover, the address of the second array element can be
written as &arr[1] or simply (arr+1). In general, address of array element (i+1) can be
expressed as either &arr[ i] or as (arr+ i). Thus, we have two different ways for writing the
address of an array element. In the latter case i.e, expression (arr+ i) is a symbolic
representation for an address rather than an arithmetic expression. Since &arr[ i] and (ar+ i)
both represent the address of the ith element of arr, so arr[ i] and *(ar + i) both represent the
contents of that address i.e., the value of ith element of arr.
Note that it is not possible to assign an arbitrary address to an array name or to an array
element. Thus, expressions such as arr, (arr+ i) and arr[ i] cannot appear on the left side of an
assignment statement. Thus we cannot write a statement such as:
&arr[0] = &arr[1]; /* Invalid */
However, we can assign the value of one array element to another through a pointer, for
example,
ptr = &arr[0]; /* ptr is a pointer to arr[ 0] */
arr[1] = *ptr; /* Assigning the value stored at address to arr[1] */
Here is a simple program that will illustrate the above-explained concepts:
Example:
/* Program that accesses array elements of a one-dimensional array using pointers */
# include<stdio.h>
#include<conio.h>
main()

© BISHWO PRAKASH POKHAREL [130]


C Programming Language

{
int arr[ 5 ] = {10, 20, 30, 40, 50};
int i;
for (i = 0; i < 5; i++)
{
printf ("i=%d\t arr[i]=%d\t *(arr+i)=%d\t", i, arr[i], *(arr+i));
printf ("&arr[i]=%u\t arr+i=%u\n", &arr[i], (arr+i));
}
}
OUTPUT:
i=0 arr[i]=10 *(arr+i)=10 &arr[i]=65516 arr+i=65516
i=1 arr[i]=20 *(arr+i)=20 &arr[i]=65518 arr+i=65518
i=2 arr[i]=30 *(arr+i)=30 &arr[i]=65520 arr+i=65520
i=3 arr[i]=40 *(arr+i)=40 &arr[i]=65522 arr+i=65522
i=4 arr[i]=50 *(arr+i)=50 &arr[i]=65524 arr+i=65524

Note that i is added to a pointer value (address) pointing to integer data type (i.e., the array
name) the result is the pointer is increased by i times the size (in bytes) of integer data type.
Observe the addresses 65516, 65518 and so on. So if ptr is a char pointer, containing
addresses a, then ptr+1 is a+1. If ptr is a float pointer, then ptr+ 1 is a+ 4.

//Program to add two m*n matrices using pointer

#include<stdio.h>
#include<conio.h>
#define m 2
#define n 3
void main()
{
int (*a)[n], (*b)[n], (*sum)[n], i, j;
clrscr();
printf("Input first matrix elements of order %d*%d:\n", m, n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",*(a+i)+j);
}
printf("\n The first matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d\t",*(*(a+i)+j));
printf("\n");
}
printf("Input second of order %d*%d:\n", m, n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",*(b+i)+j);
}
© BISHWO PRAKASH POKHAREL [131]
C Programming Language

printf("\n The second matrix is:\n");


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(" %d\t",*(*(b+i)+j));
}
printf("\n");
}
printf("\n The sum of the matrices is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
*(*(sum+i)+j)=*(*(a+i)+j)+*(*(b+i)+j);
printf("\t%d",*(*(sum+i)+j));
}
printf("\n");
}
getch();
}

9.7 Pointers and Character Strings,


As we have seen in strings, a string in C is an array of characters ending in the null character
(written as '\0'), which specifies where the string terminates in memory. Like in one-
dimensional arrays, a string can be accessed via a pointer to the first character in the string.
The value of a string is the (constant) address of its first character. Thus, it is appropriate to
say that a string is a constant pointer. A string can be declared as a character array or a
variable of type char *. The declarations can be done as shown below:
char country[ ] = "NEPAL";
char *country = "NEPAL";
Each initialize a variable to the string “NEPAL”. The second declaration creates a pointer
variable country that points to the letter N in the string "NEPAL" somewhere in memory.
Once the base address is obtained in the pointer variable country, *country would yield the
value at this address, which gets printed through,

printf ("%s", *country);

Here is a program that dynamically allocates memory to a character pointer using the library
function malloc at run-time. An advantage of doing this way is that a fixed block of memory
need not be reserved in advance, as is done when initializing a conventional character array.
Example:

#include<stdio.h>
#include<conio.h>
main()
{
char name[25]="Bishwo Prakash Pokharel";
© BISHWO PRAKASH POKHAREL [132]
C Programming Language

int i;
printf("String Element\t Address\n");
printf("........................\n");
for(i=0;i<25;i++)
printf("name[%d]=%c \t %u\n", i, name[i], &name[i]);
printf("\n String Element\t Address\n");
printf("........................\n");
for(i=0;i<25;i++)
printf("name[%d]=%c \t %u\n", i,*(name + i), name + i);
printf("%s \t %s \t %s\n", name, name+1, name+2, name+3);
getch();
}

Array of pointers to strings:

#include<stdio.h>
#include<conio.h>
main()
{
char *names[]= {"jump", "walk", "red", "green", "talk", "move", "look", "feel"};
int i, j;
char *temp;
for(i=0;i<7;i++)
{
for(j=i+1;j<8;j++)
{
if(strcmp(names[i],names[j])>0)
{
temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
}
printf("\n Sorted List:\n");
for(i=0;i<8;i++)
puts(names[i]);
getch();
}

9.8 Array of Pointers,


The way there can be an array of integers, or an array of float numbers, similarly, there can
be array of pointers too. Since a pointer contains an address, an array of pointers would be a
collection of addresses. For example, a multidimensional array can be expressed in terms of
an array of pointers rather than a pointer to a group of contiguous arrays.

© BISHWO PRAKASH POKHAREL [133]


C Programming Language

Two-dimensional array can be defined as a one-dimensional array of integer pointers by


writing:
int *arr[3];
rather than the conventional array definition,
int arr[3][5];
Similarly, an n-dimensional array can be defined as (n-1)-dimensional array of pointers by
writing
data-type *arr[subscript 1] [subscript 2]…. [subscript n-1];
The subscript1, subscript2 indicate the maximum number of elements associated with each
subscript.

9.9 Pointers as Function Arguments,


Pointers are often used to pass value on the function. The value and address can be passed as
an argument or parameter to the function and receive as pointer. The value of pointer
variable can be manipulated as other functions.

For example: WAP to pass pointer variable to function sum them and display after returning
it.
#include<stdio.h>
#include<conio.h>
int add(int *i, int *j);
main()
{
int a,b,c=0;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
c=add(&a,&b);
printf("\n Sum of two numbers %d and %d is %d", a,b,c);
getch();
}

add(int *p, int *q)


{
int temp;
temp=*p+*q;
return(temp);
}

9.10 Function Returning pointers,


 A function can return a single value by its name or return multiple values through
pointer parameters.
 Since pointers are a data type in C, we can force a function to return a pointer to the
calling function.

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

© BISHWO PRAKASH POKHAREL [134]


C Programming Language

int * larger(int *,int *);


main()
{
int a=100,b=50;
int *p;
p=larger(&a,&b); //function call
printf("%d",*p);
getch();
}
int *larger(int *x,int *y)
{
if(*x>*y)
return (x); //address of a
else
return (y); //address of b
}
Note: The address returned must be the address of a variable in the calling function. It is
an error to return a pointer to a local variable in the called function.
9.11 Dynamic Memory Allocation
The process of allocating and freeing memory at run time (or execution time) is called
dynamic memory allocation.

For allocating and freeing memory during program execution, C has provided four library
functions viz. malloc(), calloc(), free() and realloc() called memory management functions.

Memory allocation process:


The conceptual view of storage of a C program in memory is shown below:

 The program instructions and global and static variables are stored in a region known
as permanent storage area and the local variables are stored in another area called
stack.
 The memory space that is located between these two regions is available for dynamic
memory allocation during execution of the program.
 This free memory region is called the heap.
 The size of the heap keeps changing when program is executed due to creation and
death of variables that are local to functions and blocks.
 Thus, it is possible to encounter memory overflow during dynamic memory allocation
process.

© BISHWO PRAKASH POKHAREL [135]


C Programming Language

 In such situations, the memory allocation functions return a NULL pointer (when they
fail to locate enough memory requested).

malloc():
It allocates requested size of bytes and returns a pointer to the first byte of the allocated
space.
Syntax:
p = (data_type*) malloc(size_of_block);
Here, p is a pointer of type data_type. The malloc() returns a pointer to the first byte to an
area of memory with size size_of_block.
For example:
x = (int *) malloc(100*sizeof(int));
x=(int *) malloc(200);
This statement allocates a memory space equivalent to 100 times the size of integer (100*2B
= 200 B) and the address of the first bte is assigned to the pointer x of type int.

calloc()
 Unlike malloc(), calloc() accepts two arguments: no_of_blocks and
size_of_each_block so that calloc() can allocate memory for an array of elements.
 All bytes allocated using calloc() are initialized to zero and a pointer to the first byte
is returned.
 Syntax:
p=(data_type *)calloc(no_of_blocks, size_of_each_block);
 E.g. x=(int *)calloc(5, 100*sizeof(int));
 This statement allocates 5 contiguous blocks of size 200B for each block, i.e. we can
store 5 arrays, each of 100 integer elements.

realloc()
 It is used to modify the size of the previously allocated space.
 When the size of previously allocated memory space is not enough or when the size
of previously allocated memory space is larger than needed, we need to use the
realloc() function.
 Syntax: If original allocation has been done as:
p=(data_type *)malloc(size);
then reallocation is done as:
p=(data_type *)realloc(p, new_size);
This statement allocates a new memory space of size new_size, and returns a pointer to the
first byte of this new memory space to pointer variable p.

free()
 It frees previously allocated memory space by malloc(), calloc(), or realloc() function.
 Syntax: free(pointer_name);
Q] Write a function that takes 1-D array of n numbers and sort the elements in
ascending order. Use dynamic memory allocation.

#include<stdio.h>
#include<conio.h>
void sort(float *, int);
main()

© BISHWO PRAKASH POKHAREL [136]


C Programming Language

{
float *f;
int n, i;
printf("\n Enter number of elements in your array:");
scanf("%d", &n);
f=(float *)malloc(n*sizeof(float));
printf("\n Enter the %d array elements:\t", n);
for(i=0;i<n; i++)
scanf("%f", f + i);
printf("\n The unsorted list of array elements and their addresses are:\t");
for(i=0;i<n; i++)
printf("\n %f \t\t %u", *(f + i), f + i);
sort(f, n);
printf("\n The sorted list of array elements and their addresses are:\t");
for(i=0;i<n; i++)
printf("\n %f \t\t %u", *(f + i), f + i);
getch();
}
void sort(float *g, int n)
{
int i, j;
float temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n; j++)
{
if(*(g + i)>*(g + j))
{
temp=*(g + i);
*(g + i)=*(g + j);
*(g + j)=temp;
}
}
}
}

Q] /*Program to read an array of integers using dynamic memory allocation and


display the maximum and minimum value*/

#include<stdio.h>
#include<conio.h>
void minmax(int *, int);
main()
{
int n, i;
int *num;
printf("Enter no. of elements in your array:");
scanf("%d", &n);
num=(int *)calloc(n, sizeof(int));
printf("\nEnter %d integers:",n);

© BISHWO PRAKASH POKHAREL [137]


C Programming Language

for(i=0;i<n;i++)
scanf("%d", num+i);
minmax(num, n);
getch();
}
void minmax(int *no, int n)
{
int i;
int min, max;
max=*no;
min=*no;
for(i=0;i<n; i++)
{
if(max<*(no + i))
max=*(no + i);
if(min>*(no + i))
min=*(no + i);
}
printf("\n The maximum number is:%d", max);
printf("\n The minimum number is:%d", min);
}

Q] Write a function that accepts a string and a character. The function should look for
the first occurrence of the character in the string and return a pointer to that location.

#include<stdio.h>
#include<conio.h>
char* fun(char [],char *);
main()
{
char string[20],character;
char *pointer;
printf("\n Enter string:");
gets(string);
printf("\n Enter character:");
scanf("%c", &character);
pointer=fun(string, &character);
printf("\n Character=%c Address=%u",*pointer, pointer);
getch();
}
char *fun(char str[],char *c)
{
int i;
for(i=0;str[i]!='\0';i++)
{
if(str[i]==*c) //if(*(str+i)==*c)
{
printf("\n Character found");
break;
}

© BISHWO PRAKASH POKHAREL [138]


C Programming Language

}
return &str[i]; //return (str+i);
}
Check Your Progress
What is the output?
int main()
{
char *ppp="programming language";
char **p=&ppp;
int pp;
printf("\n %s AND %s", *p, ppp); //p=&ppp
pp=strlen(*p);
printf("\n%4d\t%4d\t%4d\t%4d\t%4d\t", pp--,pp,++pp, pp++,--pp);
if(strcmp("abandon", "abandonment")<=0)
pp=10;
printf("Value of pp=%d", pp);
getch();
return;
}

© BISHWO PRAKASH POKHAREL [139]


C Programming Language

FILE HANDLING IN C
CHAPTER OUTLINE
10.1 Concept of File,
10.2 Opening and closing of File,
10.3 Input Output Operations in File,
10.4 Random access in File,
10.5 Error Handling in Files

10.1 Concept of File,


 A file is a place on the disk (not memory) where a group of related data is stored. Also
called data files.
 The data file allows us to store information permanently and to access and alter that
information whenever necessary.
 To perform basic file operations, C supports a number of functions, which include
functions for:
◦ naming a file,
◦ opening a file,
◦ reading data from file,
◦ writing data to a file, and
◦ closing a file
 Basically, there are two kinds of data files:
◦ high-level or stream oriented or standard
◦ low-level or system-oriented
 In high-level data files, the available library functions (in the C’s standard I/O library)
do their own buffer management whereas in low-level data files (using UNIX system
calls) a programmer is required to do buffer management explicitly.
 The high-level data files are further subdivided into two: text files and binary files.
 The text files consist of consecutive characters and these characters can be interpreted
as individual data items whereas the binary files organize data into blocks containing
contiguous bytes of information.
 There are a number of formatted and unformatted functions in C for both text and
binary files.

© BISHWO PRAKASH POKHAREL [140]


C Programming Language

10.2 Opening and closing of File,


Defining and opening a file: If we want to store data in a file into the secondary memory, we
must specify certain things about the file to the operating system. They include the fielname,
data structure, purpose.
The general format of the function used for opening a file is

FILE *fp; fp=fopen(“filename”,”mode”);

The first statement declares the variable fp as a pointer to the data type FILE. As stated
earlier, File is a structure that is defined in the I/O Library. The second statement opens the
file named filename and assigns an identifier to the FILE type pointer fp. This pointer, which
contains all the information about the file, is subsequently used as a communication link
between the system and the program. The second statement also specifies the purpose of
opening the file. The mode does this job.
r – read the xisting file.
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)

Consider the following statements:


FILE *p1, *p2; p1=fopen(“data”,”r”); p2=fopen(“results”,”w”);

In these statements the p1 and p2 are created and assigned to open the files data and results
respectively the file data is opened for reading and result is opened for writing. In case the
results file already exists, its contents are deleted and the files are opened as a new file. If
data file does not exist error will occur.

© BISHWO PRAKASH POKHAREL [141]


C Programming Language

Closing a file:
The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);

A file must be closed as soon as all operations on it have been completed. This would close
the file associated with the file pointer. Observe the following program.
….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….

fclose(p1);
fclose(p2);
above program opens two files and closes them after all operations on them are completed,
once a file is closed its file pointer can be reversed on other file.
10.3 Input Output Operations in File,
 Using string I/O functions fgets() and fputs(), data can be read from a file or written to
a file in the form of array of characters.
i. fgets(): is used to read string from file.
Syntax: fgets(string, int_value, fp);
Here, int_value denotes the no. of characters in the string.
ii. fputs(): is used to write string to file.
Syntax: fputs(string, fp);
/* Program to create a file named test.txt and write some text “I study B.Sc. CSIT” to
the file. */
#include <stdio.h>
#include<conio.h>
main()
{
FILE *fp;
fp=fopen("C:\\test.txt", "w");
if(fp==NULL)
{
printf("\n Cannot create file.");
exit();
}
else
{
printf("\n File is created.");
}
fputs("I study B.Sc. CSIT", fp);
fclose(fp);
getch();
}

© BISHWO PRAKASH POKHAREL [142]


C Programming Language

/* Program to open the file named test.txt, read its content and display it to screen */

#include <stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char s[100];
fp=fopen("C:\\test.txt", "r");
if(fp==NULL)
{
printf("\n Cannot open file.");
exit();
}
else
{
printf("\nFile is opened.");
}
fgets(s,19,fp);
printf("\n Text from file is:%s", s);
fclose(fp);
getch();
}

Character I/O functions:


 Using character I/O functions fgetc() and fputc(), data can be read from file or written
onto file one character at a time.
i. fgetc(): is used to read a character from a file.
Syntax: char_variable=fgetc(fp);
ii. fputc(): is used to write a character to a file.
Syntax: fputc(‘character’or character_variable, fp);
End – Of – File (EOF):
 EOF is a special character (an integer with ASCII value 26) that indicates that the
end-of-file has been reached. This character can be generated from the keyboard by
typing Ctrl+Z.
 Defined in <stdio.h>
 When we are creating a file, the special character EOF, is inserted after the last
character of the file by the Operating System.
 Thus, the last point of file is detected using EOF while reading data from file.
 It’s necessity arises from the fact that we may not know in advance up to where we
have data.
 Caution: An attempt to read after EOF might either cause the program to terminate
with an error or result in an infinite loop situation.

© BISHWO PRAKASH POKHAREL [143]


C Programming Language

/* Program to append some text to a file by reading filename from user*/


#include <stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char filename[20];
char c;
printf("Enter filename:\t");
gets(filename);
fp=fopen(filename,"a");
if(fp==NULL)
{
printf("\n Cannot create or open file.");
exit();
}
printf("\nEnter text to append to file %s:\n", filename);
while((c=getchar())!='\n')
fputc(c,fp);
fclose(fp);
getch();
}

Q] /* Program to open a file and copy all its content to another file*/
#include <stdio.h>
#include<conio.h>
main()
{
FILE *sfp,*dfp;
char sfilename[20],dfilename[20];
char c;
printf("Enter source filename:\t");
gets(sfilename);
printf("\n Enter destination filename:\t");
gets(dfilename);
sfp=fopen(sfilename,"r");
if(sfp==NULL)
{
printf("\nSource file can't be opened.");
exit();
}
dfp=fopen(dfilename, "w");
if(dfp==NULL)
{
printf("\n Destination file cannot be created or opened.");
exit();

© BISHWO PRAKASH POKHAREL [144]


C Programming Language

}
while((c=fgetc(sfp))!=EOF)
fputc(c, dfp);
printf("\n Copied........");
fclose(dfp);
fclose(sfp);
getch();
}
Q] Given a text file, create another text file deleting all the vowels (a, e, i, o, u).
#include <stdio.h>
#include<conio.h>
main()
{
FILE *fp,*fpp;
char c;
fp=fopen("C:\\test.txt","r+");
if(fp==NULL)
{
printf("Cannot open file");
exit();
}
fpp=fopen("C:\\hello.txt","w");
if(fpp==NULL)
{
printf("Cannot create file");
exit();
}
while((c=fgetc(fp))!=EOF)
{
if((c!='a')&&(c!='e')&&(c!='i')&&(c!='o')&&(c!='u'))
fputc(c, fpp);
}
fclose(fp);
fclose(fpp);
getch();
}

Formatted I/O functions:


 Using formatted I/O functions, fprintf() and fscanf(), numbers, characters or string can
be read from file or written onto file according to our requirement format.
i. fprintf(): is formatted output function which is used to write integer, float, char
or string value to a file. Syntax: fprintf(fp,
“control_string”, list_of_variables);
ii. fscanf(): is formatted input function which is used to read integer, float, char
or string value from a file. Syntax: fscanf(fp, “control_string”,
&list_of_variables);

© BISHWO PRAKASH POKHAREL [145]


C Programming Language

/* Program to create a file named student.txt and write name, roll, address and marks
of a student to this file*/
#include <stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char name[20];
int roll;
char address[20];
float marks;
fp=fopen("C:\\student.txt", "w");
if(fp==NULL)
{
printf("\n File cannot be created or opened.");
exit();
}
printf("\n Enter name of student:\t");
gets(name);
printf("\n Enter roll number of %s:\t", name);
scanf("%d", &roll);
fflush(stdin);
printf("\n Enter address of %s:\t", name);
gets(address);
printf("\n Enter marks of %s:\t", name);
scanf("%f", &marks);
printf("\n Now writing data to file...");
fprintf(fp, "Name=%s\n Roll=%d\n Address=%s\n Marks=%.2f", name, roll, address,
marks);
printf("\n Completed");
fclose(fp);
getch();
}

q] Given a text file, create another text file deleting the following words “three”, “bad”,
and “time”.
#include <stdio.h>
#include<conio.h>
main()
{
FILE *fp,*fpp;
char c[10];
fp=fopen("C:\\test.txt",“r");
if(fp==NULL)
{
printf("Cannot open file");

© BISHWO PRAKASH POKHAREL [146]


C Programming Language

exit();
}
fpp=fopen("C:\\hello.txt","w");
if(fpp==NULL)
{
printf("Cannot create file");
exit();
}
while(fscanf(fp,"%s",&c)!=EOF)
{
if((strcmp(c,"three")!=0)&&(strcmp(c,"bad")!=0)&&(strcmp(c,"time")!=0))
{
fprintf(fpp,"%s ",c);
}
}
fclose(fp);
fclose(fpp);
getch();
}
Q] Some text file is given, create another text file replacing the following words “Ram”
to “Hari”, “Sita” to “Gita”, and “Govinda” to “Shiva”.
#include <stdio.h>
#include<conio.h>
main()
{
FILE *fp,*fpp;
char c[10];
fp=fopen("C:\\test.txt","r");
if(fp==NULL)
{
printf("Cannot open file");
exit();
}
fpp=fopen("C:\\hello.txt","w");
if(fpp==NULL)
{
printf("Cannot create file");
exit();
}
while(fscanf(fp,"%s",&c)!=EOF)
{
if(strcmp(c, "Ram")==0)
fprintf(fpp, "Hari ",c);
else if(strcmp(c, "Sita")==0)
fprintf(fpp,"Gita",c);
else if(strcmp(c, "Govinda")==0)

© BISHWO PRAKASH POKHAREL [147]


C Programming Language

fprintf(fpp, "Shiva",c);
else
fprintf(fpp,"%s ",c);
}
fclose(fp);
fclose(fpp);
getch();
}

10.4 Random access in File,


 Till now, reading and writing data from/to a file has been done sequentially.
 While reading data from a file, the data items are read from the beginning of the file
in sequence until the end of file.
 Also, while writing data to a file, the data items are placed one after the other in a
sequence.
 This is called sequential access.
 But we may need to access a particular data item placed in any location without
starting from the beginning.
 This is called random access or direct access.

Use of file pointer in random access file:


 A file pointer is a pointer to a particular byte in a file.
 While opening a file in write mode, the file pointer is at the beginning of the file, and
whenever we write to a file, the file pointer moves to the end of the data items written
so that writing can continue from that point.
 While opening a file in read mode, the file pointer is at the beginning of the file, and
whenever we read from a file, the file pointer moves to the beginning of the next data
item so that reading cam continue from that point.
 While opening a file in append mode, the file pointer is at the end of the existing file,
so that new data items can be written from there onwards.
 So, if we are able to move the file pointer according as our need, then any data item
can be read from a file or written onto a file randomly.

Functions used in random access:


1. ftell(): This function takes a file pointer as argument and returns a number of type
long, that indicates the current position of the file pointer within the file. This function
is useful in saving the current position of a file, which can be used later in the
program.
Syntax
n = ftell(fp);
Here, n would give the relative offset (in bytes) of the current position. This means
that n bytes have already been read (or written).
2. rewind(): Do you remember that one way of positioning the file pointer to the
beginning of the file is to close the file and then reopen it??? The rewind() function
can do this without closing the file. This function takes a file pointer as argument and
resets the current position of the file pointer to the start of the file.

© BISHWO PRAKASH POKHAREL [148]


C Programming Language

Syntax: rewind(fp);
 What these statements do?: rewind(fp);
n=ftell(fp);
 Here, n would be assigned 0, because file position has been set to the start of the file
by rewind().
 Note: The first byte in the file is numbered as 0, second as 1, and so on.
3. fseek(): This function is used to move the file pointer to a desired position within a
file.
Syntax
fseek(fp, offset, position);
where fp is a file pointer, offset is a number or variable data type long, and position is
an integer number
 The offset specifies the number of positions (bytes) to be moved from the location
specified by position.
 The position can have one of the following 3 values:
Value Meaning
0 Beginning of file
1 Current position
2 End of file
Q] Write a program to open a file employee.txt created in above program and
edit/modify the details of a particular employee.
#include <stdio.h>
#include<conio.h>
main()
{
struct employee
{
char empname[20];
int age;
float salary;
};
struct employee e;
FILE *fp;
char name[20];
int search=0;
int record_count=0;
fp=fopen("C:\\employee.txt","rb+");
if(fp==NULL)
{
printf("Cannot open file");
exit();
}
printf("\tEnter employee name to be modified:\t");
gets(name);
while(fread(&e,sizeof(e),1,fp)==1)
{

© BISHWO PRAKASH POKHAREL [149]


C Programming Language

if(strcmp(name, e.empname)==0)
{
search=1;
printf("\n Old record is:");
printf("\n Name:%s",e.empname);
printf("\n Age:%d",e.age);
printf("\n Salary:%.2f",e.salary);
printf("\n Enter new record(name,age and salary):");
scanf("%s %d %f", e.empname, &e.age, &e.salary);
fseek(fp,sizeof(e)*record_count,0);
if(fwrite(&e,sizeof(e),1,fp)==1)
printf("\nRecord modified!!!");
}
record_count++;
}
if(search==0)
printf("\n There is no employee with name %s", name);
fclose(fp);
getch();
}
10.5 Error Handling in Files
Error situations during I/O operations:
 Trying to read beyond the end-of-file mark.
 Trying to use a file that has not been opened.
 Trying to perform an operation on a file, when the file is opened for another type of
operation.
 Opening a file with an invalid filename.
Error handling functions:
 I/O errors can be detected using two status-inquiry library functions: feof() and
ferror().
 feof(): It is used to test for an end-of-file condition. It takes a FILE pointer as its only
argument and returns a nonzero integer value if all of the data from the specified file
has been read, and returns zero otherwise. If fp is a pointer to a file that has just been
opened for reading, then the statement
if(feof(fp))
printf(“End of data”);
would display the message “End of data” on reaching the end-of-file condition.
 ferror(): This function reports the status of the file indicated. It takes a FILE pointer
as its argument and returns a nonzero integer if an error has been detected up to that
point, during processing. It returns zero otherwise. So the statement
if(ferror(fp)!=0)
printf(“An error has occurred”);
would print the error message, if the reading is not successful.
Some strategies:
 Addition of new records should take place at the end of existing records in the file, i.e.
in the same way new records are added in a register manually.

© BISHWO PRAKASH POKHAREL [150]


C Programming Language

 While modifying records, first we must ask the user which record he intends to
modify. Instead of asking the record number to be modified, it would be more
meaningful to ask for the name of the student whose record is to be modified. On
modifying the record, the existing record gets overwritten by the new record.
 In deleting records, except for the record to be deleted, rest of the records must first be
written to a temporary file, then the original file must be deleted, and the temporary
file must be renamed back to original.
 Displaying all records means displaying the existing records on the screen. Naturally,
records should be displayed from first record to last record.

© BISHWO PRAKASH POKHAREL [151]


C Programming Language

INTRODUCTION TO GRAPHICS
CHAPTER OUTLINE
11.1 Concepts of Graphics,
11.2 Graphics Initialization and Modes,
11.3 Graphics Function

11.1 Concepts of Graphics,


If all pictures are built by concept of pixel then wondering how each picture differ that is how
some picture appear more brighter while some other have a shady effect. All this is by the
concept or technically terminology called as resolution.
Resolution is the number of rows that appear from top to bottom of a screen and in turn the
number of pixels or pixel elements that appear from left to right on each scan line. Based on
this resolution only the effect of picture appears on screen. In other words greater the
resolution greater will be the clarity of picture. This is because greater the number of dots
greater will be sharpness of picture. That is resolution value is directly proportional to clarity
of picture.
There are generally two modes available namely text and graphics. In a graphics mode we
have generally the following adapters namely CGA called as Color Graphics Adapter, EGA
and VGA. Each adapter differs in the way of generating colors and also in the number of
colors produced by each adapter. Pixel being a picture element when we consider the
graphics mode each pixel has a color associated with it. But the way these colors are used
depends on adapters because each adapter differs in the way they handle colors and also in
the number of colors supported.

11.2 Graphics Initialization and Modes,


Having known about adapters now let us start knowing on how to start switching to graphics
mode from text mode in other words how to start using pixel and resolution concepts. This is
done by a function called intigraph ( ).This intigraph ( ) takes in it 2 main arguments as input
namely gd and gm. In this gd has the number of mode which has the best resolution. This is
very vital for graphics since the best resolution only gives a sharper picture as we have seen
before. This value is obtained by using the function called as getgraphmode ( ) in C graphics.
The other argument gm gives insight about the monitor used, the corresponding resolution of
that, the colors that are available since this varies based on adapters supported. This value is
obtained by using the function named as getmodename ( ) in C graphics.

© BISHWO PRAKASH POKHAREL [152]


C Programming Language

11.3 Graphics Function


There are numerous graphics functions available in c. But let us see some to have an
understanding of how and where a pixel is placed in each when each of the graphics function
gets invoked.
Function: putpixel(x, y, color)
Purpose: The functionality of this function is it put a pixel or in other words a dot at position
x, y given in inputted argument. Here one must understand that the whole screen is imagined
as a graph. In other words the pixel at the top left hand corner of the screen represents the
value (0, 0).
Here the color is the integer value associated with colors and when specified the picture
element or the dot is placed with the appropriate color associated with that integer value.
Function: Line(x1, y1, x2, y2)
Purpose: The functionality of this function is to draw a line from (x1,y1) to (x2,y2).Here also
the coordinates are passed taking the pixel (0,0) at the top left hand corner of the screen as the
origin. And also one must note that the line formed is by using number of pixels placed near
each other.
Function: getpixel(x, y)
Purpose: This function when invoked gets the color of the pixel specified. The color got will
be the integer value associated with that color and hence the function gets an integer value as
return value.
So the smallest element on the graphics display screen is a pixel or a dot and the pixels are
used in this way to place images in graphics screen in C language.
Some Examples of C graphics:
// Drawing a Circle
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
main()
{
int gd= DETECT, gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
circle(200,100,10);
setcolor(WHITE);
getch();
closegraph();
}
//Drawing Lines
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()

© BISHWO PRAKASH POKHAREL [153]


C Programming Language

{
int gd= DETECT, gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
line(90,70,60,100);
line(200,100,150,300);
setcolor(WHITE);
getch();
closegraph();
}
// Drawing rectangle
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd= DETECT, gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
rectangle(200,100,150,300);
setcolor(WHITE);
getch();
closegraph();
}
//Constructing Triangle
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd= DETECT, gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
line(200,100,10,20);
line(10,20,50,60);
line(50,60,200,100);
setcolor(WHITE);
getch();
closegraph();
}
Exercise
1. Why do you require graphical function? Explain the basic graphical function with
suitable program.
2. Explain the use of graphical function. Make a program that contains basic graphic
functions.
3. What are the uses of graphical function? Explain the basic graphical function with
suitable program.
4. Write short notes on: Graphical function.
5. List any five names of graphics function.

© BISHWO PRAKASH POKHAREL [154]

You might also like