C Language
C Language
C PROGRAMMING
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
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
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.
Ø Step-form
Ø Pseudo-code
Ø Flowchart
Ø Nassi-Schneiderman
Sahu Technologies Internship 5
• Sequence
• Correctness
• Termination
• Selection
• Iteration
Example:
Sahu Technologies Internship 6
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.
The following are two main complexity measures of the efficiency of an algorithm:
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.
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.
Sahu Technologies Internship 10
C) TOKENS IN C
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.
Sahu Technologies Internship 13
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
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.
TYPES OF VARIABLES IN C:
Sahu Technologies Internship 16
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
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
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.
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
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.
Sahu Technologies Internship 23
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
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
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:
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
Sahu Technologies Internship 29
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:
Sahu Technologies Internship 30
ARITHMETIC OPERATORS
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
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
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
PROGRAM:
OUTPUT:
Sahu Technologies Internship 42
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
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
Sahu Technologies Internship 51
BREAK STATEMENT
PROGRAM:
OUTPUT:
Sahu Technologies Internship 52
Sahu Technologies Internship 53
CONTINUE STATEMENT
PROGRAM:
OUTPUT:
Sahu Technologies Internship 54
Sahu Technologies Internship 55
GOTO STATEMENT
PROGRAM:
OUTPUT:
Sahu Technologies Internship 56
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.
Conditional Code
CONDITION
If the condition
is TRUE
If the condition is
FALSE
Sahu Technologies Internship 58
TYPES OF LOOPS:
There are 3 types of loops in C language:
LOOPS
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
{
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
PROGRAM:
OUTPUT:
Sahu Technologies Internship 69
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.
• 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:
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
Sahu Technologies Internship 76
Sahu Technologies Internship 77
Q] Write a program to add two numbers using function.
PROGRAM:
OUTPUT:
Sahu Technologies Internship 78
OUTPUT:
Sahu Technologies Internship 79
RECURSIVE FUNCTIONS
The process of performing same operation repeatedly without using looping is
known as ‘recursion’.
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.
NOTE:
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
// 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
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.
• 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:
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.
Similarly, an array can be of any data type such as double, float,
short etc.
Sahu Technologies Internship 90
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.
For arrays in C:
2D array:
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:
Sahu Technologies Internship 91
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
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.
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
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.
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
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.
Sahu Technologies Internship 101
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.
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
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.
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.
};
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:
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
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.
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;
}; };
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;
}
Sahu Technologies Internship 117
Q] Write a C program to display student details using structure.
PROGRAM:
OUTPUT:
Sahu Technologies Internship 118
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.
Sahu Technologies Internship 120
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.
Ø 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
Sahu Technologies Internship 122
File Operations
In C, you can perform four major operations on files, either text or binary:
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
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:
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
NOTE: Rules for programming practice when dealing with different data
type to prevent from data loss:
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:
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.
Sahu Technologies Internship 132
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.
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.
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
PROGRAM:
OUTPUT:
Sahu Technologies Internship 136
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.
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
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
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.
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.
Sahu Technologies Internship 142
• 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.
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.
free (variable_name);
free (std);
Sahu Technologies Internship 144
Sahu Technologies Internship 145
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 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.