You are on page 1of 153

C PROGRAMMING GET ON TO

C PROGRAMMING

Don’t write better error messages,


write code that doesn’t need them.
Sahu Technologies Internship

INDEX
SR.NO. TOPIC PAGE NO.
1) Introduction 1
2) Environmental Setup 3
3) Algorithms 4
4) Flowcharts 8
5) Program Structure 9
6) Library Functions 12
7) Data Types 13
8) Variables & its Types 15
9) Constants 17
10) Keywords 19
11) Literals 22
12) Storage Classes 24
13) Operators 26
14) Decision Making Statements 37
15) Loops 57
16) Functions 72
17) Recursive Functions 79
18) Scope Rules 86
19) Arrays 88
20) Pointers 99
21) Strings 104
22) Structures 109
23) Unions 111
24) Bit Fields 114
25) Type Definitions 116
26) Input & Output Types 118
27) File I/O 121
28) Preprocessors 124
29) Header Files 125
30) Type Casting 126
31) Error Handling 130
32) Recursion 133
33) Variable Arguments 137
34) Memory Management 138
35) Command Line Arguments 144
36) Interview Questions 146
37) Practice Programs 149

Sahu Technologies Internship 1

INTRODUCTION
ABOUT C-LANGUAGE

The base or father of programming languages is ‘Algorithmic


Language (ALGOL)’ which introduced the concept of structured
programming to the developer community in 1960. In 1967, a new
computer programming language was announced called as ‘Basic
Combined Programming Language (BCPL)’. It was designed and
developed by Martin Richards, especially for writing system
software. This was the era of programming languages. After 3 years, in
1970, a new programming language called ‘B’ was introduced by Ken
Thompson that contained multiple features of ‘BCPL’. Both ‘BCPL’
and ‘B’ were system programming languages.

In 1972, a great computer scientist DENNIS RITCHIE created a


new programming language called ‘C’ at the Bell Laboratories. It was
first implemented on the Digital Equipment Corporation PDP-11
computer in 1972.C is called mother language of all
programming languages.
It was created from ‘ALGOL’, ‘BCPL’ and ‘B’ programming languages. ‘C’
programming language contains all the features of these languages and
many more additional concepts that make it unique from other
languages.

‘C’ is a powerful programming language which is strongly associated


with the UNIX operating system. Later, as C started spreading around
the world, it became commercial and many compilers were released for
cross-platform systems. It is extremely popular, simple and flexible. It is
machine-independent, structured programming language which is used
extensively in various applications.


Sahu Technologies Internship 2

• ALGOL
• Algorithmic Language
1960 • Developed by International group

• BCPL
• Basic Combined Programming Language
1967 • Developed by Martin Richard

•B
• Developed by Ken Thompson
1970

•C
• Developed by Dennis Ritchie
1972

Where do we use C language?

C language is mainly used for,

• Design Operating system


• Design Language Compiler
• Design Database
• Language Interpretaters
• Utilities
• Network Drivers
• Assemblers


Sahu Technologies Internship 3

ENVIRONMENTAL SETUP
If you want to set up your environment for C programming language, you need
the following two software tools: i) Text Editor
ii) The C compiler
TEXT EDITOR:
This will be used to type your program. E.g. Notepad, OS Edit command, Brief,
Epsilon, EMACS and vim or vi. The name and the version of text editors can vary
based on different operating systems. E.g. Notepad will be used on windows, and
vim or vi can be used on windows as well as on Linux or UNIX. The files you create
with your editor are called the source files and they contain the program source
codes. The source files for C programs are typically named with the extension
“.c”. Before starting your programming, make sure you have one text editor in
place and you have enough experience to write a computer program, save it in a
file, compile it and finally execute it.
THE C COMPILER:
The source code written in source file is human readable source for your program.
It needs to be “compiled”, into machine language so that your CPU can actually
execute the program as per the instructions given. The compiler compiles the
source codes into final executable programs. The most frequently used and free
available compiler is the GNU C/C++ compiler.









Sahu Technologies Internship 4

ALGORITHMS
A computer scientist Niklaus Wirth stated that PROGRAM =ALGORITHM + DATA.

An algorithm is a part of the plan for a computer program. In fact, an algorithm is ‘an
effective procedure for solving a problem in a finite number of steps’. It is effective,
which means that an answer is found and it has a finite number of steps. A well-
designed algorithm will always provide an answer; it may not be the desired answer but
there will be an answer. It may happen that the answer is that, there is no answer. A
well-designed algorithm is also guaranteed to terminate. Algorithm is blueprint of the
program. It is also considered as plan of the program.

DIFFERENT WAYS OF STATING ALGORITHMS:

Algorithms can be represented in various ways. There are 4 ways of stating


algorithms:

Ø Step-form
Ø Pseudo-code
Ø Flowchart
Ø Nassi-Schneiderman

In the step-form representation, the procedure of solving a problem is stated with


written statements. Each statement solves a part of the problem and these together
complete the solution. The step-form uses just normal language to define each
procedure. Every statement, that defines an action, is logically related to the preceding
statement.

The pseudo-code is a written form representation of the algorithm. However, it differs


from the step form as it uses a restricted vocabulary to define its action of solving the
problem. One problem of human language is that it can seem to be imprecise. But the
pseudo-code, which is in human language, tends towards more precision by using a
limited vocabulary.

Flowchart and Nassi-Schneiderman are graphically oriented representation forms. They


use symbols and language to represent sequence, decision and repetition actions.
Generally, Flowchart method is mostly used.


Sahu Technologies Internship 5

POINTS TO BE CONSIDERED WHILE DEVELOPING AN ALGORITHM:

• Sequence
• Correctness
• Termination
• Selection
• Iteration

Example:

Q] Write an algorithm to add two numbers and display the result.


1) START
2) Declare A and B as integer variables.
3) Print “Enter the two numbers”
4) Input A, B
5) R=A+B
6) Print “Result=”
7) Print R
8) STOP

Q] Write an algorithm of interchanging the numeric values of two


variables.
1) START
2) Read ‘A’ and ‘B’ values.
3) Interchange the values.
temp=a
a=b
b=temp
4) Write the values of A and B
5) STOP


Sahu Technologies Internship 6

Q] Write an algorithm to print the largest among three numbers.


1) START
2) Declare variables a, b, c.
3) Read variables a, b, c
4) if a>b
if a>c
Display “a is the largest number”
else
Display “c is the largest number”
else
if b>c
Display “b is the largest number”
else
Display “c is the largest number”
5) STOP

Q] Write an algorithm to find the sum of series 2+4+6+8+… upto n


terms.
1) START
2) Enter the value of n
3) Initialize number=2, sum=0
4) Compute sum=sum+n;
5) Compute n=n+2;
6) Check number<=n
goto step 3
else goto step 7
7) Display sum.
8) STOP


Sahu Technologies Internship 7

EFFICIENCY OF ALGORITHMS
One significant factor considered while designing algorithms is algorithm’s efficiency.
The efficiency of an algorithm is determined by the amount of time it takes to run the
program and the memory space the program requires. In analyzing an algorithm, rather
than a piece of code, the number of times, ‘the principle activity’ of that algorithm is
performed, should be predicted. Here, if one is analyzing a sorting algorithm, one might
count the number of comparisons performed, and if it is an algorithm to find an optimal
solution, or might count the number of times it evaluates to perform a solution.

Complexity of an algorithm is a measure of the amount of time and/or memory space


required by an algorithm for a given input. It is a function describing the efficiency of the
algorithm in terms of the amount of data the algorithm must process.

The following are two main complexity measures of the efficiency of an algorithm:

• TIME COMPLEXITY: It is a function describing the amount of time an algorithm


takes with respect to the amount of input provided to the algorithm. ‘Time’ can
measure the number of memory accesses performed, the number of
comparisons between integers, the number of times some inner loop is executed,
or some other natural unit related to the amount of real time the algorithm will
take. It is denoted by T(n), where n≡ size of the input.
• SPACE COMPLEXITY: It is a function describing the amount of memory (space) an
algorithm takes with respect to the amount of input provided to the algorithm.
Space complexity is sometimes ignored because the space used is minimal and/or
obvious, but sometimes it becomes an important an issue as time. It is denoted
by S(n), where n≡ size of the input.
Complexity analysis attempts to characterize the relationship between the
number of data elements and resource usage (time or space).
Ø The worst-case complexity of the algorithm is the function defined by the
number of steps taken on any instance of input size n.
Ø The best-case complexity of the algorithm is the function defined by the
minimum number of steps taken on any instance of input size n.
Ø The average-case complexity of the algorithm is the function defined by
the average number of steps taken on any instance of input size n.


Sahu Technologies Internship 8

FLOWCHARTS
Flowcharts are the graphical representation of a solution to a particular problem.
They are symbolic diagrams which show type of data (numeric, character etc.),
data flow, control flow and programming logics and algorithms. Flowcharts are
important for planning and working of a program. Flowchart decreases our efforts
i.e. they are easy to understand and check logics and algorithms.

SYMBOL PURPOSE DESCRIPTION


Indicates the flow of logic
͢ Flow line
by connecting symbols.
Represents the start and
Terminal(START/STOP)
the end of a flowchart
Used for input and output
Input/ Output
operation
Used for arithmetic
Processing operations and data
manipulations
Used for decision making
Decision between two or more
alternatives
Used to join different
On-page connector
flowline.
Used to connect the
Off-page connector flowchart portion on a
different page
Represents a group of
Predefined
statements performing
Process/Function
one processing task.


Sahu Technologies Internship 9

PROGRAM STRUCTURE
C BASIC SYNTAX:
Syntax basically refers to the protocols to be followed while writing a
program. It is very necessary to follow proper syntax while coding to get
the desired set of output. The C basic syntax consists of header files,
main function and program code. This is the most fundamental structure
in the C program. A C program necessarily consists of the main function
because the execution of the program starts from this line. Without the
main function, the program execution does not start.

A) HEADER FILES:
Here we have used two header files. C has a series of predefined
functions embedded in the header files in the C library. We use these
functions to perform a specific task with the help of a header file.
Q] What are header files?
Header files contain a bunch of files that help the user to include the
predefined functions according to his requirements. You can add header
files using the preprocessor directive #include.
B) MAIN FUNCTION
When your operating system runs a program in C, it gives the control of
the computer to the C program. If a program consists of only one line of
the code in the main function, then the program can run successfully.
As the program execution starts from this line, it becomes compulsory
for every C program to have the main function.

• clscr()-This function is predefined in the header file <conio.h>. It


helps to clear the output screen.
• printf()- This is another function that helps you to display the
message on the output screen. This function is defined in
<stdio.h>.
• getch()- This function is defined in <conio.h> . It is used to hold the
output screen until we hit the next key after we run the program.


Sahu Technologies Internship 10

C) TOKENS IN C

A C syntax /program consist of a series of tokens. They can be identifiers,


variables, symbols. They are the smallest units of a program that convey a specific
meaning to the compiler.

KEYWORDS

IDENTIFIERS/
OPERATORS
VARIABLES
TOKEN
S IN C

PUNCTUATOR
CONSTANTS
S


Sahu Technologies Internship 11


PARTS OF C PROGRAM:
i) #include<stdio.h>
This command is a preprocessor directive in C that includes all
standard input-output files before compiling any C program so as
to make use of all those functions in our C program.
ii) #include<conio.h>
This is a header file used in C programming language contains
functions for console input/output
iii) {
iv) (Opening bracket)- This indicates the beginning of any function in
the program.
v) int main();
This is the line from where the execution of the program starts.
The main () function starts the execution of any C program.
vi) printf(“WELCOME TO C PROGRAMMING”);
//The printf() command is included in the C stdio.h library, which
helps to display the message on the output screen.
vii) getch();
viii) //This command helps to hold the screen
ix) return 0;
x) //This command terminates the C program and returns a null
value (i.e. 0).
xi) }
xii) (Closing bracket)- This indicates the end of the function


