Cs3251 Programming in c Update
Cs3251 Programming in c Update
Some paradigms are concerned mainly with implications for the execution model of the
language, such as allowing side effects, or whether the sequence of operations is defined by the
execution model.
declarative which does not state the order in which operations execute,
object-oriented which groups code together with the state the code modifies,
logic which has a particular style of execution model coupled to a particular style of
Machine code
The lowest-level programming paradigms are machine code, which directly represents
and assembly language where the machine instructions are represented by mnemonics
and memory addresses can be given symbolic labels. These are sometimes called first-
The next advance was the development of procedural languages. These thirdgeneration languages
(the first described as high-level languages) use vocabulary related to the
define algorithms, while using mathematical language terminology and targeting scientific
C is highly portable, programs once written in C can be run on another machines with
minor or no modification.
C is basically a collection of C library functions, we can also create our own function and
C is easily extensible.
Advantages of C
Several standard functions are there (like in-built) that can be used to develop programs.
C programs are basically collections of C library functions, and it’s also easy to add own
functions in to the C library.The modular structure makes code debugging, maintenance and
testing easier.
Disadvantages of C
Object-oriented programming
C++, C#, Eiffel, PHP, and Java. In these languages, data and methods to manipulate it are kept
as one unit called an object. The only way that another object or user can access the data is via
the object's methods. Thus, the inner workings of an object may be changed without affecting
The documentation section consists of a set of comment lines giving the name of the
program, the author and other details, which the programmer would like to use later.
2. Link section: The link section provides instructions to the compiler to link functions
3. Definition section: The definition section defines all symbolic constants such using
4. Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all
5. main () function section: Every C program must have one main function section. This
i. Declaration part: The declaration part declares all the variables used in the
executable part.
ii. Executable part: There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. Theprogram
execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program. All statements in the
section contains all the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main () function,
All section, except the main () function section may be absent when they are not required.
C provides various types of data-types which allow the programmer to select the appropriate type
The data-type in a programming language is the collection of data with values having
fixed meaning as well as characteristics. Some of them are integer, floating point, character etc.
Usually, programming languages specify the range values for given data-type.
void As the name suggests it holds no value and is generally used for specifying
the type of function or what it returns. If the function has a void type, it
After taking suitable variable names, they need to be assigned with a data type. This is
Example:
int age;
char letter;
Data Types
Description
Arrays Arrays are sequences of data items having homogeneous values. They have
Pointers These are powerful C features which are used to access the memory and deal with
identifier that would represent an existing data type. There are three such types:
DataTypes
Description
Structure It is a package of variables of different types under a single name . This is done
Union
These allow storing various data types in the same memory location.
Programmers can define a union with different members but only a single
Enumeration is a special data type that consists of integral constants and each of
them is assigned with a specific name. “enum” keyword is used to define the
Let's see the basic data types. Its size is given according to 32 bit architecture.
float 4 byte
double 8 byte
#include <stdio.h>
int main()
machine. sizeof operator can use to get the exact size of a type or a variable on a particular
platform.
Example:
#include <stdio.h>
#include <limits.h>
int main()
return 0;
}
1.5 CONSTANTS
A constant is a value or variable that can't be changed in the program, for example: 10,
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
1) C const keyword
#include<stdio.h>
int main(){
return 0;
Output:
If you try to change the the value of PI , it will render compile time error.
#include<stdio.h>
int main(){
PI=4.5;
return 0;
Output:
2) C #define preprocessor
The #define preprocessor directive is used to define constant or micro substitution. It can
Syntax:
#include <stdio.h>
#define PI 3.14
main() {
printf("%f",PI);
12
Output:
3.140000
C supports some character constants having a backslash in front of it. The lists of
backslash characters have a specific meaning which is known to the compiler. They are also
Example:
\t horizontal tab
applied on Enumeration data type so size of the enumerator data type is 2 byte . It work like
the Integer.
It is used for creating an user defined data type of integer. Using enum we can create
Syntax:
In above syntax tagname is our own variable. tagname is any variable name.
enum tagname{value1,value2,value3,….};
It is start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list. If constant one value is not initialized then by default sequence will be start
from zero and next to generated value should be previous constant value one.
Example of Enumeration in C:
enum week{sun,mon,tue,wed,thu,fri,sat};
In above code first line is create user defined data type called week .
today variable is declare as week type which can be initialize any data or value among
7 (sun, mon,....).
Example:
#include<stdio.h>
#include<conio.h>
enum abc{x,y,z};
void main()
int a;
clrscr();
a=x+y+z; //0+1+2
printf(“sum: %d”,a);
getch();
Output:
Sum: 3
1.7 KEYWORDS
A keyword is a reserved word. You cannot use it as a variable name, constant name etc.
or logical Operation.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators
Which can be used to check the Condition, it always return true or false. Lets suppose
== A== B False
!= A!=(-4) True
Logical Operator
Which can be used to combine more than one Condition?. Suppose you want to
combined two conditions A<B and B>C, then you need to use Logical Operator like (A<B)
! !(B<=-A) True
TTTTFF
TFFTFT
FTFTTF
FFFFTT
Assignment operators
Which can be used to assign a value to a variable. Lets suppose variable A hold 8
and B hold 3.
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
Increment Operators are used to increased the value of the variable by one
and Decrement Operators are used to decrease the value of the variable by one in C
programs.
Both increment and decrement operator are used on a single operand or variable, so it is
called as a unary operator. Unary operators are having higher priority than the other operators
pre-increment
post-increment
In pre-increment first increment the value of variable and then used inside the
Syntax:
In post-increment first value of variable is used in the expression (initialize into another
variable) and then increment the value of variable.
Syntax:
Example:
#include<stdio.h>
#include<conio.h>
void main()
int x,i;
i=10;
x=++i;
printf(“Pre-increment\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
i=10;
x=i++;
++variable;
variable++;
printf(“Post-increment\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
Output:
Pre-increment
x::10
i::10
Post-increment
x::10
i::11
pre-decrement
post-decrement
Pre-decrement (-- variable)
In pre-decrement first decrement the value of variable and then used inside the
Syntax:
In Post-decrement first value of variable is used in the expression (initialize into another
Example:
#include<stdio.h>
#include<conio.h>
void main()
int x,i;
i=10;
--variable;
variable--;
x=--i;
printf(“Pre-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
i=10;
x=i--;
printf(“Post-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
Output:
Pre-decrement
x::9
i::9
Post-decrement
x::10
i::9
Ternary Operator
If any operator is used on three operands or variable is known as Ternary Operator. It can
Using?: reduce the number of line codes and improve the performance of application.
Syntax:
In the above symbol expression-1 is condition and expression-2 and expression-3 will be
either value or variable or statement or any mathematical expression. If condition will be true
Example:
#include<stdio.h>
void main()
int a,b,c,large;
scanf(“%d%d%d”,&a,&b,&c);
large=a>b?(a>c?a:c):(b>c?b:c);
Output:
Special Operators
* Pointer to a variable.
Expression evaluation
Associativity
It represents which operator should be evaluated first if an expression is containing
1 ()
[]
->
function call
array reference
Left to Right
2!
++
--
&
*
sizeof
(type)
negation
1's complement
Unary plus
Unary minus
incre
ment operator
decrement operator
address of operator
pointer
type conversion
Right to Left
3*
multiplication
division
remainder
Left to Right
4+
addition
5 <<
>>
left shift
6<
<=
>
>=
less than
greater than
Left to Right
7 ==
!=
equal to
14 =
*=
/=
%=
+=
-=
&=
^=
|=
<<=
>>=
assignment
assign multiplication
assign division
assign remainder
assign additon
assign subtraction
assign bitwise OR
Right to Left
use scanf() and printf() predefined function to read and print data.
Managing Input/Output
I/O operations are useful for a program to interact with users. stdlib is the standard C
library for input-output operations. While dealing with input-output operations in C, there are
Standard input or stdin is used for taking input from devices such as the keyboard as a
data stream. Standard output or stdout is used for giving output to a device such as a monitor.
For using I/O functionality, programmers must include stdio header-file within the program.
Reading Character In C
The easiest and simplest of all I/O operations are taking a character as input by reading
that character from standard input (keyboard). getchar() function can be used to read a single
Syntax:
Example:
#include<stdio.h>
void main()
char title;
title = getchar();
There is another function to do that task for files: getc which is used to accept a
Syntax:
Writing Character In C
Similar to getchar() there is another function which is used to write characters, but one at a time.
Syntax:
var_name = getchar();
putchar(var_name);
Example:
#include<stdio.h>
void main()
putchar(result);
putchar('\n');
Similarly, there is another function putc which is used for sending a single character to the
standard output.
Syntax:
Formatted Input
It refers to an input data which has been arranged in a specific format. This is possible
in C using scanf(). We have already encountered this and familiar with this function.
Syntax:
Format specifier:
%d Integer
%f Float
%lf Double
%c Single character
%s String
%u Unsigned int
Example:
#include<stdio.h>
void main()
Input data items should have to be separated by spaces, tabs or new-line and the
There are two popular librar y functions gets() and puts() provides to deal with strings in
C.
gets: The char *gets(char *str) reads a line from stdin and keeps the string pointed to by
the str and is terminated when the new line is read or EOF is reached. The declaration of gets()
function is:
Syntax:
puts: The function – int puts(const char *str) is used to write a string to stdout but it does not
include null characters. A new line character needs to be appended to the output. The declaration
is:
Syntax:
Its purpose is saving the result of the expression to the right of the assignment operator to
variable = expression/constant/variable;
If the type of the expression is identical to that of the variable, the result is saved in the
variable.
Otherwise, the result is converted to the type of the variable and saved there.
o If the type of the variable is integer while the type of the result is real, the
result.
o If the type of the variable is real while the type of the result is integer, then a
Once the variable receives a new value, the original one disappears and is no more
available.
The expression on the right hand side of the assignment statement can be:
An arithmetic expression;
A relational expression;
A logical expression;
A mixed expression.
For example,
int a;
If the condition is "true" statement block will be executed, if condition is "false" then
In this section we are discuss about if-then (if), if-then-else (if else), and switch statement. In C
if
if-else
switch
if Statement
Syntax:
Constructing the body of "if" statement is always optional, Create the body when we
If the body is not specified, then automatically condition part will be terminated with
next semicolon ( ; ).
Example:
#include<stdio.h>
void main()
if(condition)
true
int time=10;
if(time>12)
printf(“Good morning”)
Output:
Good morning
if-else statement
In general it can be used to execute one block of statement among two blocks, in C
In the above syntax whenever condition is true all the if block statement are executed
remaining statement of the program by neglecting else block statement. If the condition is false
else block statement remaining statement of the program are executed by neglecting if block
statements.
Example:
#include<stdio.h>
void main()
int time=10;
if(time>12)
printf(“Good morning”)
}
else
Output:
Good morning
Syntax:
switch(expression/variable)
case value1:
statements;
break;//optional
case value2:
statements;
break;//optional
default:
statements;
break;//optional
1. With switch statement use only byte, short, int, char data type.
Example:
#include<stdio.h>
void main()
{
int a;
scanf("%d",&a);
switch(a)
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default :
break;
Output:
times, and C loops execute a block of commands a specified number of times until a condition is
met.
What is Loop?
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do
a task tens of thousands of times. Every programming language has the feature to instruct to do
such repetitive tasks with the help of certain form of statements. The process of repeatedly
executing a collection of statement is called looping . The statements get executed many
numbers of times based on the condition. But if the condition is given in such a logic that the
repetition continues any number of times with no fixed condition to stop looping those
while loops
for loops
while loops
C while loops statement allows to repeatedly run the same block of code until a
condition is met. while loop is a most basic loop in C programming. while loop has one control
condition, and executes as long the condition is true. The condition of the loop is tested before
Syntax:
Example:
#include<stdio.h>
int main ()
int n = 1,times=5;
{
printf("C while loops: %d\n", n);
n++;
return 0;
Output:
C while loops:1
C while loops:2
C while loops:3
C while loops:4
C while loops:5
while (condition)
statement(s);
Increment statement;
Do..while loops:
C do while loops are very similar to the while loops, but it always executes the code
block at least once and furthermore as long as the condition remains true. This is an exitcontrolled
loop.
Syntax:
Example:
#include<stdio.h>
int main ()
int n = 1,times=5;
/* do loops execution */
do
return 0;
Output:
C do while loops:1
C do while loops:2
C do while loops:3
do{
statement(s);
}while( condition );
C do while loops:4
C do while loops:5
for loops
C for loops is very similar to a while loops in that it continues to process a block of code
until a statement becomes false, and everything is defined in a single line. The for loop is
Syntax:
Example:
#include<stdio.h>
int main ()
int n,times=5;;
return 0;
}
for ( init; condition; increment )
statement(s);
Output:
C for loops:1
C for loops:2
C for loops:3
C for loops:4
C for loops:5
break
statement
continue
statement
iteration.
goto
statement
goto labelName;
labelName:
statement;
o #include
o #define
o #undef
C program
Expanded
Source
Code
Preprocessor Compiler
o #ifdef
o #ifndef
o #if
o #else
o #elif
o #endif
o #error
o #pragma
S.No Preprocessor
#include
#include <filename>
#include “filename”
defined by #define.
#define PI 3.14
#undef PI
4 #ifdef
#ifdef MACRO
//code
#endif
5 #ifndef
#ifndef MACRO
//code
#endif
6 #if
executed.
#if expression
//code
#endif
7 #else
#if expression
//if code
#else
//else code
#endif
8 #error
9 #pragma
operating-system feature.
#pragma token
Below are the steps we use on an Ubuntu machine with gcc compiler.
We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The option -Wall enables all compiler’s warning messages. This option is recommended to
After compilation executable is generated and we run the generated executable using below
command.
$ ./filename
Compiler converts a C program into an executable. There are four phases for a C program to
become an executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, We get the all intermediate files in the current directory along
Pre-processing
This is the first phase through which source code is passed. This phase include:
Removal of Comments
Expansion of Macros
The preprocessed output is stored in the filename.i. Let’s see what’s inside filename.i:
In the above output, source file is filled with lots and lots of info, but at the end our code
is preserved.
Analysis:
printf contains now a + b rather than add(a, b) that’s because macros have expanded.
#include<stdio.h> is missing instead we see lots of code. So header files has been
Compiling
The next step is to compile filename.i and produce an; intermediate compiled output
file filename.s. This file is in assembly level instructions. Let’s see through this file using $vi
filename.s
Assembly
In this phase the filename.s is taken as input and turned into filename.o by assembler.
This file contain machine level instructions. At this phase, only existing code is converted into
machine language, the function calls like printf() are not resolved. Let’s view this file using $vi
filename.o
Linking
This is the final phase in which all the linking of function calls with their definitions are
done. Linker knows where all these functions are implemented. Linker does some extra work
also, it adds some extra code to our program which is required when the program starts and ends.
For example, there is a code which is required for setting up the environment like passing
command line arguments. This task can be easily verified by using $size filename.o and $size
filename. Through these commands, we know that how output file increases from an object file
to an executable file. This is because of the extra code that linker adds with our program.
C array is beneficial if you have to store similar elements. Suppose you have to store
marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to
manage. For example we cannot access the value of these variables with only 1 or 2 lines of
code.Another way to do this is array. By using array, we can access the elements easily. Only
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the
limit. So, it doesn't grow the size dynamically like Linked List.
Declaration of C Array
We can declare an array in the c language in the following way.
int marks[5];
Here, int is the data_type, marks is the array_name and 5 is the array_size.
data_type array_name[array_size];
Initialization of C Array
A simple way to initialize array is by index. Notice that array index starts from 0 and
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Example 1:
#include<stdio.h>
int main(){
int i=0;
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
return 0;
Output:
80
60
41
70
85
75
C Array: Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define size. So it can also be written as the following
code.
int marks[]={20,30,40,50,60};
Example 2:
#include<stdio.h>
int main(){
int i=0;
//traversal of array
for(i=0;i<5;i++)
printf("%d \n",marks[i]);
return 0;
Output:
20
30
40
50
60
columns, also known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known
as multidimensional arrays.
int twodimen[4][3];
Initialization of 2D Array in C
A way to initialize the two dimensional array at the time of declaration is given below.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Example:
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
}//end of j
}//end of i
return 0;
Output:
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
data_type array_name[size1][size2];
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
STRING OPERATIONS
What is meant by String?
1. By char array
2. By string literal
char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As you know well, array index starts from 0, so it will be represented as in the figure
given below.
While declaring string, size is not mandatory. So you can write the above code as given
below:
char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
You can also define string by string literal in C language. For example:
char ch[]="javatpoint";
In such case, '\0' will be appended at the end of string by the compiler.
The only difference is that string literal cannot be changed whereas string declared by
Example:
Let's see a simple example to declare and print string. The '%s' is used to print string in c
language.
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[11]="javatpoint";
Output:
The strlen() function returns the length of the given string. It doesn't count null
character '\0'.
Example:
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
return 0;
Output:
Here, we are using gets() function which reads string from the console.
Example:
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
gets(str2);
if (strcmp(str1,str2)==0)
else
return 0;
Output:
returned to first_string.
Example:
#include<stdio.h>
#include <string.h>
int main(){
strcat(ch,ch2);
return 0;
Output:
Example:
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', ' p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
return 0;
Output:
In large programs, debugging and editing tasks is easy with the use of functions.
Built-in(Library) Functions
These functions are provided by the system and stored in the library, therefore it is also
To use these functions, you just need to include the appropriate C header files.
These functions are defined by the user at the time of writing the program.
Parts of Function
2. Function Definition
3. Function Call
1. Function Prototype
Syntax:
Example:
int addition();
2. Function Definition
Syntax:
Example:
int addition()
3. Calling a function in C
Syntax:
Example:
#include<stdio.h>
/* function declaration */
int addition();
int main()
{
int answer;
returnType functionName(Function
arguments)
functionName(Function arguments)
answer = addition();
return 0;
int addition()
return num1+num2;
Output:
calling function to called function and executes function definition, and finally comes back to the
calling function. When the execution control is transferred from calling function to called
function it may carry one or more number of data values. These data values are called
as parameters.
Parameters are the data values that are passed from calling function to called function.
In C, there are two types of parameters and they are as follows...
Actual Parameters
Formal parameters
The actual parameters are the parameters that are specified in calling function.
The formal parameters are the parameters that are declared at called function. When a
function gets executed, the copy of actual parameter values are copied into formal parameters.
In C Programming Language, there are two methods to pass parameters from calling
Call by value
Call by reference
Call by Value
In call by value parameter passing method, the copy of actual parameter values are
copied to formal parameters and these formal parameters are used in called function. The
changes made on the formal parameters does not affect the values of actual parameters .
That means, after the execution control comes back to the calling function, the actual parameter
Example:
#include <stdio.h>
#include<conio.h>
void main(){
clrscr() ;
num1 = 10 ;
num2 = 20 ;
getch() ;
int temp ;
temp = a ;
a=b;
b = temp ;
Output:
51
In the above example program, the variables num1 and num2 are called actual
parameters and the variables a and b are called formal parameters. The value of num1 is copied
into a and the value of num2 is copied into b. The changes made on variables a and b does not
Call by Reference
In Call by Reference parameter passing method, the memory location address of the
Actual parameters is copied to formal parameters. This address is used to access the memory
locations of the actual parameters in called function. In this method of parameter passing, the
That means in call by reference parameter passing method, the address of the actual
Parameters is passed to the called function and is received by the formal parameters (pointers).
Whenever we use these formal parameters in called function, they directly access the memory
locations of actual parameters. So the changes made on the formal parameters effects the
Example:
#include <stdio.h>
#include<conio.h>
void main(){
num1 = 10 ;
num2 = 20 ;
getch() ;
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
Output:
In the above example program, the addresses of variables num1 and num2 are copied to
pointer variables a and b. The changes made on the pointer variables a and b in called function
effects the values of actual parameters num1 and num2 in calling function.
Function Description
1) strlen(string name) Returns the length of string name.
3) strcat(first_string,second_string)
Concatenates or joins first string with second string. Theresult of the string is stored in first string.
4) strcmp(first_string,second_string)
Compares the first string with second string. If both strings are same, it returns 0.
Math Functions
C Programming allows us to perform mathematical operations through the functions
defined in <math.h> header file. The <math.h> header file contains various methods for
There are various methods in math.h header file. The commonly used functions of math.h
Function Description
1) ceil(number) Rounds up the given number. It returns the integer value which is
2) floor(number) Rounds down the given number. It returns the integer value which
4) pow(base,exponent)
Example:
#include<stdio.h>
#include <math.h>
int main(){
printf("\n%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
return 0;
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
3.4 RECURSION
When function is called within the same function, it is known as recursion in C. The
A function that calls itself, and doesn't perform any task after function call, is know
as tail recursion. In tail recursion, we generally call the same function with return statement. An
recursionfunction(){
Example:
#include<stdio.h>
if ( n < 0)
int main(){
int fact=0;
fact=factorial(5);
return 0;
Output:
factorial of 5 is 120
We can understand the above program of recursive method call by the figure given below:
3.5 POINTERS
The pointer in C language is a variable, it is also known as locator or indicator that
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings,
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions
Pointers in c language are widely used in arrays, functions and structures. It reduces the
Address Of Operator
The address of operator '&' returns the address of a variable. But, we need to use %u to
Example:
#include<stdio.h>
int main(){
int number=50;
return 0;
Output
Declaring a pointer
Pointer example
An example of using pointers printing the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable
i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
#include<stdio.h>
int main(){
int number=50;
int *p;
Output
Value of p variable is 50
NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you
don't have any address to be specified in the pointer at the time of declaration, you can assign
int *p=NULL;
#include<stdio.h>
int main(){
int a=10,b=20,*p1=&a,*p2=&b;
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
return 0;
Output:
In c language, a pointer can point to the address of another pointer which points to the address of
int **p2;
Example:
Let's see an example where one pointer points to the address of another pointer.
As you can see in the above figure, p2 contains the address of p (fff2) and p contains the
Example:
#include<stdio.h>
int main(){
int number=50;
p2=&p;
return 0;
Output:
Value of *p variable is 50
o Increment
o Decrement
o Addition
o Subtractiono Comparison
Incrementing Pointer in C
Incrementing a pointer is used in array because it is contiguous memory location.
Increment operation depends on the data type of the pointer variable. The formula of
Example:
#include<stdio.h>
int main(){
int number=50;
p=p+1;
return 0;
Output:
Decrementing Pointer in C
61
Example:
#include <stdio.h>
void main(){
int number=50;
p=p-1;
Output:
Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is
given below:
Let's see the example of adding value to pointer variable on 64 bit OS.
Example:
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
return 0;}
Output:
As you can see, address of p is 3214864300. But after adding 3 with p variable, it is
3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we
were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. The formula of
Let's see the example of subtracting value from pointer variable on 64 bit OS.
Example:
#include<stdio.h>
int main(){
int number=50;
return 0;
}
Output:
You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous
address value.
between them is that, a pointer variable takes different addresses as value whereas, in case of
array it is fixed.
#include <stdio.h>
int main()
char charArr[4];
int i;
return 0;
Notice, that there is an equal difference (difference of 1 byte) between any two consecutive
elements of array charArr. But, since pointers just point at the location of another variable, it can
store any address.
Consider an array:
int arr[4];
In C programming, name of the array always points to address of the first element of anarray.
In the above example, arr and &arr[0] points to the address of the first element.
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
Similarly,
In C, you can declare an array and can use pointer to alter the data of an array.
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
65
scanf("%d",(classes + i));
return 0;
Output:
Enter 6 numbers:
Sum = 21
Example:
#include <stdio.h>
int main ()
int i, *array_of_pointers[ARRAY_SIZE];
array_of_pointers[i] = &array_of_integers[i];
by the pointers: */
return 0;
Output:
array_of_integers[0] = 5
array_of_integers[1] = 10
array_of_integers[2] = 20
array_of_integers[3] = 40
array_of_integers[4] = 80
type of elements.
It works like a template in C++ and class in Java. You can have different type of
elements in it.
Defining structure
The struct keyword is used to define structure. Let's see the syntax to define structure in c.
struct employee
{ int id;
char name[50];
float salary;
};
structure; id, name and salary are the members or fields of the structure. Let's understand it by
struct structure_name
data_type member1;
data_type member2;
..
data_type memberN;};
Declaring structure variable
We can declare variable for the structure, so that we can access the member of structure
1st way:
Let's see the example to declare structure variable by struct keyword. It should be
struct employee
{ int id;
char name[50];
float salary;
};
2nd way:
Let's see another way to declare variable at the time of defining structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare
If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in
main() fuction.
p1.id
Example:
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
int main( )
e1.id=101;
return 0;
Output:
employee 1 id : 101
1. By separate structure
2. By Embedded structure
Separate structure
We can create 2 structures, but dependent structure should be used inside the main
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
int id;
char name[20];
}emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a
member in Employee structure. In this way, we can use Date structure in many structures.
Embedded structure
We can define structure within the structure also. It requires less code than previous way.
struct Employee
int id;
char name[20];
struct Date
int dd;
int mm;
int yyyy;
}doj;
}emp1;
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
Let's see an example of structure with array that stores information of 5 students and prints it.
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
return 0;
Output:
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
program.
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc()
Example:
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
scanf("%d",&n);
if(ptr==NULL)
exit(0);
ptr=(cast-type*)malloc(byte-size)
for(i=0;i<n;++i)
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
Output:
10
10
Sum=30
calloc()
The calloc() function allocates multiple block of requested memory.
Example:
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
scanf("%d",&n);
ptr=(cast-type*)calloc(number, byte-size)
if(ptr==NULL)
exit(0);
scanf("%d",ptr+i);
sum+=*(ptr+i);
printf("Sum=%d",sum);
free(ptr);
return 0;
Output:
10
10
Sum=30
realloc()
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by
free()
The memory occupied by malloc() or calloc() functions must be released by calling free()
ptr=realloc(ptr, new-size)
struct struct_name
datatype datatypename;
struct_name * pointer_name;
};
A self-referential structure is one of the data structures which refer to the pointer to
(points) to another structure of the same type. For example, a linked list is supposed to be a
selfreferential data structure. The next node of a node is being pointed, which is of the same struct
void *data;
} linked_list;
In the above example, the listnode is a self-referential structure – because the *next is of
character or integers. Each element in a linked list is stored in the form of a node.
Node:
free(ptr)
A node is a collection of two sub-elements or parts. A data part that stores the element
and a next part that stores the link to the next node.
Linked List:
A linked list is formed when many such nodes are linked together to form a chain. Each
node points to the next node present in the order. The first node is always used as a reference to
traverse the list and is called HEAD. The last node points to NULL.
The above definition is used to create every node in the list. The data field stores the
element and the next is a pointer to store the address of the next node.
In place of a data type, struct LinkedList is written before next. That's because its a selfreferencing
pointer. It means a pointer that points to whatever it is a part of. Here next is a part
Creating a Node:
struct LinkedList
int data;
};
typedef struct LinkedList *node; //Define node as pointer of data type struct LinkedList
node createNode(){
sizeof() is used to determine size in bytes of an element in C. Here it is used to determine size of
The above code will create a node with data as value and next pointing to NULL.
Let's see how to add a node to the linked list:
Here the new node will always be added after the last node. This is known as inserting a
This type of linked list is known as simple or singly linked list . A simple linked list can be
temp = createNode();//createNode will return a new node with data = value and next
pointing to NULL.
if(head == NULL){
else{
p = head;//assign head to p
while(p->next != NULL){
p = p->next;//traverse the list until p is the last node.The last node always points
to NULL.
p->next = temp;//Point the previous last node to the new node created.
return head;
Here -> is used to access next sub element of node p. NULL denotes no node exists after the
The linked list can be traversed in a while loop by using the head node as a starting reference:
node p;
4.7 TYPEDEF
The C programming language provides a keyword called typedef , by using this keyword you
can create a user defined name for existing data type. Generally typedef are use to create
Declaration of typedef
Example:
Example program:
#include<stdio.h>
#include<conio.h>
void main()
int a=10;
integerdata b=20
p->next = NULL;
p = head;
while(p != NULL)
p = p->next;
integerdata s;
s=a+b;
printf("\nSum::%d",s);
getch();
Output:
Sum::30
In above program Intdata is an user defined name or alias name for an integer data
type.
Advantages of typedef
struct student{
int id;
char *name;
float percentage;
};
As we can see we have to include keyword struct every time you declare a new variable,
typedef struct{
int id;
char *name;
float percentage;
}student;
student a,b;
When a program is terminated, the entire data is lost. Storing in a file will preserve your
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
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 that you can easily create using Notepad or any simple
text editors.
When you open those files, you'll see all the contents within the file as plain text. You
They take minimum effort to maintain, are easily readable, and provide least security
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides abetter
security than text files.
File Operations
In C, you can perform four major operations on the file, either text or binary:
3. Closing a file
5. C provides a number of functions that helps to perform basic file operations. Following
Function description
Syntax:
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
filename is the name of the file to be opened and mode specifies the purpose of opening the file.
Mode Description
Closing a File
Syntax :
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.
In the above table we have discussed about various file I/O functions to perform reading
and writing on file. getc() and putc() are the simplest functions which can be used to read and
Example:
#include<stdio.h>
int main()
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
printf("%c",ch);
fclose(fp);
return 0;
#include<stdio.h>
struct emp
char name[10];
int age;
};
void main()
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
fclose(p);
do
}
while(!feof(q));
In this program, we have created two FILE pointers and both are refering to the same file
fprintf() function directly writes into the file, while fscanf() reads from the file, which can
Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are
used to write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will not
happen.
Append mode is used to append or add data to the existing data of file(if any). Hence,
when you open a file in Append(a) mode, the cursor is positioned at the end of the present
Opening modes are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fread() is also used in the same way, with the same arguments like fwrite() function. Below
const char *mytext = "The quick brown fox jumps over the lazy dog";
if (bfp)
fclose(bfp);
}
5.2 TYPES OF FILE PROCESSING: SEQUENTIAL ACCESS, RANDOM ACCESS
In computer programming, the two main types of file handling are:
Sequential access
In this type of files data is kept in sequential order if we want to read the last record of the
file, we need to read all records before that record so it takes more time.
Random access
In this type of files data can be read and modified randomly .If we want to read the last
record we can read it directly. It takes less time when compared to sequential file.
There is no need to read each record sequentially, if we want to access a particular record.
1. fseek()
2. ftell()
3. rewind()
fseek():
It is used to move the reading control to different positions using fseek function.
Syntax:
Where
displacement ---- It is positive or negative. This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position. This is attached with L
Pointer position:
This sets the pointer position in the file.
0 Beginning of file
1 Current position
2 End of file
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer position
2)fseek( p,5L,1)
1 means current position of the pointer position. From this statement pointer position is
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the current
position.
ftell(): It tells the byte location of current position of cursor in file pointer.
Write a program to read last ‘n’ characters of the file using appropriate file functions(Here
#include<stdio.h>
#include<conio.h>
void main()
FILE *fp;
char ch;
clrscr();
fp=fopen("file1.c", "r");
if(fp==NULL)
else
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
printf("%c\t",ch);}}
fclose(fp);
getch();