Sahu Technologies Internship 12

LIBRARY FUNCTIONS IN C
Library functions are the in-built functions in C that are grouped and placed at
common place called ‘library’. Such functions are used to perform some specific
operations. The library functions are created by the designers of compilers. All C
standard library functions are defined inside the different header files saved with
the extension .h. We need to include these header files in our program to make
use of the library functions defined in such header files.

SR. NO. HEADER FILE DESCRIPTION


This is standard input/output header file. It contains
1) stdio.h
all library functions regarding standard input/output.
2) conio.h This is a console input/output header file.
It contains all string related library functions. Like
3) string.h
gets(), puts(), etc.
This header file contains all the general library
4) stdlib.h
functions like malloc(), calloc(), exit(),etc.
This header file contains all the math operations
5) math.h
related functions like sqrt(), pow(), etc.
6) time.h This header file contains all time-related functions.
This header files contains all character handling
7) ctype.h
functions.
Variable argument functions are defined in this
8) stdarg.h
header file.
All the signal handling functions are defined in this
9) signal.h
header file.
10) setjmp.h This file contains all the jump functions.
11) locale.h This file contains locale functions
12) errno.h This file contains error handling functions.
13) assert.h This file contains diagnostic functions.


Sahu Technologies Internship 13

DATA TYPES IN C PROGRAM


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

C Language supports two different types of data types:

PRIMARY DATA TYPES


CHARACTER INTEGER FLOAT VOID

DERIVED DATA TYPES


ARRAY STRUCTURE UNION POINTER


Sahu Technologies Internship 14

SIZE FORMAT
TYPE RANGE
(BYTES) SPECIFIER

int or signed
2 %d, %i -32,768 to 32,767
int
unsigned int 2 %u 0 to 65,535
short int or
signed short 1 %hd -128 to 127
int
unsigned
1 %li 0 to 255
short int
signed long -2,147,483,648 to
4 %lu
int or long int 2,147483,647
unsigned
4 %llu 0 to 4,294,967,295
long int

char 1 %c -128 to 127 OR 0 to 255

signed char 1 %c -128 to 127


unsigned
1 %c 0 to 255
char

float 4 %f 3.4E-38 to 3.4E+38

double 8 %lf 1.7E-308 to 1.7E+308


at least 10,
long double usually 12 or %Lf 3.4E-4932 to 1.1E+4932
16
NOTE: A string can be of any size. It has format specifier %s.


Sahu Technologies Internship 15

VARIABLES IN C PROGRAMMING
A variable is a name of the memory location. It is used to store data. Its value can
be changed, and it can be reused many times. It is a way to represent memory
location through so that it can be easily identified.

SYNTAX TO DECLARE A VARIABLE:



type variable_list;
Example: int a; >> eg. int a=10,b=20;
float b; >> eg. float f=20.8;

char c; >> eg. char c= ‘A’

Here a, b, c are variables & int, float, char


are data types.
RULES FOR DEFINING VARIABLES:

• A variable can have alphabets, digits and underscore.


• A variable name can start with the alphabet, and underscore (_) only. It
cannot start with a digit.
• No whitespace is allowed within the variable name.
• A variable name must not be any reserved word or a keyword.

TYPES OF VARIABLES IN C:

1) LOCAL VARIABLE: A variable that is declared inside the function or block is


called a local variable. It must be declared at start at the start of the block.
You must initialize the local variable before it is used.
EXAMPLE:


Sahu Technologies Internship 16

2) GLOBAL VARIABLE: A variable that is declared outside the function or


block is called a global variable. Any function can change the value of
global variable. It is available to all functions. It must be declared at the
start of the block.
EXAMPLE:



3) STATIC VARIABLE: A variable that is declared with the static keyword is
called static variable. It retains its value between multiple function calls.
EXAMPLE:



4) AUTOMATIC VARIABLE: All variables in C that are declared inside the block
are automatic variables by default. We can explicitly declare an automatic
variable using auto keyword.
EXAMPLE:


Sahu Technologies Internship 17

5) EXTERNAL VARIABLE: We can share a variable in multiple C source files by


using an external variable. To declare an external variable, you need to use
extern keyword.
EXAMPLE:

CONSTANTS IN C PROGRAMMING

A constant is a value or a variable that cannot be changed in the program.
There are different types of constants in C programming.

CONSTANT EXAMPLE
Decimal Constant 10, 20, 450 etc.
Real or Floating point Constant 10.3,20.2,450.6 etc.
Octal Constant 021, 033, 046 etc.
Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.
Character Constant ‘a’, ‘b’, ‘x’ etc.
String Constant “C”, “C program” etc.




Sahu Technologies Internship 18

RULES FOR CONSTRUCTING INTEGER CONSTANTS:


• An integer constant must have atleast one digit.
• It must not have a decimal point.
• It can be either positive or negative.
• If no sign precedes an integer constant it is assumed to be positive.
• No commas (,) or blanks ( ) are allowed within an integer constant.
• The range of integer constants is -32768 to 32767

RULES FOR CONSTRUCTING REAL CONSTANTS:


Real constants are often called Floating Point constants. The real constants
could be written in two forms: - i) Fractional form ii) Exponential form
• A real constant must have atleast one digit.
• It must have a decimal point.
• It could be either positive or negative.
• Default sign is positive.
• No commas or blanks are allowed within a real constant.

RULES FOR CONSTRUCTING CHARACTER CONSTANTS:


• A character constant is a single alphabet, single digit or a single special
symbol enclosed within single inverted commas.
• Both the inverted commas should point to the left. E.g. ’A’.
• The maximum length of a character constant can be one character.


Sahu Technologies Internship 19

KEYWORDS IN C PROGRAMMING

Keywords are the words whose meaning has already been explained to the C
compiler. The keywords cannot be used as variable names because if we do so we
are trying to assign a new meaning to the keyword, which is not allowed by the
computer. The keywords are also known as ‘Reserved words’. There are only 32
keywords available in C.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while


There are two ways to define a constant in C programming.
i) C const keyword
The const keyword is used to define constant in C programming. If
you try to change the value of PI, it will render compile time error.
Eg. const float PI=3.14;
ii) C #DEFINE PREPROCESSOR
The #define preprocessor is also used to define constant or micro
substitution. It can use any basic data type.
SYNTAX: #define token value
EXAMPLE: # define TESTING. Here TESTING is a symbol.


Sahu Technologies Internship 20

KEYWORD DESCRIPTION
auto Used to define a local (automatic) variable.
Used to pass the control out of ‘while’, ‘do’, ‘for’, ‘switch’
break statements.
case Used in switch statement to define a particular switch case.
char Basic data type. Used to indicate character type.
const Used to make variables unmodifiable.
continue Used to skip certain statements inside the loop.
Used in switch case. Default case gets executed when the value
default doesn’t match any of ‘case’ values.
do do-while loop (Iteration statement).
double Data type for floating type variables (double precision).
else Decision making statement (used with ‘if’)
enum Used to define enumerated type data (set of integer constants).
Used to tell the compiler that the variable is already declared
extern somewhere else.
float Data type for floating type variables (single precision).
for for loop (iteration statement)
goto Unconditional jump statement
if Decision statement. (used with “else” or alone)
int Basic data type. Used to indicate integer type.
Type modifier. Used to alter the meaning of base data type (in
long order to increase their range and size).
register Used to tell the compiler to store the variable in a CPU register.
Used to return the flow of control back to the calling function
return from the called function (with a returning value).
short Type modifier. Used to alter the meaning of base data type.
signed Type modifier. Used to alter the meaning of base data type.
Special operator. Used to determine the size of any entity in
sizeof terms of bytes.
Indicate the static storage class. Static variable stay alive (in
static memory) until the end of the program.


Sahu Technologies Internship 21

Keyword which is used to create a structure, i.e. a collection of


struct variables having different data types.
Decision making statement which is used to test the value of an
switch expression against the different “case” values.
Used to define a new type. Basically, it enables us to provide a
typedef new name for the existing data types.
Used to create a union which is a collection of variables of
union different data type that shares a common storage space.
Type modifier. Used to alter the meaning of base data type (in
unsigned order to increase positive range).
Means nothing. Commonly used as a function return type and
void indicate that the function does not return a value.
Used to indicate a volatile entity. A volatile entity can be altered
volatile in unspecified way by the hardware or background routine.
Used as an entry controlled loop. Executes repeatedly until
while statement becomes FALSE.


Sahu Technologies Internship 22

LITERALS IN C PROGRAMMING
Literals are data used for representing fixed values. They can be used directly in
the code. Eg. 1, 2.5,‘c’ etc.

i) INTEGERS:
An integer is a numeric literal (associated with numbers) without any
fractional or exponential part. There are three types of integer
literals in C programming:
• decimal (base 10)
• octal (base 8)
• hexadecimal (base 16)
In C programming, octal starts with a 0 and hexadecimal starts with a 0x.

ii) FLOATING POINT LITERALS:
A floating point literal is a numeric literal that has either a fractional
form or an exponential form.
E.g. -2.0, 0.0000234, -0.22E-5. (NOTE: E-5 = 10-5)

iii) CHARACTERS:
A character literal is created by enclosing a single character inside
single quotation marks.
E.g. ‘a’,‘m’,‘F’,‘2’, ‘}’ etc.

iv) ESCAPE SEQUENCES:


Sometimes, it is necessary to use characters that cannot be typed or
has some special meaning in C programming.
E.g. newline (enter), tab, question mark etc.


Sahu Technologies Internship 23

In order to use these characters, escape sequences are used.

ESCAPE ESCAPE
CHARACTER CHARACTER
SEQUENCES SEQUENCES

\b Backspace \\ Backslash
\f Form feed \’ Single quotation mark
\n New line \” Double quotation mark
\r Return \? Question mark
\t Horizontal tab \0 Null character
\v Vertical tab

The backslash (\) causes escape from the normal way the characters are handled
by the compiler.

v) STRING LITERALS:
A string literal is a sequence of characters enclosed in double-quote
marks.

“good” //string constant

“” // null string constant

“ ” // string of six whitespaces

“x” // string constant having a single character

“Earth is round\n” // prints string with a newline


Sahu Technologies Internship 24

STORAGE CLASSES IN C
Storage Classes are used to describe the features of a variable/function. These
features basically include the scope, visibility and life-time which help us to trace
the existence of a particular variable during the runtime of a program.

STORAGE INITIAL
STORAGE SCOPE LIFE
SPECIFIER VALUE

automatic stack Garbage Within block End of block


Data Till end of
external Zero Global Multiple files
segment program
Data Till end of
static Zero Within block
segment program
CPU
register Garbage Within block End of block
register

i) auto: This is the default storage class for all the variables declared
inside the function or a block. Hence, the keyword auto is rarely
used while writing programs in C language. Auto variables can
be only accessed within the block/function they have been
declared and not outside them (which defines their scope). Of
course, these can be accessed within nested blocks within the
parent block/function in which the auto variable was declared.
However, they can be accessed outside their scope as well
using the concept of pointers given here by pointing to the very
exact memory location where the variables resides. They are
assigned a garbage value by default whenever they are
declared.
ii) extern: Extern storage class simply tells us that the variable is defined
elsewhere and not within the same block where it is used.
Basically, the value is assigned to it in a different block and this
can be overwritten / changed in a different block as well. So an
extern variable is nothing but a global variable initialized with a
legal value where it is declared in order to be used elsewhere. It


Sahu Technologies Internship 25

can be accessed within any function/block. Also, a normal


global variable can be made extern as well by placing the
‘extern’ keyword before its declaration/definition in any
function/block. This basically signifies that we are not
initializing a new variable but instead we are using/ accessing
the global variable only. The main purpose of using extern
variables is that they can be accessed between two different
files which are part of a large program.
iii) static: This storage class is used to declare static variables which are
popularly used while writing program in C language. Static
variables have a property of preserving their value even after
they are out of their scope! Hence static variables preserve the
value of their last use in their scope. So we can say that they
are initialized only once and exist till the termination of the
program. Thus, no new memory is allocated because they are
not re-declared. Their scope is local to the function to which
they were defined. Global static variables can be accessed
anywhere in the program. By default they are assigned the
value 0 by the compiler.

iv) register: This storage class declares register variables which have the
same functionality as that of the auto variables. The only
difference is that the compiler tries to store these variables in
the register of the microprocessor if a free register is available.
This makes the use of register variables to be much faster than
that of the variables stored in the memory during the runtime
of the program. If a free register is not available, these are then
stored in the memory only. Usually few variables which are to
be accessed very frequently in a program are declared with the
register keyword which improves the running time of the
program. An important and interesting point to be noted here
is that we cannot obtain the address of a register variable using
pointers.


Sahu Technologies Internship 26

OPERATORS IN C
An operator is a symbol that tells the compiler to perform specific mathematical
or logical functions. C language is rich in built-in operators and provides the
following types of operators:

1) ARITHMETIC OPERATORS: These are used to perform


mathematical calculations like addition, subtraction,
multiplication, division and modulus
EXAMPLE
OPERATORS DESCRIPTION
For A=10, B=20
+ Adds two operands. A+B=30
- Subtracts second operand from the first. A-B=-10
* Multiplies both operands. A*B=200
/ Divides numerator by denominator. B/A=2
Modulus operator and remainder of after an
% B%A=0
integer division.
Increment operator increases the integer A++=10
++
value by 1. ++A=12
Decrement operator increases the integer A--=12
--
value by 1. --A=10

OPERATOR TYPE OPERATOR DESCRIPTION
Value of i is incremented before
Pre-increment ++i
assigning it to variable i
Value of i is incremented after
Post-increment i++
assigning it to variable i
Value of i is decremented before
Pre-decrement --i
assigning it to variable i
Value of i is decremented after
Post-decrement i--
assigning it to variable i


Sahu Technologies Internship 27



2) LOGICAL OPERATORS: These operators are used to perform logical
operations on the given two variables.
EXAMPLE
OPERATORS DESCRIPTION
For A=1, B=0
Called Logical AND operator. If both the
(A&&B) is
&& operands are non-zero, then the condition
becomes TRUE. FALSE
Called Logical OR operator. If any of the two
|| operands are non-zero, then the condition (A||B) is TRUE
becomes TRUE.
Called Logical NOT operator. It is used to
reverse the logical state of its operand. If a !(A&&B) is
! condition is TRUE, then the Logical NOT TRUE
operator will make it FALSE.
3) BITWISE OPERATORS: These operators are used to perform bit
operations on given two variables. Bitwise operator works on bits and
performs bit-by-bit operation.
FOR A=60 (0011 1100), B=13 (0000 1101)
OPERATORS DESCRIPTION EXAMPLE
Binary ANDOperator copies a bit to the (A&B)=12, i.e.
&
result if it exists in both operands. 0000 1100
Binary OROperator copies a bit if it exists (A|B)=61, i.e.
|
in either operand. 0011 1101
Binary XOR Operator copies the bit if it is (A^B)=49, i.e.
^
set in one operand but not both. 0011 0001
Binary One’s complement Operator is (~A)=~(60)
~
unary and has the effect of ‘flipping’ bits. i.e. -0111101
Binary Left Shift Operator. The left
operands value is moved left by the A<<2 =240 i.e.
<<
number of bit specified by the right 1111 0000
operand.
Binary Right Shift Operator. The left
operands value is moved right by the A>>2 =15 i.e.
>>
number of bits specified by the right 0000 1111
operand.


Sahu Technologies Internship 28

4) ASSIGNMENT OPERATORS: These are used to assign the values


for the variables in C programs.

OPERATORS DESCRIPTION EXAMPLE


Simple assignment operator. Assigns
C=A+B will assign the
= values from right side operands to left
value of A+B to C
side operand.
Add AND assignment operator. It adds
the right operand to the left operand C+= A is equivalent to
+= and assigns the result to the left C=C+A
operand.
Subtract AND assignment operator. It
subtracts the right operand from the C-= A is equivalent to
-= left operand and assigns the result to C=C-A
the left operand.
Multiply AND assignment operator. It
multiplies the right operand with the C*=A is equivalent to
*= left operand and assigns the result to C=C*A
the left operand.
Divide And assignment operator. It
divides the left operand with the right C/=A is equivalent to
/= operand and assigns the result to the C=C/A
left operand.
Modulus AND assignment operator. It
C%=A is equivalent to
%= takes modulus using two operands and
C=C%A
assigns the result to the left operand.
Left shift AND assignment operator. C<<=2 is same as
<<=
C=C<<2
Right shift AND assignment operator. C>>=2 is same as
>>= C=C>>2
Bitwise AND assignment operator. C&=2 is same as
&= C=C&2
Bitwise exclusive OR and assignment C^=2 is same as
^= operator. C=C^2
Bitwise inclusive OR and assignment C|=2 is same as
|= operator. C=C|2


Sahu Technologies Internship 29

5) RELATIONAL OPERATORS: These operators are used to compare


the value of two variables.

EXAMPLE
OPERATORS DESCRIPTION
For A=10, B=20
Checks if the values of two operands are equal
(A==B) is
== or not. If yes, then the condition becomes
TRUE. FALSE
Checks if the values of two operands are equal
(A!=B) is
!= or not. If the values are not equal, then the
condition becomes TRUE. TRUE
Checks if the value of left operand is greater
(A>B) is
> than the value of right operand. If yes, then
the condition becomes TRUE. FALSE
Checks if the value of left operand is less than
< the value of right operand. If yes, then the (A<B) is TRUE
condition becomes TRUE.
Checks if the value of left operand is greater
(A>=B) is
>= than or equal to the value of right operand. If
yes, then the condition becomes TRUE. FALSE
Checks if the value of left operand is less than
(A<=B) is
<= or equal to the value of right operand. If yes,
then the condition becomes TRUE. TRUE

6) MISCELLANEOUS OPERATORS:

OPERATORS DESCRIPTION EXAMPLE


sizeof(a), where a is
sizeof() Returns the size of a variable.
integer, will return 4
Returns the address of a &a, returns the actual
&
variable. address of the variable
* Pointer to a variable *a;
If Condition is TRUE?
? : Conditional expression then value X:otherwise
value Y


Sahu Technologies Internship 30

ARITHMETIC OPERATORS

Q] Write a C program to perform the arithmetic operators.


PROGRAM:


OUTPUT:


Sahu Technologies Internship 31

LOGICAL OPERATORS
Q] Write a C program to perform the logical operators.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 32

BITWISE OPERATORS
Q] Write a C program to perform the logical operators.

PROGRAM:


OUTPUT:


Sahu Technologies Internship 33


ASSIGNMENT OPERATORS
Q] Write a C program to perform the assignment operators.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 34

RELATIONAL OPERATORS


Q] Write a C program to perform the relational operators.

PROGRAM:


OUTPUT:


Sahu Technologies Internship 35

MISCELLANEOUS OPERATORS
Q] Write a C program to perform the miscellaneous operators.

PROGRAM:


OUTPUT:


Sahu Technologies Internship 36

OPERATORS PRECEDENCE IN C:
Operator precedence determines the grouping of terms in an expression
and decides how an expression is evaluated. Certain operators have higher
precedence than others.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.

CATEGORY OPERATOR ASSOCIATIVITY
Postfix ( ), [ ], -,>,.,++,-- Left to Right
+,-,!,~,++,--
Unary Right to Left
,(type),*,&,sizeof
Multiplicative *, /, % Left to Right
Additive +, - Left to Right
Shift <<, >> Left to Right
Relational <, <=, >, >= Left to Right
Equality ==, != Left to Right
Bitwise AND & Left to Right
Bitwise XOR ^ Left to Right
Bitwise OR | Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Conditional ?: Right to Left
=+, =-, =*, =/, =%,
Assignment Right to Left
=>>, =<<, &=, ^=, |=
Comma , Left to Right


Sahu Technologies Internship 37

DECISION MAKING IN C

DECISION MAKING STATEMENTS


If-else Switch Jump

if break

if-else continue

if-else-if goto
ladder
return
nested if

A) IF-ELSE STATEMENTS:
i) if STATEMENT
‘if statement’ is the most simple decision making statement. It is
used to decide whether a certain statement or block of statements is
will be executed or not. i.e. if a certain condition is TRUE then a block
of statement is executed or not.
SYNTAX:

if(condition)

{
// Statements to execute if the condition is TRUE


Sahu Technologies Internship 38


Q] Write a C program to compare the 2 numbers using if statement.

PROGRAM:





















OUTPUT:
















Sahu Technologies Internship 39

ii) if-else STATEMENT


The ‘if’ statement alone tells us that if the condition is TRUE, it will
execute a block of statements. But if the condition is FALSE it won’t.
What if we want to do something else, if the condition is FALSE? Here
comes the C else statement. We can use the else statement with if
statement to execute a block of code when the condition is FALSE.
SYNTAX:

if(condition)

{

//Executes this block if the condition is TRUE

}

else

{

//Executes this block if the condition is FALSE

}


How an if-else statement works?
If the test expression is evaluated to TRUE, statements inside the
body of if are executed, whereas, the statements inside the body of
else are skipped from the execution. If the test expression is FALSE,
statements inside the body of else are executed, whereas the
statements inside the body of if are skipped.


Sahu Technologies Internship 40


Q] Write a C program to check whether the person is eligible for voting
or not. [Hint: age>18, eligible for voting].

PROGRAM:

OUTPUT:


Sahu Technologies Internship 41

Q] Write a C program to check whether the given number is Armstrong number.



[Hint: Sum of cubes of each digit of a number is equal to number itself]

PROGRAM:

OUTPUT:


Sahu Technologies Internship 42

iii) NESTED if STATEMENT


A nested if in C is an if statement that is the target of another if
statement. Nested if statements means an if statement inside
another if statement.
SYNTAX:

if(condition 1)
{
// Executes when condition 1 is TRUE
if(condition 2)
{
// Executes when condition 2 is TRUE
}
}



Sahu Technologies Internship 43


Q] Write a C program to check whether the entered year is leap year using
nested if-else.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 44

iv) if-else-if ladder STATEMENT


Here, a user can decide among multiple options. The C if statements
are executed from the top down. As soon as one of the conditions
controlling the if is TRUE, the statement associated with that if is
executed, and the rest of the C else-if ladder is bypassed. If none of
the conditions are TRUE, then the final else statement will be
executed.
SYNTAX:

if(condition 1)
statement;
else if(condition 2)
statement;
.

.
.
else
statement;

Q] Write a C program to find the quadrant in which the given point lies.

PROGRAM:


Sahu Technologies Internship 45



OUTPUT:


Sahu Technologies Internship 46

B) SWITCH STATEMENTS:
A switch statement allows a variable to be tested for equality against a list
of values. Each value is called a case, and the variable being switched on is
checked for each switch case.

SYNTAX:
switch(expression)
switch(expression)
{
{
case 1: Block-1;
case 1: Block-1;
break;
break;
case 2: Block-2;
case 1: Block-1;
break;
. break;
. .
. .
case n: Block-n;
.
break;
case n: Block-n;
default: Block-s
} break;
default: Block-s
}


The expression provided in the switch should result in a constant value

otherwise it would not be valid.
Duplicate case values are not allowed.







Sahu Technologies Internship 47



Q] Write a C program to enter the week number (1-7) and print the

name of week-day using switch case.

PROGRAM:




















OUTPUT:






Sahu Technologies Internship 48


RULES FOR SWITCH STATEMENT:

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


Sahu Technologies Internship 49


Q] Write a C program to print single digit numbers in words using switch
case.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 50

C) JUMP STATEMENTS: These statements are used in C for unconditional flow


of control throughout the functions in the program. They support 4 types of
JUMP statements as follows:

i) break statement
This loop control statement is used to terminate the loop. As soon as
the break statement is encountered from within a loop, the loop
iterations stops there and control returns from the loop immediately
to the first statement after the loop.
Basically break statements are used in the situations when we are
not sure about the actual number of iterations for the loop or we
want to terminate the loop based on some condition.

SYNTAX:
break;


Loop body Starts




TRUE
Condition to break

break from the


loop
FALSE



Sahu Technologies Internship 51


BREAK STATEMENT

PROGRAM:







OUTPUT:


Sahu Technologies Internship 52

ii) continue statement


This loop control statement is just like the break statement. The
continue statement is opposite to that of break statement, instead of
terminating the loop; it forces to execute the next iteration of the
loop. As the name suggests, the continue statement forces the loop
to continue or execute the next iteration. When the continue
statement is executed in the loop, the code inside the loop following
the continue statement will be skipped and next iteration of the loop
will begin.
SYNTAX:
continue;

Loop body Starts




Condition to continue TRUE

next iteration continue



FALSE

Execute remaining part of loop body
\












Sahu Technologies Internship 53



CONTINUE STATEMENT

PROGRAM:


OUTPUT:


Sahu Technologies Internship 54

iii) goto statement


The goto statement in C which is also referred as an unconditional
jump statement can be used to jump from one point to another
within a function.
SYNTAX:
Syntax 1 | Syntax 2
-----------------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;

In the above syntax, the first line tells the compiler to go to or jump
to the statement marked as a label. Here, label is a user-defined
identifier which indicates the target statement. The statement
immediately followed after ‘label:’ is the destination statement. The
‘label:’ can also appear before the ‘goto label;’ statement in the
above syntax.


START


Label 1: Statement 1


Label 2: Statement 2 goto

Label 3



Label 3: Statement 3




Label 4: Statement 4




STOP


Sahu Technologies Internship 55

GOTO STATEMENT
PROGRAM:

OUTPUT:


Sahu Technologies Internship 56

iv) return statement


The return in C returns the flow of the execution to the function from
where it is called. This statement does not mandatorily need any
conditional statements. As soon as the statement is executed, the
flow of the program stops immediately and returns the control from
where it was called. The return statement may or may not return
anything for a void function, but for a non-void function, a returned
value must be returned.
SYNTAX:
return [expression];

RETURN STATEMENT

PROGRAM:

OUTPUT:


Sahu Technologies Internship 57

LOOPS IN C
The versatility of the computer lies in its ability to perform a set of instructions
repeatedly. This involves repeating some portion of the program either a
specified number of times or until a particular condition is being satisfied.

For a situation, when block of code needs to be executed several number of


times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.

A loop statement allows us to execute a statement or a group of statements


multiple times. The general form of a loop statement is:


Conditional Code

CONDITION

If the condition
is TRUE
If the condition is
FALSE

The sequence of statements to be executed is kept inside the curly braces { }


known as the Loop Body. After every execution of the loop body, condition is
verified, and if it is found to be TRUE the loop is executed again. When the
condition check returns FALSE, the loop body is not executed, and execution
breaks out of the loop.


Sahu Technologies Internship 58

TYPES OF LOOPS:
There are 3 types of loops in C language:

LOOPS

for while do while


i) for LOOP:
A for loop is a repetition control structure that allows you to efficiently
write a loop that needs to execute a specific number of times.
‘for’ loop is used to execute a set of statements repeatedly until a
particular condition is satisfied. We can say that it is an ‘open-ended loop’.
The general form of a for loop is,
SYNTAX:
for (initialization; condition; increment/decrement)

{

conditional code;
}

In for loop we have exactly two semicolons, one after initialization and
second after the condition. In this loop we can have more than one
initialization or increment/decrement, separated using comma operator.
But it can have only one condition.
The for loop is executed as follows:
a) It first evaluates the initialization code.
b) Then it checks the condition expression.
c) If it is TRUE, it executes the for-loop body.
d) Then it evaluates the increment/decrement condition and again
follows from step (b).
e) When the condition expression becomes FALSE, it exits the loop.


Sahu Technologies Internship 59


FLOWCHART:
for (initialization; condition;
increment/decrement)

Initial condition {

conditional code;
}
Condition

If condition is
FALSE
If condition is

TRUE

Code Block


Increment/Decrement





Nested for LOOP:

for (initialization; condition; increment/decrement)

{

for (initialization; condition; increment/decrement)

{
statement;

}

}


Sahu Technologies Internship 60


Q] Write a C program to print Pascal triangle using for loop.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 61


Q] Write a C program to find the sum of series 1+2+3+… upto n terms.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 62


Q] Write a C program to print alphabets in triangular form using for
loop.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 63


Q]Write a Program to Print Floyd’s Triangle.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 64


Q] Write a C program to print an inverted triangular pattern.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 65


Q] Write a C program to print each alphabet serially increasing order.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 66

ii) while LOOP:


A while loop can be addressed as an entry controlled loop. It is completed
in 3 steps.
The while loop is executed as follows:
a) Variable initialization. (eg. int x = 0;)
b) condition (eg. while(x<=n))
c) Variable increment or decrement (x++ & x--or x=x+2)

SYNTAX: variable initialization;


while (condition)

{
statements;

variable increment or decrement;

}

FLOWCHART:
while (condition)

{
conditional code;
}

Condition

If condition is If condition is

TRUE FALSE

Code Block





Sahu Technologies Internship 67


Q] Write a C program to reverse a number using while loop.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 68

Q] Write a C program to print triangular pyramid using while loop.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 69

iii) do while LOOP:


In some situations it is necessary to execute body of the loop before testing
the condition. Such situations can be handled with the help of do-while
loop. Here, thedo statements evaluates the body of the loop first and at the
end, the condition is checked using while statement. It means that the body
of the loop will be executed at least once, even though the starting
condition inside while is initialized to be FALSE.
SYNTAX:
do
{
conditional code;

}

while (condition test)


Flowchart: do{

Conditional code;

} while (condition)


Code block


If the condition

is TRUE
Condition

If the condition is

FALSE


Sahu Technologies Internship 70


Q] Write a C program to add all the numbers entered by the user until

user enters 0.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 71

Q] Write a C program to add all the numbers entered by the user until
user enters 0.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 72

FUNCTIONS IN C
A function is a block of statements that together perform a specific task. Every C
program has atleast one function, which is main (), and all the most trivial
programs can define additional functions. You can divide your code into separate
functions. The way you divide your code among different functions is upto you,
but logically the division is such that each function performs a specific task. A
function declaration tells the compiler about a function’s name, return type, and
parameters. A function definition provides the actual body of the function. The C
standard library provides numerous built-in functions that your program can call.
Example, strcat () to concatenate two strings, memcpy () to copy one memory
location to another location, and many more functions.

A function can also be referred as a method or a subroutine or a procedure, etc.

A function definition in C programming consists of a function header and a


function body. The following are parts of a function:

• RETURN TYPE: A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
• FUNCTION NAME: This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
• PARAMETERS: A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type, order,
and number of the parameters of a function. Parameters are optional; i.e.
functions may contain no parameters.
• FUNCTION BODY: The function body contains a collection of statements
that define what the function does.


Sahu Technologies Internship 73

DEFINING A FUNCTION:

return_type function_name (parameter list)


{
Body of the function/Set of Statements
}

FUNCTION DECLARATIONS:
A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name (parameter list);
Here the parameter names are not important in function declaration only their
type is required.
Hence, int max (int , int );
Function declaration is required when you define a function in one source file and
you call that function in another file. In such case, you should declare the function
at the top of the file calling the function.

CALLING A FUNCTION:
While creating a C function, you give a definition of what the function has to do.
To use a function, you will have to call that function to perform the defined task.

When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement
is executed or when its function-ending closing brace is reached, it returns the
program control back to the main program.

To call a function, you simply need to pass the required parameters along with
the function name, and if the function returns a value, then you can store the
returned value.


Sahu Technologies Internship 74

FUNCTION ARGUMENTS:
If a function is to use arguments, it must declare variables that accept the values
of the arguments. These variables are called the formal parameters of the
function. Formal parameters behave like other local variables inside the function
and are created upon entry into the function and destroyed upon exit.

CALL BY VALUE:
The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameters of the function. In this case,
changes made to the parameters inside the function have no effect on the
argument. By default, C programming language uses call by value method to pass
arguments. In general, this means that code within a function cannot alter the
arguments used to call the function. Consider the function swap () definition as
follows

CALL BY REFERENCE:
The call by reference method of passing arguments to a function copies the
address of anargument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the passed argument.

To pass the value of reference, argument pointers are passed to the functions just
like any other value. So accordingly you need to declare the function parameters
as pointer types as in the following function swap(), which exchanges the values
of the two integervariables pointed to by its arguments.


Sahu Technologies Internship 75

CALL BY VALUE CALL BY REFERENCE


This method copies the address of an
This method copies the actual value of
argument into the formal parameter.
an argument into the formal parameter of
Inside the function, the address is used to
the function. In this case, changes made
access the actual argument used in the
to the parameter inside the function have
call. This means that changes are made to
no effect on the argument.
the parameter affect the argument.
Function is called by passing values as Function is called by passing address as
the parameters. the parameter.
Changes made in formal parameters will Changes made in formal parameter will be
not reflect in actual parameters. reflected in actual parameter.
Normal variables can be used as formal Pointer variables are required as formal
parameters. parameters.
E.g.
E.g.
void swap(int *x, int*y)
int add(int x, int y)
{
{
int z;
int z;
z=*x;
z=x+y;
*x=*y;
return(z);
*y=z;
}
}

By default, C uses call by value to pass arguments. In general, it means


the code within a function cannot alter the arguments sued to call the
function.


Sahu Technologies Internship 76

Q) Why do we need FUNCTIONS in C Programming?

Functions are used because of the following reasons:

• To improve the readability of the code.


• Improves the reusability of the code, same function can be used in any
program rather than writing the same code from the scratch.
• Debugging of the code would be easier if you use functions, as errors are
easy to be traced.
• Reduces the size of the code, duplicate set of statements are replaced by
function calls.

Example, you want to create a function to add two variable integers.

Let’s split the problem so that it would be easier to understand,


The function will add the two numbers, so, it should also have some meaningful
name like sum, addition, etc. Consider the function,

return_type addition(parameters list)


This function addition adds two integer variables, which means I need two integer
variables as input, lets provide two integer parameters in the function signature.
The function signature would be:

return_type addition(int num1, int num2)


The result of the sum of two integers would be integer only. Hence, function
should return an integer value.

int addition(int num1, int num2);


Hence, you have got your function prototype or signature.




Sahu Technologies Internship 77


Q] Write a program to add two numbers using function.

PROGRAM:















OUTPUT:





Sahu Technologies Internship 78

Q] Write a program to find factorial of a number using function.



PROGRAM:












OUTPUT:




Sahu Technologies Internship 79

RECURSIVE FUNCTIONS
The process of performing same operation repeatedly without using looping is
known as ‘recursion’.

The recursion can be implemented by using a function which calls itself.

ADVANTAGES:
• It helps in reducing length of a program.
• It helps in reducing the complexity in logic by replacing loops.
• Recursive function executes faster than normal function.

DISADVANTAGES:
• If proper termination condition is not used then it leads to infinite loop.

CONDITION FOR WRITING RECURSION FUNCTION:


Every recursive function must consist of if-else statement. It is required to select
one out of two options: keeps calling or stop calling.The condition used in if-else is
important.

NOTE:

• main() in C program is also a function.


• Each C program must have atleast one function, which is main().
• There is no limit on number of functions. A C program can have any number
of functions.
• A function can call itself, which is also known as ‘Recursion’.


Sahu Technologies Internship 80


Q] Write a C program to print Fibonacci series using recursive function.

PROGRAM:




OUTPUT:


Sahu Technologies Internship 81


Q] Write a program to find GCD/LCM of two numbers using recursive

function.
PROGRAM:

OUTPUT:


Sahu Technologies Internship 82

CATEGORIES OF FUNCTION
Q) What are the different ways of passing parameters to a function?
For better understanding of arguments and return type in functions, user-defined
functions can be categorized as follows:
i) FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUES:
This type of functions has no arguments and no return values.
void sum()
{
----------
----------
}
Q] Write a C program to check whether a number entered by user is prime or not using

function with no arguments and no return values.
PROGRAM:








#



OUTPUT:







Here, function prime() is used for asking user a input, check whether it is prime or not and
display it accordingly. No argument is passed and returned from prime() function.



Sahu Technologies Internship 83

ii) FUNCTION WITH NO ARGUMENTS AND RETURN VALUE:


This type of functions has no argument but a return value
int sum()
{
----------
----------
return(value);
}
Q] Write a C program to check whether a number entered by user is prime or not using

function with no arguments but having return value
PROGRAM:














OUTPUT:








There is no argument passed to input() function. But, the value of n is returned from

input() to main() function.



Sahu Technologies Internship 84

iii) FUNCTION WITH ARGUMENTS BUT NO RETURN VALUE:


This type of functions has arguments but no return value.
void sum(int a, int b)
{
----------
----------
}
Q] Write a C program to check whether a number entered by user is prime or not
using function with arguments and no return value
PROGRAM:


// PROGRAM









OUTPUT:









Here, check_display () function is used to check whether it is prime or not and display it
accordingly. Here, argument is passed to user-defined function, but value is not returned

from it to calling function.



Sahu Technologies Internship 85


iv) FUNCTION WITH ARGUMENTS AND RETURN VALUE:
This type of function has arguments and also has a return value.
float sum(int a, float b)
{
----------
----------
}

Q] Write a C program to check whether a number entered by user is prime or not using

function with arguments and also has a return value.
PROGRAM:


OUTPUT:

Here, check() function is used for checking whether a number is prime or not. In this program,
input from user is passed to function check() and integer value is returned from it. If input the
number is prime, 0 is returned and if number is not prime, 1 is returned.



Sahu Technologies Internship 86

SCOPE RULES
Scope rules in C or scope of a variable may directly be accessible after its
declaration. The scope of a variable in C programming language can be
declared in three places:
SCOPE PLACE
Local variable Inside a function or block
Outside of all function (can be accessed from
Global variable
anywhere)
Formal parameters In the function parameters

A scope in any programming is a region of the program where a defined


variable can have its existence and beyond that variable it cannot be
accessed. There are three places where variables can be declared in C
programming:
• Inside a function or a block which is called local variables.
• Outside of all functions which is called global variables.
• In the definition of function parameters which are called formal
parameters.

LOCAL VARIABLE:
Local variables are the variables that are declared inside a block or a
function. These variables can only be used inside that block or function.
Local variables can’t be accessed from outside of that block or function.

GLOBAL VARIABLE:
Global variable is the variable that is declared outside of a block or
function. These variables can be accessed from anywhere in the program.
Once a global variable is declared you can use it within the whole program.




Sahu Technologies Internship 87

FORMAL PARAMETER:
Formal parameters are the parameters that are written in the function
definition. Formal parameter takes precedence over global variable.

Scope of an identifier is the part of the program where the identifier may
directly be accessible.

SCOPE MEANING
Scope of an identifier starts at the beginning of the file
and ends at the end of the file. It refers to only those
File Scope identifiers that are declared outside all functions. The
identifiers of File Scope are visible all over the file.
Identifiers having file scope are global.
Scope of an identifier begins at the opening of the block /
Block Scope ‘{’ and ends at the end of the block / ‘}’. Identifiers with
block scope are local to their block.
Function Identifiers declared in function prototype are visible within
Prototype the prototype.
Scope
Function scope begins at the opening of the function and
ends with the closing of it. Function scope is applicable to
Function
labels only. A label declared is used as a target to goto
Scope
statement and both goto and label statement must be in
same function.


Sahu Technologies Internship 88

ARRAYS IN C
An ‘array’ is a group (or collection) of same data types. For example, an int array
holds the elements of int types while a float array holds the elements of float
types.
An ‘array’ is defined as the collection of similar type of data items stored at
same memory locations. Arrays are the derived data type in C programming
language, which can store the primitive type of data such as int, char, double,
float, etc. It also has the capability to store the collection of derived data types
such as pointers, structures etc. The array is the simplest data structure where
each data element can be randomly accessed by using its indexed number. C
array is beneficial if you have to store similar elements. Eg. If we want to store
marks of a student in 5 subjects, then we don’t need to define different variables
for the marks in different subjects. Instead, we can define an array which can
store the marks in each subject at specific memory locations.

By using an array, we can access the elements more easily. Only few lines of code
are required to access the elements of the array.

DECLARATION OF ARRAY: data_type array_name[array_size];


Eg. int marks[5];
INITIALIZATION OF ARRAY:The simplest way to initialize an array is by using
the index of each element. We can initialize each element of the array by using
the index. E.g. int arr[4]={1,2,3,4}; int arr[]={1,2,3,4};….Both are same.

An un-initialized array always contains garbage values.


PROPERTIES OF ARRAY:

• Each element of an array is of same data type and carries same size.
• Elements of the array are stored at contiguous memory locations, where
the first element is stored at the smallest memory location.
• Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the
size of the data element.


Sahu Technologies Internship 89

ADVANTAGES OF ARRAY:

• CODE OPTIMIZATION: Less code to access the data.


• EASE OF TRAVERSING: By using the for loop, we can retrieve the elements
of an array easily.
• EASE OF SORTING: To sort the elements of array, we need a few lines of
code only.
• RANDOM ACCESS: We can access any element randomly using the array.

DISADVANTAGES OF ARRAY:

• FIXED SIZE: The size which we define at declaration of the array, we can’t
exceed the limit. So, it doesn’t grow the size dynamically.

Q) Why do we need an array in programming?

Consider a program where you need to find average of 100 integers


entered by user. In C, you have two ways to do it.
• Define 100 variables with int data type and then perform 100 scanf ()
operations to store the entered values in the variables and then at
last calculate the average of them.
• Have a single integer array to store all the values, loop the array to
store all the entered values in array and later calculate the average.

The better solution is that it is convenient to store same data types in


one single variable and later access them using array index.

Q) How to declare an array?


int num[50]; //An integer array of 50 numbers

char ch[10]; //An array of characters for 10 elements


Similarly, an array can be of any data type such as double, float,
short etc.


Sahu Technologies Internship 90

Q) How to access element of an array in C?

You can use array subscript (or index) to access any element stored in array.
Subscript starts with 0, i.e. A[0] represents the first element in the array A[ ]. In
general, A[n-1] can be used to access nth element of an array, where n≡ integer.

Example: int A[20];


A[0]>> First element of the array, A[19]>> Last element of the array

For arrays in C:
2D array:

We can have multidimensional arrays in C like 2D and 3D array. However the


most popular and frequently used array is 2D – two dimensional arrays. In this
post you will learn how to declare, read and write data in 2D array along with
various other features of it.

Passing an array to a function:

Generally we pass values and variables while calling a function; likewise we can
also pass arrays to a function. You can pass array’s element as well as whole array
(by just specifying the array name, which works as a pointer) to a function.

Pointer to array:

Array elements can be accessed and manipulated using pointers in C. Using


pointers you can easily handle array. You can have access of all the elements of an
array just by assigning the array’s base address to pointer variable.


Sahu Technologies Internship 91

Q] Write a C program to print all the elements present in the array.


PROGRAM:

OUTPUT:


Sahu Technologies Internship 92


Q] Write a C program to reverse all the elements present in the array.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 93


Q] Write a C program to represent the entered elements in form of
array.

PROGRAM:


OUTPUT:


Sahu Technologies Internship 94


Q] Write a C program to find transpose of a matrix.

PROGRAM:


Sahu Technologies Internship 95


OUTPUT:


Sahu Technologies Internship 96


Q] Write a C program to find determinant of a matrix.
PROGRAM:


OUTPUT:


Sahu Technologies Internship 97


Q] Write a C program for addition of two matrices.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 98


Q] Write a C program for multiplication of two matrices.

PROGRAM:


OUTPUT:


Sahu Technologies Internship 99

POINTERS IN C
A pointer is a variable that stores the address of another variable. Unlike other
variables that hold values of a certain type, pointer holds the address of a
variable. For example, an integer variable holds (or stores) an integer value.
However, an integer pointer holds the address of an integer variable.

The data type of pointer and the variable must match, an int pointer can hold
the address of int variable, and similarly a pointer declared with float data type
can hold the address of a float variable

The operators & and * that are used with Pointers in C.

Address of”(&) Operator

We can display the address of a variable using ampersand sign. I have used &num
to access the address of variable num. The & operator is also known as “Address
of” Operator.

printf("Address of var is: %p", &num);

Point to note: %p is a format specifier which is used for displaying the address in
hexadecimal format.

Now, you know how to get the address of a variable but how to store that
address in some other variable? That’s where pointers concept enters. Pointers in
C programming are used for holding the address of other variables.
“Value at Address” (*) Operator
The * Operator is also known as Value at address operator.
How to declare a pointer?


int*p1 //Pointer to an integer variable

double *p2 //Pointer to a variable of data type double


char *p3 //Pointer to a character variable

float *p4 //Pointer to a float variable


Sahu Technologies Internship 100

If you need a pointer to store the address of integer variable then the data type
of the pointer should be int.

More Topics on Pointers


1) Pointer to Pointer – A pointer can point to another pointer (which means it can
store the address of another pointer), such pointers are known as double pointer
OR pointer to pointer.

2) Passing pointers to function – Pointers can also be passed as an argument to a


function, using this feature a function can be called by reference as well as an
array can be passed to a function while calling.

3) Function pointers – A function pointer is just like another pointer, it is used for
storing the address of a function. Function pointer can also be used for calling a
function in C program.

USE OF POINTERS

• Pointers are used to create dynamic data structures.


• To pass and handle variable parameters passed to functions.
• To access information stored in array.
• It makes possible to return more than one value from function.

ARRAY OF POINTERS:
Arrays and pointers are closely related to each other but the important difference
between them is that, a pointer variable takes different addresses as values
whereas, in case of array, it is fixed.

Constant pointer is a special pointer whose value cannot be modified. Means, a


pointer that once points to a memory location cannot point to another memory
location later in the program.


Sahu Technologies Internship 101

RELATION BETWEEN ARRAY AND POINTER:



PROGRAM:

OUTPUT:


Sahu Technologies Internship 102


Q] Write a C program to demonstrate use of * and & in pointers.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 103


Q] Write a C program to find the address of pointer variable.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 104

STRINGS IN C
Strings are actually one-dimensional array of characters terminated by a null
character '\0'. Thus a null-terminated string contains the characters that comprise
the string followed by a null.

The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the
character array containing the string is one more than the number of characters
in the word "Hello."

Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the '\0' at the end of the string when it initializes
the array.

gets() and puts()


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

The scanf() and printf() are generic i/o functions that they support all built-in data
types such as int, float, long, double, strings,..etc. But gets() and puts() are
specialized to scan and print only string data. There is a little difference between
scanf() and gets(), while reading string from keyboard, the scanf() accepts
character by character from keyboard until either a new line (‘\n’) or blank space
is found, which ever comes earlier. Whereas “gets()” accepts until a newline is
found. That is it accepts white spaces & tab also, these input functions append a
null character at end of string, the formatted string %s is used in printf() and
scanf().


Sahu Technologies Internship 105

C supports a wide range of functions that manipulate null-terminated strings:

Sr. No. FUNCTION USE


1) strlen It is used to find length of the string.
2) strlwr It converts a string to lower case.
3) strupr It converts a string to upper case.
4) strcat It appends one string at the end of another.
It appends first n characters of the string at the end of
5) strncat
another.
6) strcpy It is used to copy one string to another.
7) strncpy It copies first n characters of string to another.
8) strcmp It compares two strings.
9) strncmp It compares first n characters of two strings.
It compares two string without regards to case(“i”
10) strcmpi
denotes that this function ignores cases.
It compares two strings without regards to case
11) stricmp
(identical to strcmpi).
It compares first n characters of two strings. It is not case
12) strnicmp
sensitive.
13) strdup It is used for duplicating a string.
It finds out the first occurrence of a given character in
14) strchr
the string.
It finds out the last occurrence of a given character in the
15) strrchr
string.
It finds the first occurrence of the string into another
16) strstr
string.
17) strset It sets all characters of a string to a given character.
18) strnset It sets first n characters of a string to a given character.
19) strrev It reverses a string.


Sahu Technologies Internship 106


Q] Write a C program to print a string.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 107


Q] Write a C program to display the characters in prime position.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 108


Q] Write a C program to find whether the entered character is present
in the string.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 109

STRUCTURES IN C
Structure is a user-defined datatype in C language which allows us to combine
data of different types together. Structure helps to construct a complex data type
which is more meaningful. It is somewhat similar to an Array, but an array holds
data of similar type only. But structure on the other hand, can store data of any
type, which is practical more useful.

For example: If I have to write a program to store Student information, which will
have Student's name, age, branch, permanent address, father's name etc, which
included string values, integer values etc, how can I use arrays for this problem, I
will require something which can hold data of different types together.

In structure, data is stored in form of records.

Defining a structure
struct keyword is used to define a structure. struct defines a new data type which
is a collection of primary and derived datatypes.

Syntax of struct: struct structure_name


{
data_type member1;
data_type member2;

};

Access members of a structure

There are two types of operators used for accessing members of a structure.

• . - Member operator
• - Structure pointer operator
Sahu Technologies Internship 110


Q] Write a C program to enter student’s details using structure.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 111

UNIONS IN C
A union is a special data type available in C that allows storing different data types
in the same memory location. You can define a union with many members, but
only one member can contain a value at any given time. Unions provide an
efficient way of using the same memory location for multiple-purpose.

Defining a Union

To define a union, you must use the union statement in the same way as you did
while defining a structure. The union statement defines a new data type with
more than one member for your program. The format of the union statement is
as follows:

union [union tag]


{
member definition;
member definition;
...
member definition;
} [one or more union variables];

The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end
of the union's definition, before the final semicolon, you can specify one or more
union variables but it is optional. Here is the way you would define a union type
named Data having three members i, f, and str:

union Data {
int I;

float f;
char str[20];
} data;

Sahu Technologies Internship 112

Now, a variable of Data type can store an integer, a floating-point number, or a


string of characters. It means a single variable, i.e., same memory location, can be
used to store multiple types of data. You can use any built-in or user defined data
types inside a union based on your requirement.

The memory occupied by a union will be large enough to hold the largest member
of the union.

C Union is also like structure, i.e. collection of different data types which are
grouped together. Each element in a union is called member.

• Union and structure in C are same in concepts, except allocating memory


for their members.
• Structure allocates storage space for all its members separately.
• Whereas, Union allocates one common storage space for all its members
• We can access only one member of union at a time. We can’t access all
member values at the same time in union. But, structure can access all
member values at the same time. This is because; Union allocates one
common storage space for all its members. Whereas structure allocates
storage space for all its members separately.
• Many union variables can be created in a program and memory will be
allocated for each union variable separately.


Sahu Technologies Internship 113


Q] Write a C program to illustrate the concept of unions.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 114

BIT FIELDS IN C
Bit fields can be used to reduce memory consumption when it is known that only
some bits would be used for a variable. Bit fields allow efficient packaging of data
in the memory. As we know, integer takes two bytes (16 bits) in memory.
Sometimes we need to store value that takes less than 2 bytes. In such cases,
there is wastage of memory.

For example, if we use a variable temp to store value either 0 or 1. In this case,
only one bit of memory will be used rather than 16 bits. By using bit field, we can
save lot of memory.
SYNTAX: BIT FIELD DECLARATION:
struct struct_name
The declaration of bit-field has the
{ following form inside the structure:

data type var 1: size of bits;

data type var 1: size of bits;
struct
----------------------------------
---------------------------------- {
data type var N: size of bits; type [member_name]: width;
}; };

In the above example, the variable elements of bit fields are:

• type: An integer type that determines how a bit-fields value is interpreted.


The type may be int, signed int or unsigned int.
• member_name: This gives the name of the bit field.
• width: The number of bits in the bit-field. The width must be less than or
equal to the bit width of the specified type.

The variables defined with a pre-defined width are called bit-fields. A bit-field can
hold more than a single bit. Example, if you need a variable to store value from 0
to 7, then you can define a bit-field with width of 3 bits as follows:

struct {
unsigned int age: 3;

} Age;


Sahu Technologies Internship 115


Q] Write a C program to explain bit field representation.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 116

TYPE_DEF IN C
‘Typedef’ is a keyword that is used to give a new symbolic name for the existing
name in a C program. Consider the below structure,

struct student
{

int marks [2];
char name [10];
float average;

}

Here, variables can be declared in 2 ways:

i) struct student record; //for normal variable


struct student*record; //for pointer variable

ii) typedef struct student_status;
• When we use “typedef” keyword before struct <tag_name> like
above, after that we can simply use type definition “status” in the C
program to declare structure variable.
• Now, structure variable declaration will be “status record”.
• This is equal to “struct student record”. Type definition for “struct
student” is status. i.e. status= “struct student”

An alternative way for typedef in C:

typedef struct student


{
int marks[2];
char name [10];
float average;
} status;


Sahu Technologies Internship 117


Q] Write a C program to display student details using structure.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 118

C INPUT AND OUTPUT


Input means to provide the program with some data to be used in the program
&Output means to display data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input
and to display data on screen when there is a need to output the result.
All these built-in functions are present in C header files; we will also specify the
name of header files in which a particular function is defined while discussing
about it.

v scanf () and printf() functions


The standard input-output header file, named stdio.h contains the
definition of the functions printf () and scanf (), which are used to display
output on screen and to take input from user respectively.

Q] Write a C program to implement the printf() and scanf() functions.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 119

When you will compile the above code, it will ask you to enter a value. When you
will enter the value, it will display the value you have entered on screen.

You must be wondering what is the purpose of %d inside the scanf() or printf()
functions. It is known as format string and this informs the scanf() function, what
type of input to expect and in printf() it is used to give a heads up to the compiler,
what type of output to expect.

FORMAT STRING MEANING


%d Scan or print an integer as signed decimal number
%f Scan or print a floating point number
%c To scan or print a character
To print or scan a character string. The scanning ends a
%s
whitespace.

We can also limit the number of digits or characters that can be input or output,
by adding a number with the format string specifier, like "%1d" or "%3s", the first
one means a single numeric digit and the second one means 3 characters, hence if
you try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is
the case for output.
In C Language, computer monitor, printer etc output devices are treated as files
and the same process is followed to write output to these devices as would have
been followed to write the output to a file.

NOTE: printf () function returns the number of characters printed by it,


and scanf() returns the number of characters read by it.


Sahu Technologies Internship 120

v getchar () &putchar () functions


The getchar () function reads a character from the terminal and returns it
as an integer. This function reads only single character at a time. You can
use this method in a loop in case you want to read more than one
character. The putchar () function displays the character passed to it on
the screen and returns the same character. This function displays only a
single character at a time. In case you want to display more than one
characters, use putchar () method in a loop.

v gets() & puts() functions


The gets() function reads a line from stdin(standard input) into the buffer
pointed to by str pointer, until either a terminating newline or EOF (end of
file) occurs. The puts() function writes the string str and a trailing newline
to stdout.

Difference between scanf () and gets ()

The main difference between these two functions is that scanf() stops
reading characters when it encounters a space, but gets() reads space
as character too.

If you enter name as ‘C Programming’ using scanf() it will only read and
store ‘C’ and will leave the part after space. But gets() function will read
it completely.


Sahu Technologies Internship 121

FILE I/O IN C
A file is a container in computer storage devices used for storing data.

Why files are needed?

Ø When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
Ø If you have to enter a large number of data, it will take a lot of time to
enter them all. However, if you have a file containing all the data, you can
easily access the contents of the file using a few commands in C.
Ø You can easily move your data from one computer to another without any
changes.
Types of Files

When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files

1. Text files

Text files are the normal .txt files. You can easily create text files using any simple
text editors such as Notepad.When you open those files, you'll see all the
contents within the file as plain text. You can easily edit or delete the
contents.They take minimum effort to maintain, are easily readable, and provide
the least security and takes bigger storage space.

2. Binary files

Binary files are mostly the .bin files in your computer.


Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides
better security than text files.


Sahu Technologies Internship 122

File Operations

In C, you can perform four major operations on files, either text or binary:

Ø Creating a new file


Ø Opening an existing file
Ø Closing a file
Ø Reading from and writing information to a file

Working with files


When working with files, you need to declare a pointer of type file. This
declaration is needed for communication between the file and the program.
FILE *fptr;

Opening a file - for creation and edit


Opening a file is performed using the fopen() function defined in the stdio.h
header file.
The syntax for opening a file in standard I/O is:
ptr = fopen("fileopen","mode");

For example,
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");

Closing a File
The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using the fclose() function.
>>fclose(fptr)
Here, fptr is a file pointer associated with the file to be closed.


Sahu Technologies Internship 123

Reading and writing to a text file


For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that
fprintf() and fscanf() expects a pointer to the structure FILE.

Opening Modes in Standard I/O


Mode Meaning of Mode During Inexistence of file
If the file does not exist, fopen() returns
r Open for reading.
NULL.
If the file does not exist, fopen() returns
rb Open for reading in binary mode.
NULL.
If the file exists, its contents are
w Open for writing. overwritten.
If the file does not exist, it will be created.
If the file exists, its contents are
wb Open for writing in binary mode. overwritten.
If the file does not exist, it will be created.
Open for append.
a If the file does not exist, it will be created.
Data is added to the end of the file.
Open for append in binary mode.
ab If the file does not exist, it will be created.
Data is added to the end of the file.
If the file does not exist, fopen() returns
r+ Open for both reading and writing.
NULL.
Open for both reading and writing in If the file does not exist, fopen() returns
rb+
binary mode. NULL.
If the file exists, its contents are
w+ Open for both reading and writing. overwritten.
If the file does not exist, it will be created.
If the file exists, its contents are
Open for both reading and writing in
wb+ overwritten.
binary mode.
If the file does not exist, it will be created.
Open for both reading and
a+ If the file does not exist, it will be created.
appending.
Open for both reading and
ab+ If the file does not exist, it will be created.
appending in binary mode.


Sahu Technologies Internship 124

PREPROCESSORS IN C

The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution
tool and it instructs the compiler to do require pre-processing before the actual
compilation. We'll refer to the C Preprocessor as CPP.

C Source
Preprocessor Compiler
code

Sr. No. Directive & Description
#define
1
Substitutes a preprocessor macro.
#include
2
Inserts a particular header from another file.
#undef
3
Undefines a preprocessor macro.
#ifdef
4
Returns true if this macro is defined.
#ifndef
5
Returns true if this macro is not defined.
#if
6
Tests if a compile time condition is true.
#else
7
The alternative for #if.
#elif
8
#else and #if in one statement.
#endif
9
Ends preprocessor conditional.
#error
10
Prints error message on stderr.
#pragma
11
Issues special commands to the compiler, using a standardized method.


Sahu Technologies Internship 125

HEADER FILES IN C
A ‘header file’ is a file with extension.h which contains C function declarations
and macro definitions to be shared between several source files. There are two
types of header files: the files that the programmer writes and the files that come
with your compiler.

You request to use a header file in your program by including it with the C
preprocessing directive #include, like you have seen inclusion of stdio.h header
file, which comes along with your compiler.

Including a header file is equal to copying the content of the header file but we do
not do it because it will be error-prone and it is not a good idea to copy the
content of a header file in the source files, especially if we have multiple source
files in a program.

A simple practice in C or C++ programs is that we keep all the constants, macros,
system wide global variables, and function prototypes in the header files and
include that header file wherever it is required.

HEADER
SR. NO.
FILES
DESCRIPTION
1) stdio.h Input / Output functions
2) conio.h Console Input / Output functions
3) stdlib.h General utility functions
4) math.h Mathematical functions
5) string.h String functions
6) ctype.h Character handling functions
7) time.h Date and time functions
8) float.h Limits of float types
9) limits.h Size of basic types
Functions to determine the type contained in wide
10) wctype.h
character data.


Sahu Technologies Internship 126

TYPE CASTING IN C
‘Type Casting’ is converting one data type into another one. It is also called data
conversion or type conversion. C programming provides two types of type casting
operations:

v IMPLICIT TYPE CASTING


Implicit type casting means conversion of data types without losing its
original meaning. This type of typecasting is essential when you want to
change data types without changing the significance of the values stored
inside the variable.
Implicit type conversion happens automatically when a value is copied to its
compatible data type. During conversion, strict rules for type conversion
are applied. If the operands are of two different data types, then an
operand having lower data type is automatically converted into a higher
data type.

Important Points related Implicit Conversions

• Implicit type of type conversion is also called as standard type conversion.


We do not require any keyword or special statements in implicit type
casting.
• Converting from smaller data type into larger data type is also called as
type promotion
• The implicit type conversion always happens with the compatible data
types.

We cannot perform implicit type casting on the data types which are not
compatible with each other such as:

• Converting float to an int will truncate the fraction part hence losing the
meaning of the value.
• Converting double to float will round up the digits.
• Converting long int to int will cause dropping of excess high order bits.


Sahu Technologies Internship 127


IMPLICIT TYPE CASTING
PROGRAM:

OUTPUT:


Sahu Technologies Internship 128

v Explicit type casting


In implicit type conversion, the data type is converted automatically. There
are some scenarios in which we may have to force type conversion.
Suppose we have a variable div that stores the division of two operands
which are declared as an int data type,
int result, var1=10, var2=3;
result = var1/var2;

In this case after the link is performed on variables var1 and var2 the result
stored in the variable ‘result’ will be in integer format. Whenever this
happens, the value stored in the variable ‘result’ loses its meaning because
it does not consider the fraction part which is normally obtained in the
division of two numbers.
To force the type conversion in such situations, we use explicit type casting.
It requires a type casting operator.
The general syntax for type casting operations is as follows:
(type_name) expression.
Here,

• The type name is the standard 'C' language data type.


• An expression can be a constant, a variable or an actual expression.

Ø Implicit type conversion operates automatically when the compatible data
type is found.
Ø Explicit type conversion requires a type casting operator.

NOTE: Rules for programming practice when dealing with different data
type to prevent from data loss:

i) Integer types should be converted to float.


ii) Float types should be converted to double.
iii) Character types should be converted to integer.


Sahu Technologies Internship 129


EXPLICIT TYPE CASTING
PROGRAM:

OUTPUT:


Sahu Technologies Internship 130

ERROR HANDLING IN C
C language does not provide any direct support for error handling. However a few
methods and variables defined in error.h header file can be used to point out
error using the return statement in a function. In C language, a function returns -
1 or NULL value in case of any error and a global variable errno is set with the
error code. So the return value can be used to check error while programming.

What is errno?
Whenever a function call is made in C language, a variable named errno is
associated with it. It is a global variable, which can be used to identify which type
of error was encountered while function execution, based on its value. Below we
have the list of Error numbers and what do they mean:

errno value Error
1 Operation not permitted
2 No such file or directory
3 No such process
4 Interrupted system call
5 I/O error
6 No such device or address
7 Argument list too long
8 Exec format error
9 Bad file number
10 No child processes
11 Try again
12 Out of memory
13 Permission denied
C language uses the
following functions to represent error messages associated
with errno:

• perror() : It returns the string passed to it along with the textual


representation of the current errno value.
• strerror() : It is defined in string.h library. This method returns a pointer to
the string representation of the current errno value.


Sahu Technologies Internship 131

We can also use Exit Status constants in the exit () function to inform the calling
function about the error. The two constant values available for use are
EXIT_SUCCESS and EXIT_FAILURE. These are nothing but macros defined stdlib.h
header file.

Division by Zero
There are some situations where nothing can be done to handle the error. In C language
one such situation is division by zero. All you can do is avoid doing this, because if you
do so, C language is not able to understand what happened, and gives a runtime error.

Best way to avoid this is, to check the value of the divisor before using it in the division
operations. You can use if condition, and if it is found to be zero, just display a message
and return from the function.

As such, C programming does not provide direct support for error handling but being a
system programming language, it provides you access at lower level in the form of
return values. Most of the C or even UNIX function calls return -1 or NULL in case of any
error and set an error code errno. It is set as a global variable and indicates an error
occurred during any function call. You can find various error codes defined in <error.h>
header file.

So a C programmer can check the returned values and can take appropriate action
depending on the return value. It is a good practice, to set errno to 0 at the time of
initializing a program. A value of 0 indicates that there is no error in the program.It is a
common problem that at the time of dividing any number, programmers do not check if
a divisor is zero and finally it creates a runtime error.

errno, perror(), and strerror()


The C programming language provides perror() and strerror() functions which can
be used to display the text message associated with errno.
• The perror() function displays the string you pass to it, followed by a colon,
a space, and then the textual representation of the current errno value.
• The strerror() function, which returns a pointer to the textual
representation of the current errno value.


Sahu Technologies Internship 132

Program Exit Status


It is a common practice to exit with a value of EXIT_SUCCESS in case of program coming
out after a successful operation. Here, EXIT_SUCCESS is a macro and it is defined as 0.
If you have an error condition in your program and you are coming out then you should
exit with a status EXIT_FAILURE which is defined as -1.

ERROR HANDLING FUNCTIONS

PROGRAM:

OUTPUT:


Sahu Technologies Internship 133

RECURSION IN C
Recursion in C language is basically the process that describes the action when a
function calls a copy of itself in order to work on a smaller problem. Recursive
functions are the function that calls themselves and this type of function calls are
known as recursive calls. The recursion in C generally involves various numbers of
recursive calls. It is considered to be very important to impose a termination
condition of recursion. Recursion code in the C language is generally shorter than
the iterative code.

Recursion cannot be applied to the entire problem, but Recursion in C language is


very useful for the tasks that can be generally be defined in terms of similar
subtasks but it cannot be applied to all the problems. For instance: Recursion in C
can be applied to sorting, searching, and traversal problems.

As function call is always overhead, iterative solutions are more efficient than
recursion. Any of the problems that can generally be solved recursively; it can be
also solved iteratively.

What is Recursive Function?


The working of a recursive function involves the tasks by dividing them generally
into the subtasks. Some specific subtasks have a termination condition defined
that has to be satisfied by them. In the next step, the recursion in C stops and the
final result is derived from the function.

The base case is the case at which the function doesn’t recur in C and there are
instances where the function keeps calling itself in order to perform a subtask and
that is known as the recursive case.


Sahu Technologies Internship 134


Q] Write a C program to find factorial of a number using recursion.
PROGRAM:

OUTPUT:


Sahu Technologies Internship 135

Q] Write a C program to find nth Fibonacci series term using recursion.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 136

Q] Write a C program to find LCM & GCD of numbers using recursion.

PROGRAM:


OUTPUT:


Sahu Technologies Internship 137

VARIABLE ARGUMENTS

Sometimes, you may come across a situation, when you want to have a function,
which can take variable number of arguments, i.e., parameters, instead of
predefined number of parameters. The C programming language provides a
solution for this situation and you are allowed to define a function which can
accept variable number of parameters based on your requirement. The following
example shows the definition of such a function.

It should be noted that the function func() has its last argument as ellipses, i.e.
three dotes (...) and the one just before the ellipses is always an int which will
represent the total number variable arguments passed. To use such functionality,
you need to make use of stdarg.h header file which provides the functions to
implement the functionality of variable arguments and follow the given steps −
• Define a function with its last parameter as ellipses and the one just before
the ellipses is always an int which will represent the number of arguments.
• Create a va_list type variable in the function definition. This type is defined
in stdarg.h header file.
• Use int parameter and va_start macro to initialize the va_list variable to an
argument list.
• Use va_list variable to access each item in argument list.
• Use a macro va_end to clean up the memory assigned to va_list variable.
• When a function gets number of arguments that changes at run time, we
can go for variable length arguments.
• It is denoted as … (3 dots)
• stdarg.h header file should be included to make use of variable length
argument functions.
intfunc(int, ... ) {

.
.
.
}
int main() {
func(1, 2, 3);
func(1, 2, 3, 4);
}


Sahu Technologies Internship 138

MEMORY MANAGEMENT

Every programming language deals with memory in the system. Each and every
variable needs a specified amount of memory, the program itself require memory
to store its own program, some temporary memory to store intermediate values
etc. Hence it is required to manage the memory with utmost care. Memory
locations assigned to one program or variable should not be used by another
program or variable. Hence, C provides 2 methods of allocating memory to the
variables and programs. They are static and dynamic memory allocations. In
static memory allocation, memory is allocated at the time of compilation and will
be same throughout the program. There will not be any changes to the amount of
memory nor the location in the memory. But in the case of dynamic memory
allocation, memory is allocated at the run time and we can increase/decrease the
amount of memory allocated or completely release the memory when not in use.
We can reallocate the memory when it is required. Hence dynamic memory
allocation gives the flexibility to use the memory efficiently.

Before proceeding to memory allocation, let us understand types of variables,
types of memory and methods of allocating memory to the various variables and
programs. In a program, we will have different types of variables and memory
requirement. The global variables are the ones which will be used throughout the
program by different functions and blocks. Hence memory area allocated to them
needs to exist throughout the program. Hence they get memory allocated at the
internal memories of the system, which are known as permanent storage area.
Similarly the program and their statements also need to exist throughout when
system is on. Hence they also need to occupy permanent storage area.

Local variables are the one which need to exist in the particular block or function
where they are declared. If we store them in permanent storage area, it will be
waste of memory as we keep the memory allocate which are not in use. Hence
we use stack memory to store the local variables and remove them from the stack
as the use of local variable is over.


Sahu Technologies Internship 139

There is a free memory space between this stack memory and permanent storage
area called heap memory. This memory is flexible memory area and keeps
changing the size. Hence they are suitable for allocating the memory during the
execution of the program. That means dynamic memory allocations use these
heap memories.

Static Memory Allocation


Suppose we need to add two integer numbers and display the result. Here we
know, how many variables and which type of variables are involved in
calculations. i.e. we need two integer variables to store two numbers and one
integer variable to store result. Thus we need three integer variables. This implies
that at compile time itself we know that there are 3 integer variables. Hence it is
easy for the compiler to reserve the memory for these variables. Such reserved
variables will have same size and memory address till the end of the program.
There will not be any change in size, type and memory location for those
variables.

This kind of memory allocation for the variables is known as static memory
allocation. Here no need to explicitly allocate memory to the variables. When we
declare the variables, memory will be automatically assigned to them. These
variables can be local or global variables. But we need to know in advance the size
and type of the variable. They need not be simple variables; but they can be array
or structure too provided we know their size.
int intX; // needs to be initialized or assigned some value at run time
int intExample = 0; //normal variable
const int intConstant = 10; // constant, read-only variable

In above all cases the compiler knows in advance that they are also integers and
their size. Hence compiler will allocate specific memory locations before
executing the program itself. These allocated memories will not be freed until the
program execution is over. These allocated memory location and their size is
constant throughout the program. Any these kinds of variables cannot store more
than predefined size of data in this case.


Sahu Technologies Internship 140

Dynamic Memory Allocation



This is in contrast to the static memory allocation. Here program will not know
the size and even sometimes type of the variable. It is determined only at the
execution time. In such case, we cannot assign any memory at compilation time.
It can be assigned only at the run time.

Suppose we need to add any number of numbers that are entered by the user.
Here we are not sure about how many numbers are entered by the user. We only
know that it he is entering only integers. In this case we cannot pre-assign any
memory to the variables. He can enter only 2 numbers or 100s of numbers. If user
enters less numbers then the program should be flexible enough to assign to
those less number of numbers and as the numbers increase memory allocation
space also should increase. But this can be determined only at the run time
depends on the user who enters the value. Thus we need to allocate space at the
run time which is done by using dynamic memory allocation methods.

There are different functions to allocate memory to the variables at run time and
fluctuate the size of the memory for the variables. The best example of dynamic
memory allocation is pointers, structures and arrays. Here we will not be aware
of number of variables and types of variables being used. We can assign memory
and determine the type of the variable at run time using below functions.

• malloc ()
This is the most common method of allocating memory at run time. This
function allocates requested amount of memory to the variables at run
time and returns the void pointer to the first memory address. That means
it allocates the requested amount of memory in bytes and it does not
points/defines datatype for the variable. It considers the variable as void
and moves its pointer to the first byte in the allocated memory. In case it
cannot allocate memory, then it returns the NULL pointer.


Sahu Technologies Internship 141

The general syntax for allocating memory using malloc is:


(cast_type *) malloc (size_in_bytes);
ptr = malloc(10); // allocates 10 bytes of memory

Here ptr is a pointer variable and it allocates 10 bytes of memory. Here we


have not defined datatype of the variable and ptr is a void pointer now. It
will now point to the first byte in the allocated memory.

If we need to make this pointer as integer then we need specify the type
also while allocating memory. If we do this, then when we assign values,
the values will be stored at the interval of those many sizes. That means if
we make ptr as integer and start storing the data, then each data value will
be stored at the interval of 4 bytes.

ptr = (int*)malloc(10); //returns integer pointer to ptr pointing to first byte


of allocated memory

This will make ptr as integer pointer and allocated memory is only 10 bytes.
If it is divided for integer value (4 bytes each), then we will be able to store
only 2 values. But the size of the integer may vary from system to system.
Hence we can allow processor itself to determine the size of the integer
and allocate memory to the pointer. In addition, we can specify how many
data value of integer size needs to be stored.

ptr = (int*) malloc(10* sizeof(int)); //allocates memory sufficient for 10


integer values and returns integer pointer to ptr

The parameter within malloc will have total size of memory to be


allocated. But we cannot calculate the total size always. Hence we perform
calculation with malloc to determine the total size of the memory to be
allocated.


Sahu Technologies Internship 142

Suppose we need to create a dynamic array of floating numbers to store


100 elements, then:
arr = (float*)malloc(10 * sizeof(float));

Same method can be used to allocate memory for the structures. Suppose
we have student structure, then:
struct student *std = (struct student *)malloc(sizeof(struct student));

Here structure pointer *std is allocated memory dynamically. It gets the


memory allocated to store one student details and makes the pointer to
point to the first member of the student structure. Suppose same *std
should hold more than one student, considering 50 students.
Then we need to allocate memory to hold 50 * sizeof (student).
struct student *std = (struct student *)malloc(50 * sizeof(struct student));

• calloc ()
This function is similar to malloc. But this function is usually used to allocate
memories to arrays and structures. When calloc () is used to allocate
memory, it automatically initializes the variable to zero. Suppose we need
to allocate memory for 50 students. In malloc we multiply 50 with the size
of student structure to get the total memory size. But in calloc, we pass 50
and size of student as two arguments as shown below. Apart from this, it
allocates memory in the same way as malloc.

The general syntax for allocating memory using calloc is:


(cast_type *) calloc (blocks ,size_of_block);

struct student *std = (struct student *)calloc(sizeof(struct student));


// single student

struct student *std = (struct student *)malloc(50, sizeof(struct student));


// 50 students


Sahu Technologies Internship 143

• realloc ()
Suppose we need to increase or decrease the memory size of already
allocated variable. In such case we can use realloc function to re-define
memory size of the variable.

The general syntax for allocating memory using malloc is:


(cast_type *) realloc (blocks, size_of_block);
It will allocate totally new memory location with new block size.

• free ()
It is always good practice to release the allocated memory once it is no
longer required. This is because whenever the memory is allocated
dynamically, they will consume lot of memory space to the variables. It will
be available to same or different programs only when it is released.
However, all the memories held by the program will be released
automatically, once the program is complete.

free (variable_name);
free (std);


Sahu Technologies Internship 144

COMMAND LINE ARGUMENTS:


Command line argument is a parameter supplied to the program when it is
invoked. Command line argument is an important concept in C programming. It is
mostly used when you need to control your program from outside. Command line
arguments are passed to the main() method.

Properties of Command Line Arguments:


• They are passed to main() function.
• They are parameters / arguments supplied to the program when it is
invoked.
• They are used to control program from outside instead of hard coding
those values inside the code.
• argv[argc] is a NULL pointer.
• argv[0] holds the name of the program.
• It is possible to pass some values from the command line to your C
programs when they are executed. These values are called command line
arguments and many times they are important for your program especially
when you want to control your program from outside instead of hard
coding those values inside the code.
• The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a
pointer array which points to each argument passed to the program.


Sahu Technologies Internship 145

Q] Write a C program to implement command line arguments.

PROGRAM:

OUTPUT:


Sahu Technologies Internship 146

INTERVIEW QUESTIONS
1) Why is C language known as mother language?
2) What are the features of C language?
3) C is successor of which programming language?
4) What is the use of function in C
5) What is a null pointer?
6) What is a dangling pointer?
7) How to overcome the problem of dangling pointer?
8) What is the difference between getch () and getche ()?
9) What is a newline escape sequence?
10) What is the maximum length of an identifier?
11) What is typecasting?
12) Can we access array using pointer?
13) What is an infinite loop? List them.
14) Write a program to print “Hello World” without using semicolon (;)?
15) What is a far pointer in C?
16) What is pointer to pointer in C?
17) What is the purpose of sprintf () function?
18) How can we store a negative integer?
19) Differentiate between actual parameters and formal parameters?
20) What do you mean by a nested structure?
21) Where can we not use & (address operator in C)?
22) Which variable can be used to access Union data members if the union
variable is declared as pointer variable?
Sahu Technologies Internship 147


23) How can you print a string with the symbol % in it?
24) What are the limitations of scanf () and how can it be avoided?
25) What is lvalue and rvalue?
26) When to use -> (arrow) operator?
27) Which keyword is used to perform unconditional branching?
28) What is a null statement?
29) What are enumerations?
30) What are the default values of local and global variables?
31) Can a pointer access the array?
32) Which are the valid operations on pointers?
33) Which operator can be used to access union elements if union variable
is a pointer variable?
34) Which function can be used to release the dynamic allocated memory?
35) Can a function return multiple values to the caller using return reserved
word?
36) Is there a way to compare two structure variables?
37) Which controlled loop is recommended if you have to execute
statements for fixed number of times?
38) Can the main() function be left empty?
39) Can one function call another?
40) How can we determine whether a file is successfully opened or not using
fopen() function?
41) What is the difference between = symbol and == symbol?

Sahu Technologies Internship 148


42) Can two or more operators such as \n and \t be used in a single line of
program code?
43) How is the null pointer different from a void pointer?
44) Explain the various file opening modes in C?
45) What are some of the limitations of C language?
46) What is the utilization of #undef preprocessor?
47) How can you apply comments in C program?
48) What is the exact meaning of syntax error?
49) Explain the role of the union in C programming.
50) What do you know about logical errors and bring out the difference
between syntax and logical errors.
51) What is the exact role played by sequential access file in C
programming?
52) Explain the meaning of queue and FIFO in C programming?
53) What is a stack?
54) How do you declare a variable that will hold string values?
55) What is the advantage of an array over individual variables?
56) What is debugging?
57) What are logical errors and how does it differ from syntax errors?
58) Is it possible to initialize a variable at the time it was declared?
59) What are reserved words?
60) Is it possible to create your own header file in C?


Sahu Technologies Internship 149

PRACTICE PROGRAMS
v PRACTICE QUESTIONS
1) Write a program to find the largest among the n numbers.
2) Write a C program to swap two numbers without using third variable.
3) Write a C program to check whether the entered string is palindrome.
4) Write a C program to check whether the entered number is strong
number.
5) Write a C program to check whether the entered number is neon
number.
6) Write a C program to check whether the entered number is
automorphic number.
7) Write a C program to find the super digit of the given number.(while
loop)

v Simple C Programs
1) Write a C program to reverse a number using recursion.
2) Write a C program to find greatest of three numbers.
3) Write a C program to find prime numbers in a given range.
4) Write a C program to check whether the entered number is palindrome.
5) Write a C program to find palindrome numbers in a given range.
6) Write a C program to find ASCII value of a character.
7) Write a C program to find the size of in, float, double and char.
8) Write a C program to check whether an alphabet is vowel or consonant.

v String Programs
1) Write a C program to convert a string from upper case to lower case and
vice-versa.
2) Write a C program to sort a set of strings in ascending alphabetical
order.
3) Write a C program to find length of string without using string functions.

Sahu Technologies Internship 150


4) Write a C program concatenate two strings without using string
functions.
5) Write a C program to reverse a string using recursion.

v Programs to find out areas of Geometric figures


1) Write a C program to find area and circumference of circle.
2) Write a C program to find area of equilateral triangle.

v Array Programs
1) Write a C program to find number of elements in the array.
2) Write a C program to find the sum of array elements.
3) Write a C program to sort the array alphabetically.
4) Write a C program to find the sum of squares of elements present in the
array.

v Sorting Programs
1) Write a bubble sort program in C.
2) Write an insertion sort program in C.
3) Write a selection sort program in C.
4) Write a quick sort program in C.

v C Pointer Programs
1) Write a C program to find the largest of three numbers using pointers.
2) Write a C program to count vowels and consonants in string using
pointer.
3) Write a C program to print string using pointer.
4) Write a C program to swap two numbers using pointers.
5) Write a C program to create, initialize and access a pointer variable.


Sahu Technologies Internship 151


v Programs on Calculation
1) Write a C program to find the value of nPr for given values of n & r.
2) Write a C program to find the value of nCr for given values of n & r.
3) Write a C program to multiply two floating numbers.
4) Write a C program to find the quotient and remainder.
5) Write a C program to find the average of two numbers.

v Number System Conversion Programs


1) Write a C program for binary to decimal conversion and vice-versa.
2) Write a C program for binary to octal conversion and vice-versa.
3) Write a C program for binary to hexadecimal and vice-versa.
4) Write a C program for decimal to octal and vice-versa.
5) Write a C program for decimal to hexadecimal and vice-versa.
6) Write a C program for octal to hexadecimal and vice-versa.

You might also like