100% found this document useful (1 vote)
245 views55 pages

cs8251 C Material PDF

The document provides an overview of CS8251 - Programming in C. It discusses (1) the basics of C programming including data types, storage classes, constants, operators, input/output statements; (2) different programming paradigms such as procedural, object-oriented, functional, and scripting; and (3) features and common uses of C programming such as developing operating systems, compilers, and databases.

Uploaded by

Ishwarya M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
245 views55 pages

cs8251 C Material PDF

The document provides an overview of CS8251 - Programming in C. It discusses (1) the basics of C programming including data types, storage classes, constants, operators, input/output statements; (2) different programming paradigms such as procedural, object-oriented, functional, and scripting; and (3) features and common uses of C programming such as developing operating systems, compilers, and databases.

Uploaded by

Ishwarya M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

CS8251 – Programming in C

UNIT I BASICS OF C PROGRAMMING


Introduction to programming paradigms - Structure of C program - C programming: Data Types –
Storage classes - Constants – Enumeration Constants - Keywords – Operators: Precedence and
Associativity - Expressions - Input/Output statements, Assignment statements – Decision making
statements - Switch statement - Looping statements – Pre-processor directives - Compilation
process
Programming paradigms
A programming paradigm is a fundamental style of computer programming
• Programming paradigms differ in:
• the concepts and abstractions used to represent the elements of a program
(such as objects, functions, variables, constraints, etc.)
• the steps that compose a computation (assignation, evaluation, data flow, control
flow, etc.).
• Some languages are designed to support one particular paradigm
• Smalltalk supports object-oriented programming
• Haskell supports functional programming
• Other programming languages support multiple paradigms
Object Pascal, C++, C#, Visual Basic, Common Lisp, Scheme, Perl, Python, Ruby,
Oz and F#.
The design goal of multi-paradigm languages is to allow programmers to use the best tool
for a job.
(1)Low level
• Initially, computers were hard-wired or soft-wired and then later programmed using
binary code(First Generation).
This was difficult and error-prone, which is a very low-level programming paradigm.
• To make programming easier, assembly languages were developed.
• These replaced machine code functions with mnemonics and memory addresses with
symbolic labels.
• Assembly language programming is considered a low-level paradigm although it is a
'second generation' paradigm.
• Assembly languages supported libraries and quite sophisticated conditional macro
generation and pre-processing capabilities.
• They also supported modular programming
(2)Procedural Language (c language)
• Often thought as a synonym for imperative programming.
• Specifying the steps the program must take to reach the desired state.
• Based upon the concept of the procedure call.
• Procedures, also known as routines, subroutines, methods, or functions that contain a
series of computational steps to be carried out.
• Any given procedure might be called at any point during a program's execution, including
by other procedures or itself.
• Using a procedural language, the programmer specifies language statements to perform a
sequence of algorithmic steps.
• Possible benefits:
• Often a better choice than simple sequential or unstructured programming
• The ability to re-use the same code at different places in the program without
copying it.
• An easier way to keep track of program flow
• The ability to be strongly modular or structured.
(3)Object oriented Programming (Smalltalk ,c++, java, python)
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 1
• Object-oriented programming (OOP) is a programming paradigm that uses "objects" and
procedures together with their interactions.
• Features of OOP are data abstraction, encapsulation, modularity, polymorphism, and
inheritance.
• Many modern programming languages now support OOP.

(4)Functional Programming (Miranda, Clean and Haskell)


• Functional programming is a programming paradigm that treats computation as the
evaluation of mathematical functions.
• It emphasizes the application of functions, in contrast to the imperative programming
style, which emphasizes changes in state.
• Programs written using the functional programming paradigm are much more easily
representable using mathematical concepts.
• Functional languages can be categorized by whether they use strict (eager) or non-strict
(lazy) evaluation.

(5)Scripting Language (shell,java script, xml,html,python)


• A scripting language, historically, was a language that allowed control of software
applications.
• "Scripts" are distinct from the core code of the application, as they are usually written in a
different language and are often created by the end-user.
• Scripts are most often interpreted from source code, whereas application software is
typically first compiled to a native machine code or to an intermediate code.

Features of C Programming
• Easy to learn
• Structured language
• It produces efficient programs.
• It can handle low-level activities.
• It can be compiled on a variety of computer platforms

Usage of C Programming
C programming used to develop the following system programs,
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 2
Structure of C program
Documentation
– Non Executable statement
- To brief the program details
- Single line comment //
- Multiline comment /* ----------- */

Link section
- To link the header files to the program
- #include<stdio.h>
- #include”c:\tc\bin\myheader.c”

Definition Section
- To define constants Ex: #define pi 3.14
- To define macros Ex: #define cube(x) x*x*x

Global declaration
- The variables declared here is visible to all
- The functions declared here is visible to all

Data Types
S.N. Types and Description
1 Basic Types: They are arithmetic types and consist of the two types: (a) integer types (b)
char types and (c) floating-point types.
2 Enumerated types: They are used to define variables that can only be assigned certain
discrete integer values throughout the program.
Ex:
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
} // the variable day restricted to accept the enumerated constant listed above
3 The type void: The type specifier void indicates that no value is available.
4 Derived types: They include (a) Pointer types, (b) Array types, (c) Structure types, (d)
Union types and (e) Function types

Integer Types
Type Storage size Value range
Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 3
Floating-Point Types
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
The void Type
Types and Description
1 Function returns as void : A function with no return value has the return type as void.
For example, void exit (int status);
2 Function arguments as void:. A function with no parameter can accept as a void.
For example, int rand(void);
3 Pointers to void A pointer of type void * represents the address of an object, but not its type.
For example, a memory allocation function void *malloc( size_t size );

Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C
Program. These specifiers precede the type that they modify.
Types are,
• auto
• register
• static
• extern

The auto Storage Class


The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto can only be used
within functions, i.e., local variables.

The register Storage Class


The register storage class is used to define local variables that should be stored in a register
instead of RAM.
This means that the variable has a maximum size equal to the register size and can't have the
unary '&' operator applied to it .
Ex:
{
register int miles;
}
The register should only be used for variables that require quick access such as counters.

The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence during the life-
time of the program instead of creating and destroying it each time it comes into and goes out of
scope.
Therefore, making local variables static allows them to maintain their values between function
calls.
The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 4
In C programming, when static is used on a class data member, it causes only one copy of that
member to be shared by all objects of its class.
#include <stdio.h> /* function definition */ Output :
/* function declaration */ void func( void ) i is 6 and count is 4
void func(void); { i is 7 and count is 3
static int count = 5; /* global variable */ static int i = 5; /* local static i is 8 and count is 2
main() variable */ i is 9 and count is 1
{ i++; i is 10 and count is 0
while(count--) printf("i is %d and count is
{ func(); %d\n", i, count);
} }
return 0;
}
The extern Storage Class
The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files.
When you use 'extern', the variable cannot be initialized
When you have multiple files and you define a global variable or function, which will be used in
other files also, then extern will be used in another file to give reference of defined variable or
function.
The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions.
First File: main.c Second File: write.c
#include <stdio.h> #include <stdio.h>
int count ; extern int count;
extern void write_extern(); void write_extern(void)
main() {
{ count = 5;
write_extern(); printf("count is %d\n", count);
} }
Here, extern keyword is being used to declare count in the second file where as it has its definition
in the first file, main.c

Constants
Constants ate identifier, which values could not be changed during the program execution.
Types of constants
(1)Integer Literals(constants)
An integer literal can be a decimal (10), octal(010), or hexadecimal(0x10) constant.
(2)Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char
type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t')
(3)Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.
You can represent floating point literals either in decimal form or exponential form
(4)String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that are
similar to character literals: plain characters, escape sequences.
Defining Constants
There are two simple ways in C to define constants −
• Using #define preprocessor. Ex: # define a 100
• Using const keyword Ex: const int a=100;
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 5
Variables
Are identifiers, which values can be changed during the program execution.
Rules: Start with alphabet followed by alphabet or digits, the only allowed special character is
under score.

Keywords
The reserved word of the language, could not be used for other purpose,
Void main int char float double long
Short signed unsigned if else switch case
Default while do for break continue goto
Auto static register extern auto struct sizeof

Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations.
Types of operator:
 Arithmetic Operators  Relational Operators  Logical Operators  Bitwise Operators
 Assignment Operators  Misc Operators

Arithmetic Operators
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Gives remainder after an integer division B % A will give 0
++ Increments operator increases integer value by one A++ will give 11
-- Decrements operator decreases integer value by one A-- will give 9

Relational Operators
Assume A= 10 and B=20, then:
== Checks if the values of two operands are equal or not, (A == B) is not true.
!= Checks if the values of two operands are equal or not,. (A != B) is true.
> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand,.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand
>= Checks if the value of left operand is greater than or equal to (A >= B) is not true.
the value of right operand.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand.

Logical Operators
Assume A=2 and B=0
Operator Description Example
&& If both the operands are non-zero, then condition (A && B) is false.
becomes true.
|| If any of the two operands is non-zero, then (A || B) is true.
condition becomes true.
! If a condition is true, then Logical NOT operator !(A && B) is true.
will make false.

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 6
Bitwise Operators
P q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
1 ~p=0

Assignment Operators
Operator Description Example
= Assigns values from right side operands to left side C = A + B will assign value of
operand A + B into C
+= It adds right operand to the left operand and assign C += A is equivalent to C = C
the result to left operand +A
-= It subtracts right operand from the left operand and C -= A is equivalent to C = C -
assign the result to left operand A
*= It multiplies right operand with the left operand and C *= A is equivalent to C = C
assign the result to left operand *A
/= It divides left operand with the right operand and C /= A is equivalent to C = C /
assign the result to left operand A
%= It takes modulus using two operands and assign the C %= A is equivalent to C = C
result to left operand %A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
Misc Operators ↦ sizeof & ternary
Operator Description Example
sizeof() Returns the size of an variable. sizeof(a), where a is integer, will return 2.
& Returns the address of an variable. &a; will give actual address of the variable.
* Pointer to a variable. *a; will pointer to a variable.
?: Conditional Expression If Condition is true ? Then value X :
Otherwise value Y

Precedence of operator
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
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

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 7
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Decision making statements
In order to write useful programs, we need to check conditions and change the behavior of the
program accordingly.

The simplest form is the if statement:


Syntax Flow diagram Example
if(expression) if (x > 0)
{ statement(s)} {
The boolean expression after if printf(“x is positive”)
is called the condition. If it is }
true, the true block is run. If
not, nothing happens.
If x is greater than 0, then
There is no limit on the number it going to display
of statements that can appear in “Positive” otherwise do
the body. nothing

Alternative execution
A second form of the if statement is “alternative execution”, in which there are two possibilities
and the condition determines which one runs.

Syntax Flow diagram Example


if(expression) if (x > 0)
{ true statement(s)} {print('x is positive');}
else else
{ false statement(s)} {print(“x is negative”);}

The boolean expression after


if is called the condition. If it If the value of x is greater
is true, the true block is run. than 0 , the program
Otherwise the false block will displays “Positive”
run. message. If the condition
is false, the second set of
The condition must be true or statements runs.
false, exactly one of the
alternatives will run.

Else if ladder

Sometimes there are more than two possibilities and we need more than two branches called
chained conditional:

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 8
Syntax Flow diagram Example
if(expression1) if( x < y)
{ true statement1(s)} {
else if(expression2) printf('x is less');
{ true statement2(s)} }
else if(expression3) else if(x > y)
{ true statement3(s)} {
else printf('x is greater');
{ false statement(s)} }
else
Each condition is {
checked in order. If the printf(“both are equal”);
first is false, the next is }
checked, and so on.
If x is less than y then print x
If one of them is true, is less and go to end
the corresponding
branch runs and the Otherwise, check x is greater
statement ends. than y print x is greater and go
to end
Even if more than one
condition is true, only Otherwise, print both are
the first true branch equal
runs.

Nested conditionals (one within another)


One conditional can also be nested within another.
if (x != y)
{ if(x < y)
{printf(“x is less than y”);}
else
{printf(“x is greater than y”);}
else
{printf(“x and y are equal”);}

Expressions
1. In programming, an expression is any legal combination of symbols that represents a
value. [Definition from Webopedia]
2. C Programming Provides its own rules of Expression, whether it is legal expression or
illegal expression. For example, in the C language x+5 is a legal expression.
3. Every expression consists of at least one operand and can have one or more operators.
4. Operands are values and Operators are symbols that represent particular actions.
Expression Validity
a+b Valid
++a+b Invalid
a valid
Assignment Statements
Statement used to assign some values,(1) Assignment stmt. (2) Shorthand assignment

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 9
Switch Statements
For check multiple condition (Alternate to else if ladder)
Syntax Flow diagram Example
switch(expression) switch(choice)
{ {
case 1: case 1:
code block 1 printf(%d”,a+b);
break; break;
case 2: case 2:
code block 2 printf(%d”,a-b);
break; break;
case n: case 3:
code block n printf(%d”,a*b);
break; break;
default: case 4:
code block for default case printf(%d”,a/b);
} break;
default:
If the expression = 1, case 1 printf(“No case is
block runs and break, selected”);
otherwise go and check the }
consecutive cases.
If no one case is matched,
runs the default block.

Looping statements
For execute statement(s) more than 1 time based on the condition
While loop (Entry check loop)
Syntax Flow diagram Example
while(condition) n=3;
{conditional code} s=”Program”;
while(n > 0)
Here, conditional code may be {printf(“%s”,s);
a single statement or a block n = n – 1;
of statements. }
The condition may be any
expression. The loop iterates Initial value for n=3,
while the condition is true.
Condition n>0,
the flow of execution:
1. Determine whether the Every time n is
condition is true or false. reassigned with n-1,
2. If false, exit the while
statement and continue Print the word
execution at the next “program” for three
statement. times (n=3,n=2,n=1) and
3. If the condition is true, run come out from the loop
the body and then go back to
step 1.

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 10
Do While loop(exit check loop)
Syntax Flow diagram Example
do n=3;
{ conditional code } s=”program”;
while(expression); do{
printf(“%s”,s);
the flow of execution: n = n – 1;
1. Execute conditional code }while(n>0);
2. Determine whether the
condition is true or false. Initial value for n=3,
2. If false, exit the while statement condition n>0,
and continue execution at the next Every time n is
statement. reassigned with n-1,
3. If the condition is true, go back
to step 1. Print the word
“program” for three
times(n=3,n=2,n=1)
and come out from the
loop

Break and Continue


Syntax Flow Diagram Example
break (break the loop n=0;
execution) while (n<10)
{ n=n+1;
if(n == 5)
break;
printf(“%d”,n);
}
Output: 1 2 3 4
If n==5, it break the loop

continue (skip the rest of n=0;


the loop body and continue while (n<10)
with the loop) { n=n+1;
if(n == 5)
continue;
printf(“%d”,n);
}
Output: 1 2 3 4 6 7 8 9
If n==5, it skip the loop
body and continue with the
loop

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 11
For Loop
Syntax Flow diagram Example
for(initial value, for(i=0;i<5;i++)
condition; inc/dec) {
{conditional code printf(“%d”,i);
} }

Flow of Execution:
S1:The iterating_var i is initialized with 0, then
initialized, check for the condition and
S2:Then Check for the execute the code,
condition then it is automatically
S3: Execute code incremented by 1
S4:increment/decrement When i is reach the range,
the step value come out from the loop
S5:goto S2 output:
01234

Go to Statement
A non conditional statement, to jump from one block of code to another;
Types: 1) forward goto 2) backward goto

Example for forward goto:

printf(“C program”);
goto XX:
printf(“Lab”);
XX: printf(“completed”);

Output: C program completed

Input/Output statements
There are some library functions which are available for transferring the information between the
computer and the standard input and output devices.
These functions are available in the header file.

Some of the input and output functions are as follows:


i) printf
This function is used for displaying the output on the screen
Syntax:
printf(“format string”, arg1, arg2, …..);

In the above syntax, 'format string' will contain the information that is formatted.

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 12
Format String Meaning
%d Specify a decimal number
%f Specify a floating point number
%c Specify a character
%s To scan or print a character string. The scanning ends at whitespace.
%o Specify a Octal
%x Specify a hexa decimal value
%l Specify long integer
\n For new line
\t Tab
\r Carriage return

ii) scanf
scanf is used when we enter data by using an input device.

Syntax:
scanf (“format string”, &arg1, &arg2, …..);

The number of items which are successful are returned.

Format string consists of the conversion specifier. Arguments can be variables or array name and
represent the address of the variable. Each variable must be preceded by an ampersand (&). Array
names should never begin with an ampersand.

Example:
int avg;
float per;
char grade;
scanf(“%d %f %c”,&avg, &per, &grade):
• scanf works totally opposite to printf. The input is read, interpret using the conversion
specifier and stores it in the given variable.
• The conversion specifier for scanf is the same as printf.
• scanf reads the characters from the input as long as the characters match or it will
terminate. The order of the characters that are entered are not important.
• It requires an enter key in order to accept an input.
iii) getch
This function is used to input a single character. The character is read instantly and it does not
require an enter key to be pressed. The character type is returned but it does not echo on the
screen.
Syntax:
ch=getch();
where, ch - assigned the character that is returned by getch.

iv) putch
this function is a counterpart of getch. Which means that it will display a single character on the
screen. The character that is displayed is returned.
Syntax:
putch(ch);

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 13
where, ch - the character that is to be printed.

v) getche
This function is used to input a single character. The main difference between getch and getche is
that getche displays the (echoes) the character that we type on the screen.
Syntax:
ch=getche();

vi) getchar
This function is used to input a single character. The enter key is pressed which is followed by the
character that is typed. The character that is entered is echoed.
Syntax:
ch=getchar();

vii) putchar
This function is the other side of getchar. A single character is displayed on the screen.
Syntax:
putchar(ch);

viii) gets and puts


The gets and puts function are used to offer simple alternatives of scanf and printf for reading and
displaying.
But gets accept string even with blank space;
If gets is used enter key has to be pressed for ending the string.
Example:
#include <stdio.h>
void main()
{
char line[30];
gets (line);
puts (line);
}

Preprocessor Directives
The task which are carried out before compilation is called preprocessor directives.
Directives Usage Example
#include to paste code of given file into current #include<stdio.h>
file #include”c:\tc\include\conio.h”
#define To define constant or define macros #define pi 3.14
#define cube(x) x*x*x
#ifdef To check anything defined #ifdef pi
#undef To undefined anything #undef pi
#ifndef To check if not defined #ifndef max
#define max 100
#if Use conditional statement before
#else compilation #if expression
#elif conditional codes
#endif #elif expression1
conditional codes
... .. ...
else
conditional codes
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 14
#endif

#error Prints error message on stderr.


#if mark>100
#error marks exceeds the limit
#endif
#pragma Issues special commands to the void func1();
compiler, using a standardized method #pragma startup func1
#pragma exit func1
Ex: Compiler run func1 before void func1()
executing main and after executing main { printf("Inside func1()\n");
}
int main()
{
printf("Inside main()\n");
return 0;
}

Compilation
• User writes a program in C language
(high-level language).
• The preprocessor deals with macro-
processing, augmentation, file
inclusion, language extension, etc.
• The C compiler, compiles the
program and translates it to assembly
program (low-level language).
• An assembler then translates the
assembly program into machine code
(object).
• A linker tool is used to link all the
parts of the program together for
execution (executable machine code).
• A loader loads all of them into
memory and then the program is
executed.

Unit I – Programs: Using I/O, decision making and Looping stmts.

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 15
UNIT II ARRAYS AND STRINGS 9
Introduction to Arrays: Declaration, Initialization – One dimensional array – Example Program:
Computing Mean, Median and Mode - Two dimensional arrays – Example Program: Matrix
Operations (Addition, Scaling, Determinant and Transpose) - String operations: length, compare,
concatenate, copy – Selection sort, linear and binary search

Arrays:
Array is a derived data type (deriving from the basic types)
Need of the array : to store multiple value on single variable
Characteristics:
The elements of the array should be in same type
The elements are stored in consecutive memory locations
The size of the array is fixed

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
type arrayName [ arraySize ];
Ex : int Numbers[10]; // the array Numbers contain ten integers in consecutive locations
// the array index start from 0

Initializing Arrays
Array can be initialized in C either one by one or using a single statement as follows:
int mark[]={58,68,78,88,98}; // integer array with the size of 5
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array.
Example:
balance[4]=100.0;
Types of Array:
(1) One dimensional array // int mark[9]
(2) Two dimensional array // int matrix[3][3]
(3) Multi dimensional array // int markofclass[60][8][9]

Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.
To declare a two-dimensional integer array of size x, y you would write something as follows:
type arrayName [ x ][ y ];
Ex: int a[3][3];

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 16
Initializing Two-Dimensional Arrays
Two dimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array.
For example: int val = a[2][3];
Multi-dimensional Arrays
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:
type name[size1][size2]...[sizeN];
Example three dimensional integer array:
int markofclass[60][8][9];
// 60 – denote the number of students in the class
// 8 – denote the number of semesters
// 9 – number of subjects per semester
markofclass[0][1][4]; // refers the first students, second semesters 5th subject marks.
Character array:
Like number arrays, we can create character array (called string)
Ex: char name[30]; /* is a 1 Dimensional character array to handle a string
char name[60][30]; /* is 2 Dimensional character array to handle 60 names for a class
initializing and working with character array:
char name[30]=”Deniss”;
printf(“%s”,name); // print the name Deniss
printf(“%c”,name[0]);// print the character D
char name[2][30]={“Deniss”,”Ritchee”};
printf(%s”,name[0]); // print the first name Deniss
Example Program: Matrix operations – Addition
#include <stdio.h> for(i=0;i<m1r;i++)
#define MAXR 10 for(j=0;j<m1c;j++)
#define MAXC 10 scanf("%d",&m1[i][j]);
int main()
{ for(i=0;i<m2r;i++)
int m1[MAXR][MAXC],m2[MAXR][MAXC]; for(j=0;j<m2c;j++)
int m3[MAXR][MAXC]; scanf("%d",&m2[i][j]);
int m1r,m1c,m2r,m2c,i,j;
printf("Enter size of Matrix1"); for(i=0;i<m1r;i++)
scanf("%d %d",&m1r,&m1c); for(j=0;j<m1c;j++)
printf("Enter size of Matrix2"); m3[i][j]=m1[i][j]+m2[i][j];
scanf("%d %d",&m2r,&m2c);
if(m1r!=m2r || m1c!=m2c) for(i=0;i<m1r;i++)
{printf("Size mismatch"); {printf("\n");
return 0; for(j=0;j<m1c;j++)
} printf("%d\t",m3[i][j]);
}
return 0;
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 17
Example Program: Matrix operations - Multiplication
#include <stdio.h>
#define MAXR 10 for(i=0;i<m2r;i++)
#define MAXC 10 for(j=0;j<m2c;j++)
int main() scanf("%d",&m2[i][j]);
{
int m1[MAXR][MAXC],m2[MAXR][MAXC]; for(i=0;i<m1r;++i)
int m3[MAXR][MAXC]; for(j=0;j<m2c;++j)
int m1r,m1c,m2r,m2c,i,j,k; {m3[i][j]=0;
printf("Enter size of Matrix1"); for(k=0;k<m1c;++k)
scanf("%d %d",&m1r,&m1c); m3[i][j]=m3[i][j]+m1[i][k]*m2[k][j];
printf("Enter size of Matrix2"); }
scanf("%d %d",&m2r,&m2c); for(i=0;i<m1r;i++)
if(m1c!=m2r) {printf("\n");
{printf("Size mismatch"); for(j=0;j<m2c;j++)
return 0; printf("%d\t",m3[i][j]);
} }
for(i=0;i<m1r;i++) return 0;
for(j=0;j<m1c;j++) }
scanf("%d",&m1[i][j]);

Example Program: Find mean, median and mode


#include <stdio.h> double median(int*b,int n)
#define MAX 100 {
double mean(int*,int); double med;
double median(int*,int); if(n%2==0)
int mode(int*,int); med=(b[n/2]+b[n/2-1])/2;
void main() else
{ med=b[n/2];
int a[MAX]; return med;
int i,n,mod; }
double men,med;
printf("Enter no of elements for the array "); int mode(int*b,int n)
scanf("%d",&n); {
printf("Enter n elements"); int count=0,counti=0,i,j,mod;
for(i=0;i<n;i++) for(i=0;i<n-1;i++)
scanf("%d",&a[i]); {
men=mean(a,n); counti=1;
med=median(a,n); for(j=i+1;j<n;j++)
mod=mode(a,n); {
printf("\nThe mean is %f\n the median is if(b[i]==b[j])
%f\nthe mode is %d",men,med,mod); counti++;
} }
double mean(int*b,int n) if(count<counti)
{ int i,sum=0; {
double mn; count=counti;
for(i=0;i<n;i++) mod=b[i];
{ sum=sum+b[i]; } }
mn=(float)sum/n; }
return mn; return mod;
} }
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 18
Transpose of matrix Scaling
#include <stdio.h> #include <stdio.h>
#define MAXR 10 #define MAXR 10
#define MAXC 10 #define MAXC 10
int main() int main()
{ {
int m1[MAXR][MAXC]; int m1[MAXR][MAXC];
int m1r,m1c,i,j; int m1r,m1c,i,j,s;
printf("Enter size of Matrix1"); printf("Enter size of Matrix1");
scanf("%d %d",&m1r,&m1c); scanf("%d %d",&m1r,&m1c);
for(i=0;i<m1r;i++) for(i=0;i<m1r;i++)
for(j=0;j<m1c;j++) for(j=0;j<m1c;j++)
scanf("%d",&m1[i][j]); scanf("%d",&m1[i][j]);

for(i=0;i<m1r;i++) printf("Enter Scaling ");


{printf("\n"); scanf("%d",&s);
for(j=0;j<m1c;j++)
printf("%d\t",m1[j][i]); for(i=0;i<m1r;i++)
} {printf("\n");
return 0; for(j=0;j<m1c;j++)
} printf("%d\t",m1[j][i]*c);
}
return 0;
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 19
Example Program: Matrix operations - Determinant
#include <stdio.h> int det(int A[100][100], int n)
#include <stdlib.h> {
#include <conio.h> int Minor[100][100];
int i,j,k,c1,c2;
main() int determinant;
{ int c[100];
int A[100][100]; int O=1;
int i,j,k,n,res;
printf("Enter size of the matrix: \n"); if(n == 2)
scanf("%d",&n); {
printf("\nEnter the elements of the determinant = 0;
matrix one by one: \n"); determinant = A[0][0]*A[1][1]-A[0][1]*A[1][0];
for(i = 0 ; i < n ; i++) return determinant;
{ }
for(j = 0 ; j < n ; j++) else
{ {
scanf("%d",&A[i][j]); for(i = 0 ; i < n ; i++)
} {
} c1 = 0, c2 = 0;
for(i = 0 ; i < n ; i++) for(j = 0 ; j < n ; j++)
{ {
for(j = 0 ; j < n ; j++) for(k = 0 ; k < n ; k++)
{ {
printf("%5d",A[i][j]); if(j != 0 && k != i)
} {
printf("\n"); Minor[c1][c2] = A[j][k];
} c2++;
res = det(A,n); if(c2>n-2)
printf("%d",res); {
} c1++;
c2=0;
}
}
}
}
determinant = determinant +
O*(A[0][i]*det(Minor,n-1));
O=-1*O;
}
}
return determinant;
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 20
Selection Sort Linear Search
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int array[100], n, c, d, position, swap; int array[100], search, c, n;
printf("Enter number of elements\n"); printf("Enter number of elements in array\n");
scanf("%d", &n); scanf("%d", &n);
printf("Enter %d integers\n", n); printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++) for (c = 0; c < n; c++)
scanf("%d", &array[c]); scanf("%d", &array[c]);
for (c = 0; c < (n - 1); c++) printf("Enter a number to search\n");
{ scanf("%d", &search);
position = c; for (c = 0; c < n; c++)
for (d = c + 1; d < n; d++) {
{ if (array[c] == search)
if (array[position] > array[d]) {
position = d; printf("%d is present at location
} %d.\n", search, c+1);
if (position != c) break;
{ }
swap = array[c]; }
array[c] = array[position]; if (c == n)
array[position] = swap; printf("%d isn't present in the
} array.\n", search);
} return 0;
printf("Sorted list in ascending order:\n"); }
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}
Binary Search
#include <stdio.h> while (first <= last) {
int main() if (array[middle] < search)
{ first = middle + 1;
int c, first, last, middle, n, search, array[100]; else if (array[middle] == search) {
printf("Enter number of elements\n"); printf("%d found at location
scanf("%d",&n); %d.\n", search, middle+1);
printf("Enter %d integers\n", n); . break;
for (c = 0; c < n; c++) }
scanf("%d",&array[c]); else
printf("Enter value to find\n"); last = middle - 1;
scanf("%d", &search);
first = 0; middle = (first + last)/2;
last = n - 1; }
middle = (first+last)/2;
if (first > last)
printf("Not found! %d isn't present in the
list.\n", search);

return 0;
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 21
Strings
Strings are one-dimensional array of characters terminated by a null character '\0'.
Declaring a string
char str[30];
Ex: Initializing a string
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char str[]=”Hello”;
The C compiler automatically places the '\0' at the end of the string when it initializes the array.
Following is the memory presentation of the above defined string in C

Multiple strings using two dimensional array


#include<stdio.h> Output:
Void main() Arun
{ Ashok
int i; Babu
char name[4][30]={"Arun","Ashok","Babu","Bala"}; Bala
for(i=0;i<4;i++)
printf("%s\n",name[i]);
}
#include<stdio.h> Input:
#include<string.h> Arun Kumar
int main() Ashok kumar
{ Babu
int i; Bala kumar
char name[4][30];
for(i=0;i<4;i++) Output
gets(name[i]); // scanf(“%[^\n]”,name[i]); Arun Kumar
Ashok kumar
for(i=0;i<4;i++) Babu
puts(name[i]); Bala kumar
return 0;
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 22
String Operations
int length(char *str) int compare(char *str1,char *str2)
{ {
int i=0; int i=0;
while(str[i]!='\0') while(str1[i]!='\0' || str2[i]!='\0' )
{i++;} {
return i; if(str1[i]!=str2[i])
} return -1;
i++;
}
int main() return 0;
{ }
int l; int main()
char s1[]="Hello"; {
l=length(s1); int l;
printf("%d",l); char s1[]="Hello",s2[]="Hello";
return 0; l=compare(s1,s2);
} printf("%d",l);
return 0;
}
void concat(char *str1,char *str2) void copy(char *str1,char *str2)
{int i=0,j=0; {int i=0;
while(str1[i]!='\0') while(str2[i]!='\0')
{i++;} {str1[i]=str2[i];
while(str2[j]!='\0') i++;
{str1[i]=str2[j]; }
i++; str1[i]='\0';
j++;} }
str1[i]='\0';
} int main()
{
int main() int l;
{ char s1[]="Hello",s2[]="Helloo";
int l; copy(s1,s2);
char s1[]="Hello",s2[]="Helloo"; printf("%s",s1);
concat(s1,s2); return 0;
printf("%s",s1); }
return 0;
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 23
//Program to print no vowels, consonants, digits and white space in the given string
#include <stdio.h>
int main()
{
char line[150];
int i, vowels=0, consonants=0, digits=0, spaces=0;
printf("Enter a line of string: ");
scanf("%[^\n]",line);
for(i=0; line[i]!='\0'; ++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u')
++vowels;
else if((isalpha(line[i])
++consonants;
else if(isdigit(line[i])
++digits;
else if(line[i]==' ')
++spaces;
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d", spaces);
}
//Program to print no vowels, consonants, digits and white space in the given string
#include<stdio.h>
#include<string.h>
Void main()
{
int i,j,count;
char str[25][25],temp[25];
puts("How many strings u are going to enter?: ");
scanf("%d",&count);

puts("Enter Strings one by one: ");


for(i=0;i<=count;i++)
gets(str[i]);
for(i=0;i<=count;i++)
for(j=i+1;j<=count;j++)
{
if(strcmp(str[i],str[j])>0) //return 0 if both are same, return > 0 if first is greater
{ // return 0< if second is greater
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("Order of Sorted Strings:");
for(i=0;i<=count;i++)
puts(str[i]);
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 24
UNIT III FUNCTIONS AND POINTERS
Introduction to functions: Function prototype, function definition, function call, Built-in functions
(string functions, math functions) –Recursion –Example Program: Computation of Sine series,
Scientific calculator using built-in functions, Binary Search using recursive functions –Pointers –
Pointer operators –Pointer arithmetic –Arrays and pointers –Array of pointers –Example Program:
Sorting of names –Parameter passing: Pass by value, Pass by reference –Example Program:
Swapping of two numbers and changing the value of a variable using pass by reference
Functions
A function is a subprogram of one or more statements that performs a specific task when
called.
Advantages of Functions:
1. Code reusability
2. Better readability
3. Reduction in code redundancy
4. Easy to debug & test.
Classification of functions:
• Based on who develops the function
o Library functions (built-in functions)
o User defined functions
• Based on type of arguments
o Call by value
o Call by reference
• Based on the number of arguments a function accepts
o Function without argument without return value
o Function with argument without return value
o Function without argument with return value
o Function with argument and with return value

User Defined Functions:


The functions which are defined by the users.

Declaration of Function ( Function prototype)


All the function need to be declared before they are used.
General form:
returntype functionname (parameter list or parameter type list);

a) Return type – data type of return value. It can be int, float, double, char, void etc.
b) Function name – name of the function
c) Parameter type list –It is a comma separated list of parameter types. Parameter names are
optional.
Ex: int add(int, int);
or
int add(int x, int y);

Function declaration must be terminated with a semicolon(;).

FUNCTION DEFINITION
It is also known as function implementation. Every function definition consists of 2 parts:
1. Header of the function
2. Body of the function

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 25
1. Header of the function
General form:
returntype functionname (parameter list)

1. The header of the function is not terminated with a semicolon.


2. The return type and the number & types of parameters must be same in both function
header & function declaration.

2. Body of the function


• It consists of a set of statements enclosed within curly braces.
• The return statement is used to return the result of the called function to the calling
function.

General form of Function Definition


returntype functionname (parameter list)
{ statements;
return (value);
}

FUNCTION CALL:
• A function can be called by using its name & actual parameters.
• It should be terminated by a semicolon ( ; ).
Working of a function
int abc(int, int, int); // Function declaration

void main()
{
int x,y,z;
…..
…..
abc(x,y,z); // Function Call

Actual arguments

}

int abc(int i, int j, int k) // Function definition


{
Formal arguments
…….
….
return (value);
}

Calling function – The function that calls a function is known as a calling function.
Called function – The function that has been called is known as a called function.
Actual arguments – The arguments of the calling function are called as actual arguments.
Formal arguments – The arguments of called function are called as formal arguments.
Steps for function Execution:
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 26
1. After the execution of the function call statement, the program control is transferred to
the called function.
2. The execution of the calling function is suspended and the called function starts
execution.
3. After the execution of the called function, the program control returns to the calling
function and the calling function resumes its execution.

Pass by value & Pass by reference


Argument passing methods in ‘C’ are,
1. Pass by value
2. Pass by reference
Pass by Value Pass by reference
Functions are called by passing values Functions are called by passing
address(reference).
• In this method the values of actual • In this method, the addresses of the
arguments are copied to formal actual arguments are passed to formal
arguments. argument.
• Any change made in the formal • Thus formal arguments points to the
arguments does not affect the actual actual arguments.
arguments. • So changes made in the arguments are
• Once control, return backs to the calling permanent.
function the formal parameters are
destroyed.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void swap(int ,int); void swap(int *,int *);
void main()
{ void main()
int a,b; {
a=10; int a,b;
b=20; a=10;
printf("\n Before swapping: a = %d and b b=20;
= %d",a,b); printf("\n Before swapping: a= %d
swap(a, b); and b= %d",a,b);
printf("\n After swapping: a= %d swap(&a,&b);
and b= %d",a,b); printf("\n After swapping: a= %d
getch(); and b= %d",a,b);
} getch();
}
void swap(int a1,int b1) void swap(int *a1,int *b1)
{ {
int temp; int t;
temp=a1; t = *a1;
a1=b1; *a1 = *b1;
b1=temp; *b1 = t;
} }
OUTPUT: OUTPUT:
Before swapping: a =10 and b =20 Before swapping: a = 10 and b = 20
After swapping: a =10 and b = 20 After Swapping : a=20 and b=10

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 27
4.5. Built in Functions (Library functions)
Library functions are predefined functions. These functions are already developed by
someone and are available to the user for use.
Declaration:
The declarations of library functions are available in the respective header files. To use a
library function, the corresponding header file must be included.

Built-in function (String functions)


Sno Function Description Example
1 strlen(str) Return length of the string str=”hellow”
strlen(str); # 6
2 strcmp(str1,str2) Return 0 if both are same, Return str1=”hellow”; str2=”hellow”
positive if str1 is greater strcmp(str1,str2) # return 0
Return negative if str2 is greater
3 strncmp(str1,str2,n) Return 0 if first n characters are str1=”hellow”;
same, otherwise return non zero str2=”helicopter”
strcmp(str1,str2,3) # return 0
4 strcmpi(str1,str2) Return 0 if both are same str1=”hellow”;
(upper/lower), otherwise return str2=”HELLOW”
non zero strcmp(str1,str2) # return 0
5 strcopy(str1,str2) Copy the content of str2 to str1 str1=”hellow”; str2=”world”
strcpy(str1,str2);
#str1<-“world”
6 strncopy(str1,str2,n) Copy the first n character of str2 str1=”hellow”; str2=”world”
to str1 strcpy(str1,str2,3);
#str1<-“wor”
7 strcat(str1,str2) Concatenate str1 and str2 and str1=”hellow”; str2=”world”
assigned to str1. strcat(str1,str2);
#str1<-“hellowworld”
8 strncat(str1,str2,n) Concatenate str1 and first n str1=”hellow”; str2=”world”
character of str2 and assigned to strcat(str1,str2,3);
str1. #str1<-“hellowwor”
9 strupr(str1) Convert lower case to upper case str1=”hellow”
strupr(str1);
#str1<- “HELLOW”
10 strlwr(str1) Convert Upper case to lowercase str1=”Hellow”
strupr(str1);
#str1<- “hellow”
11 strchr(str1,char) Return pointer of the first str1=”Hellow”
occurrence of the character strchr(str1,‘l’);
(from beginning) #return address of l from left
12 strrchr(str1,char) Return pointer of the first str1=”Hellow”
occurrence of the character strchr(str1,‘l’);
(from last) #return address of l from right
13 strstr(str1,str2) Return pointer of the first str1=”Hellow world”,
occurrence of the str2 str2=”world”
(from beginning) strchr(str1,str2);
#return address of str2 from left
14 strrstr(str1,str2) Return pointer of the first str1=”Hellow world”,
occurrence of the str2 str2=”world”
(from last) strchr(str1,str2);

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 28
#return address of str2 from
right
15 strset(str1,char) Set all the characters of the string str1=”Hellow”
with given character strset(str1,‘h’);
#str1<-“hhhhhh”
16 strrev(str1) Reverse the contents of string str1=”Hellow”
strrev(str1);
#str1<-“wolleH”
17 strtok(str1,delimeter Tokenizing using delimiter Str1=”Hellow world,hai;”
s) Strtok(str1,” ,;”);
Built-in function (Mathematical functions)
Sno Function Description Example
1 qqrt(no) Return the square root of the sqrt(4) is 2
given no
2 pow(no1,no2) Return the power pow(2,3) is 8
3 floor(real no) Return the next integer(>=) floor(2.1) is 3
4 ceil(real no) Return the previous integer ceil(2.9) is 2
(<=)
5 round(real no) Return next if >.5 round(2.6) is 3
Return previous if <.6 round(2.4) is 2
6 trunc(real no) Return the integer part only trunc(2.6) is 2
trunc(2.4) is 2
7 sin(no) Return sine value of the no sin(0) is 0
8 cos(no) Return the cosine value of the cos(0) is 1
no
9 tan(no) Return the tangent value of the tan(0) is 0
no
10 log(no) Return the natural logarithm of log(2.0) is 0.693147
the given no
11 log10(no) Return base 10 logarithm of the log10(10.0) is 1.0
given no
12 exp(no) Return the exponential value exp(1.) is 2.718282
13 abs(no) Return the absolute value (+ve abs(-10) is 10
value) abs(10) is 10
14 fabs(real no) Return the absolute value (+ve fabs(-10.1) is 10.1
value) fabs(10.1) is 10.1
15 fmod(real no, real no) Return the modulus for floating fmod(13.657, 2.333) is 1.992
point values
RECURSION
A function that calls itself is known as a recursive function.
Advantages
• Reduce unnecessary calling of function.
• Through Recursion one can Solve problems in easy way while its iterative solution is very
big and complex.
Disadvantages
• Recursive solution is always logical and it is very difficult to trace.(debug and
understand).
• In recursive we must have an if statement somewhere to force the function to return
without the recursive call being executed, otherwise the function will never return.
• Recursion takes a lot of stack space, usually not considerable when the program is small
and running on a PC.

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 29
• Recursion uses more processor time.
Types of Recursion:
1. Direct Recursion: A function call itself for several times
2. Indirect Recursion: Function A calls function B and Function B calls A

Recursive function for find the factorial


int fact(int n) Consider the calculation of 6!
{ ie 6! = 6 * 5 * 4 * 3 * 2 * 1
if(n==1) 6! = 6 * 5!
return(1); 6! = 6 * ( 6 - 1 )!
else n! = n * ( n - 1 )!
return n*fact(n-1);
}

Recursive function for Binary Search


int main() int RecBinSearch (int arr[], int low, int
{ high, int element)
int count, element, limit, arr[50], position; {
printf("\nEnter the Limit of Elements in Array:\t"); int middle;
scanf("%d", &limit); if(low > high)
printf("\nEnter %d Elements in Array: \n", limit); {
for(count = 0; count < limit; count++) return -1;
{ }
scanf("%d", &arr[count]); middle = (low + high) / 2;
} if(element > arr[middle])
printf("\nEnter Element To Search:\t"); {
scanf("%d", &element); RecBinSearch (arr, middle + 1, high,
position = RecBinSearch(arr, 0, limit - 1, element); element);
if(position == -1) }
{ else if(element < arr[middle])
printf("\nElement %d Not Found\n", element); {
} RecBinSearch (arr, low, middle - 1,
else element);
{ }
printf("\nElement Found at Position %d\n", else
position + 1); {
} return middle;
return 0; }
} }

Program for Sin series


#include <stdio.h> int main()
#include <math.h> {
float x,Q,sum=0;
int fac(int x) int i,j,limit;
{ printf("Enter the value of x of sinx series: ");
int i,fac=1; scanf("%f",&x);
for(i=1;i<=x;i++) printf("Enter the limit for the series: ");
fac=fac*i; scanf("%d",&limit);
return fac; Q=x;
} x = x*(3.1415/180);
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 30
for(i=1,j=1;i<=limit;i++,j=j+2)
{
if(i%2!=0)
{
sum=sum+pow(x,j)/fac(j);
}
else
sum=sum-pow(x,j)/fac(j);
}
printf("Sin(%0.1f): %f",Q,sum);
return 0;
}

POINTERS
Pointer is a variable that stores/points the address of another variable.
The pointer variable might be belonging to any of the data type such as int, float, char, double,
short etc.
• Pointer Syntax : data_type *var_name;
• Example : int *p; char *p;
• Where, * is used to denote that “p” is pointer variable and not a normal variable.
• Normal variable stores the value whereas pointer variable stores the address of the
variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
Advantages
1. Pointers save memory space (using dynamic memory allocation).
2. Faster execution
3. It allows passing of arrays and strings to functions more efficiently.
4. It makes possible to return more than one value from the function.

Pointer Operators
(1)Reference operator (&) - It gives you the address of a variable
(2) Dereference operator (*) – It gets the value from the address

Declaring and accessing pointer variable


Memory Organization
int a=10; Variable Address Value
int *p,**q; a 2000 10
p=&a; p 2002 2000
printf(“%d”,a); // Prints the value of a = 10 q 2004 2002
printf(“%d”,*p); // *(2000) = 10
printf(“%d”,**q); // *(*(2002))=*(2000)=10

NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not have
an exact address to be assigned. This is done at the time of variable declaration. A pointer that is
assigned NULL is called a null pointer.
#include <stdio.h>

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 31
void main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr ); // prints 0
}
Pointer Arithmetic
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer. There are four arithmetic operators that can be used on pointers:
Operator Purpose Example
++ To increment the current pointer, to int val[5]={10,20,30,40,50};
point the next element in the array int *p=val; // p point the first element
++p; // p point the second element
-- To Decrement the current pointer, to int val[5]={10,20,30,40,50};
point the previous element in the int *p=&val[2]; // p point the third element
array --p; // p point the second element
+ To add a constant to the pointer, to int val[5]={10,20,30,40,50};
point any element in the array int *p=val; // p point the first element
p=p+3; // p point the fourth element
- To add a constant to the pointer, to int val[5]={10,20,30,40,50};
point any element in the array int *p=&val[4]; // p point the fifth element
p=p-3; // p point the second element
Relational To compare two pointers int val[5]={10,20,30,40,50};
operators int *p=val; // p point the first element
while(p <= &val[5])
printf(“%d”,*p++);

Arrays and Pointers


• Both are derived data types
• Array is a fixed size variable, the space is allocated during compilation time
• Pointers are addresses, the space is allocated during runtime, allows variable size data
• The pointer can be used to access the array elements, makes the accessing faster.
Passing array as parameter using pointer
void main() int sum(int *p,int n) // receiving the array in
{ ptr
int a[5]={10,20,30,40,50}; {int i,s=0;
int total; for(i=0;i<n;i++)
total=sum(a); // passing array as argument s=s+*p++;
printf(“%d”,total); return s;
} }
Array of pointers
There may be a situation when we want to maintain an array, which can store pointers to an int or
char or any other data type available.
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] ); }}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 32
Function Pointer in C
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is
a simple example that shows declaration and function call using function pointer.

void fun(int a)
{
printf("Value of a is %d\n", a);
}

int main()
{
void (*fun_ptr)(int) = fun;

fun_ptr(10);

return 0;
}

Function pointer can be used in place of switch case. For example, in below program, user is
asked for a choice between 0 and 2 to do different tasks.
#include <stdio.h>
void add(int a, int b)
{
printf("Addition is %d\n", a+b);
}
void subtract(int a, int b)
{
printf("Subtraction is %d\n", a-b);
}
void multiply(int a, int b)
{
printf("Multiplication is %d\n", a*b);
}

int main()
{
void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
unsigned int ch, a = 15, b = 10;

printf("Enter Choice: 0 for add, 1 for subtract and 2 for multiply\n");


scanf("%d", &ch);

if (ch > 2) return 0;

(*fun_ptr_arr[ch])(a, b);

return 0;
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 33
UNIT IV STRUCTURES AND DYNAMIC MEMORY ALLOCATION
Structure ‐ Nested structures – Pointer and Structures – Array of structures – Example Program
using structures and pointers – Self referential structures – Dynamic memory allocation ‐ Singly
linked list ‐typedef

Difference between arrays and structures


Arrays Structures
Arrays is a derived data type Structure is a user-defined data type.
Array refers to a collection of elements of Structure refers to a collection of elements of
similar data type. different data type.
Array elements are accessed by their index Structure elements are accessed by their names
number using subscripts. using dot operator.
Array size is fixed. Structure size is not fixed.
Array declaration is done simply using [] and Structure declaration is done with the help of
not any keyword. “struct” keyword.
Array elements are stored in continuous Structure elements may or may not be stored in a
memory locations. continuous memory location.
Structure traversal and searching is complex and
Array traversal and searching is easy and fast.
slow.
struct sruct_name{
data_type1 ele1;
data_type array_name[size];
data_type2 ele2;
};

Defining a Structure
Syntax Ex
struct struct_name struct student
{ {
member definition; int rno;
member definition; char name[30];
... char dept[10];
member definition; int mark[3];
}structure_variables; }st;

Declaring Structure variable


It is possible to declare a structure variable, at the time of structure is defined. Structure
variable declaration is similar to the declaration of any other data types.
void main()
{
struct student st;
}
Initializing Structure members
void main()
{
struct student st={1,"arun","cse",{50,60,70}};
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 34
Accessing Structure Members
To access any member of a structure, we use the member access operator (.)
struct student
{
int rno;
char name[30];
char dept[10];
int mark[3]; // Array within structure
};
void main()
{
struct student st;
scanf(“%d %s %s %d %d %d”,
&st.rno,st.name,st.dept,&st.mark[0],&st.mark[1],&st.mark[2]);
printf(“%d %s %s %d %d %d”, st.rno,st.name,st.dept,st.mark[0],st.mark[1],st.mark[2]);
}

Array of Structures
It is possible to create array of variables for structure.

struct student
{
int rno;
char name[30];
char dept[10];
int mark[3]; // Array within structure
};
void main()
{
struct student st[58];
int i;
for(i=0;i<58;i++)
{
scanf(“%d %s %s %d %d %d”,
&st[i].rno,st[i].name,st.dept,&st[i].mark[0],&st[i].mark[1],&st[i].mark[2]);
}
}

Nested Structure (or) Structure with in Structure

When a structure is declared as a member of another structure then it is called structure within
structure or nested structure.
Ex: address is a structure, which used as member of another structure (student).

struct address
{
int dno;
char street[50];
char city[50];
int pin;
};
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 35
struct student
{
int rno;
char name[30];
char dept[10];
struct address ad; // nested structure
};

void main()
{
struct student st;
scanf(“%d %s %s %d %s %s %d”
&st.rno, st.name, st.dept, &st.ad.dno, st.ad.street, st.ad.city, st.ad.pin);
} // Accessing inner structure member is,
<Outer structure variable> . <inner structure variable> . inner structure member

Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any other
variable as follows:
struct student st,*stp;
Now, you can store the address of a structure variable in the above defined pointer variable
stp=&st;
To access the members of a structure using a pointer to that structure, you must use the ->
operator as follows:
stp->rno;

Structures as Function Arguments


We can pass a structure as a function argument in very similar way as we pass any other variable
or pointer. We would access structure variables in the similar way as you have accessed in the
above example:

struct student void disply(struct student *sp)


{ {
int rno; int i;
char name[30]; for(i=0;i<58;i++)
char dept[10]; {
}; printf(“%d %s %s ”,
void disp(struct student *); // Function declaration sp->.rno, sp->.name, sp->dept);
void main() sp++; // point the next record
{ }
struct student st[58]; }
int i;
for(i=0;i<58;i++)
{
scanf(“%d %s %s”,
&st[i].rno, st[i].name, st.dept);
}
disply(st); // Function calling
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 36
Difference between Structure and Union

Dynamic Memory Allocation

Memory Allocation : Allocating memory location for the variable is called memory allocation.
There are two types of memory allocation,

1. Static Memory allocation


2. Dynamic memory allocation

Static Memory Allocation Dynamic Memory Allocation


In this case, variables get allocated only if
In this case, variables get allocated permanently
your program unit gets active
Allocation is done before program execution Allocation is done during program execution
(by compiler) (by the user)
It uses the data structure called stack for It uses the data structure called heap for
implementing static allocation implementing dynamic allocation
Less efficient More efficient
There is memory reusability and memory can
There is no memory reusability
be freed when not required

Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.


malloc() The malloc() function reserves a Syntax:
block of memory of the specified ptr = (cast-type*) malloc(byte-size)
number of bytes. And, it returns a Ex:
pointer of type void which can be int *a;
casted into pointer of any form a=(int*)malloc(sizeof(int));
calloc() The malloc() function allocates a Syntax:
single block of memory. Whereas, ptr = (cast-type*) calloc(n,byte-size)
calloc() allocates multiple blocks of Ex:
memory and initializes them to zero int *a;
a=(int*)calloc(n1 , sizeof(int));

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 37
realloc() If the dynamically allocated memory Syntax
is insufficient or more than required, ptr = realloc(ptr, x);
you can change the size of Ex:
previously allocated memory using a=realloc(a,n2); // n2 – new size
realloc() function
free() Dynamically allocated memory Ex:
created with either calloc() or free(a);
malloc() doesn't get freed on their
own. You must explicitly use free()
to release the space

Ex Program to allocate , reallocate and free;

#include <stdio.h>
#include <stdlib.h>

int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("\nEnter new size of array: ");


scanf("%d", &n2);
ptr = realloc(ptr, n2 * sizeof(int));

free(ptr);
return 0;
}

Dynamic memory allocation for two dimensional array (Matrix)

int main()
{
int **matrix;
int row,col;
scanf(“%d %d”,&row,&col);
matrix = (int **)malloc(row * sizeof(int *)); // Allocate row space
for (i=0; i<r; i++)
matrix[i] = (int *)malloc(col * sizeof(int)); // Allocate column space

for (i = 0; i < row; i++)


for (j = 0; j < col; j++)
scanf(“%d”,&matrix[i][j]);

for (i = 0; i < row; i++)


for (j = 0; j < col; j++)
printf(“%d”,matrix[i][j]);

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 38
/* Code for free the dynamically allocated memory */

for (i = 0; i < row; i++)


free(matrix[i]); // free column space

free(matrix) // free row space

return 0;
}

Dynamic memory allocation for structures

#include <stdio.h>
#include<stdlib.h>

struct student
{
int rno;
char name[30];
};

int main()
{
struct student *sptr;
int i, n;
printf("Enter number of records: ");
scanf("%d", &n);

// Allocates the memory for n records of structures


sptr = (struct student*) malloc (n * sizeof(struct student));
for(i = 0; i < n; ++i)
{
scanf("%d %s", &(sptr+i)->rno, (sptr+i)->name);
}
printf("Displaying Information:\n");
for(i = 0; i < n; ++i)
{
printf("%d %s", sptr+i)->rno, (sptr+i)->name);
}
return 0;
}

Self referential structure


A self-referential structure is one of the data structures which refer to the pointer to (points) to
another structure of the same type
Ex: Linked list node
struct node
{
int rno;
char name[30];
struct node *next;
};
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 39
Linked List implementation of list
 A linked list is a series of connected nodes but the nodes need not to stored in consecutive
location
 The size of the list is dynamic
 Each node contains at least
 A piece of data (any type)
 Pointer to the next node in the list
 Advantages over arrays
1) Dynamic size
2) Ease of insertion/deletion
 Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from
the first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
 Node Structure

struct node
{
int element;
node *next;
}
 Applications of Linked Lists
 Linked lists are used to implement stacks, queues, graphs, etc.
 Polynomial operations
 Multilist used for maintain a database.

 Types of Linked Lists


There are 3 different implementations of Linked List available, they are:

 Singly Linked List


 Can’t traverse backwards, only forward movements.
 Can’t access the previous node.
 A node can’t be deleted if the pointer to that node is given.
 Can’t move to the previous node.
 To access a particular node, traverse from the first node.

 Doubly Linked List

Node Structure:
struct node
{ int element;
node *next;
node *prev;
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 40
Merits:
 List can be traversed forward and backwards.
 Easy to delete a node given with that pointer.
Demerits:
 More space needed for two pointers forward & backward

 Circular Linked List


 The last node of the list point the first node of the list
 The previous node can be accessed by traversing in the loop.

 Ex: Linked list consist of 3 elements

o The last node points to NULL


o List uses only as much space as is needed for the elements currently on the list
o but requires space for the pointers in each cell

 Ex: Linked list after inserting the newnode at 3rd position


 Steps
 Locate 2nd node
 Allocate memory for the new node
 Point the new node to its successor(3rd node)
 Point the new node’s predecessor(2nd node) to the new node

* Steps for delete the node 2


o Find the previous node (1st node)
o Release the memory occupied by the found node (2nd node)
o Set the pointer of the predecessor (1st node) to the successor (3rd node)

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 41
Linked list implementation:

#include<stdio.h> list insert(list l1,int pos,int v)


#include<conio.h> {
struct node list newnode,l2;
{ int i;
int element; l2=l1;
struct node *next; newnode=malloc(sizeof(struct node));
}; newnode->element=v;
typedef struct node* list; if(pos==1)
list insert(list,int,int); {
list del(list,int); newnode->next=l1;
list find(list,int); return newnode;
list findprevious(list,int); }
void print(list); else
{
void main() for(i=1;i<pos-1&&l1->next!=NULL;i++)
{ {
list l=NULL,t=NULL; l1=l1->next;
int val,pos,choice=0; }
while(choice<5) newnode->next=l1->next;
{ l1->next=newnode;
clrscr(); return l2;
printf("\n1.Insert\n2.delete\n3.find\n4.Printlist\n }
5.Exit\nEnter your choice"); }

scanf("%d",&choice); list del(list l1,int v)


switch(choice) {
{ list tmp,fp;
case 1: if(l1->element==v)
printf("Enter position and element"); {
scanf("%d%d",&pos,&val); tmp=l1;
l=insert(l,pos,val); l1=l1->next;
break; free(tmp);
case 2: return l1;
printf("Enter element to delete"); }
scanf("%d",&val); else
l=del(l,val); {
break; fp=findprevious(l1,v);
case 3: tmp=fp->next;
printf("Enter element to find"); fp->next=fp->next->next;
scanf("%d",&val); free(tmp);
t=find(l,val); return l1;
printf("element found%d",t->element); }
break; }
case 4:
print(l); void print(list l1)
getch(); { while(l1!=NULL)
break; { printf("%d->",l1->element);
} l1=l1->next;
} }
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 42
} }
list find(list l1,int v) list findprevious(list l1,int v)
{ {
while(l1!=NULL) while(l1->next!=NULL)
{ if(l1->element==v) { if(l1->next->element==v)
return l1; return l1;
l1=l1->next; l1=l1->next;
} }
return NULL; return NULL;
} }

typedef in C
typedef is a keyword used in C language to assign alternative names to existing data types. Its
mostly used with user defined data types, when names of the data types become slightly
complicated to use in programs. Following is the general syntax for using typedef

typedef <existing name> <alias name>

Ex:1
typedef int I;
void main()
{
I n; // equal to int n;
}

Ex:2
typedef struct student_detail
{
int rno;
char name[30];
} student;

void main()
{
student st;
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 43
Unit V : File Processing
Files – Types of file processing: Sequential access, Random access – Sequential access file ‐
Example Program: Finding average of numbers stored in sequential access file ‐ Random access file
‐ Example Program: Transaction processing using random access files – Command line arguments

Files: A named storage area, can store data or program in hard disk(secondary memory)

Why files are needed?

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

Types of files :
Text file :
• Can handle alphanumeric characters (Text)
• Text files are the normal .txt files that you can easily create using 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.
Binary files :
• Can handle audio, video , images and text
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form (0's and 1's).
• They can hold higher amount of data, are not readable easily and provides a better security
than text files.

File Operations:
In C, you can perform four major operations on the file, either text or binary:
1. Creation of a new file
2. Opening an existing file
3. Reading from file
4. Writing to a file
5. Moving to a specific location in a file
6. Closing a file

Steps for Processing a File

• Declare a file pointer variable.


• Open a file using fopen() function.
• Process the file using the suitable function.
• Close the file using fclose() function.

Opening a file - for creation and edit

Opening a file is performed using the library function in the "stdio.h" header file: fopen().

FILE *fp; //fp- file pointer

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 44
fp=fopen(<file_name>, <access_mode>);
file_name: That contains the name of the file that you want to access.
access_mode: The access_mode determines the mode in which the file has to be opened

Ex: fp=fopen(“data.txt”,”w”); // file data.txt created in write mode

File Modes

File Meaning of Mode During Inexistence of file


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

File Functions

FILE *fptr;

S No Function Purpose / Example


fptr=fopen(“data.txt”,”w”);
1 fopen
create/open a file data.txt for write opeartion
fclose(fptr);
2 fclose
close the opened file data.txt after the operations
char ch;
ch=getchar();
3 putc
putc(ch,fptr);
Write the character to the file
char ch;
ch=getc(fptr);
4 getc
Read the character from the file, after reading the pointer move to next
character
int no;
5 putw scanf(“%d”,&no);
putw(no,fptr);

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 45
Write an integer to file
int no;
6 getw no=getw(fptr);
Read integer from file
int no;
char name[30];
7 fprintf scanf(“%d %s”,&no,name);
fprintf(fptr,”%d%s”,no,name);
Write the formatted content to the file
int no;
char name[30];
8 fscanf
fscanf(fptr,”%d%s”,&no,name);
Read the formatted content from the file
char name[30];
scanf(“%s”,name);
9 fputs
fputs(fptr, name);
Write the string to the file
char name[30];
10 fgets fgets(fptr,30,name);
Read the 30 byte string from the file
Detects end-of-file marker in a file
feof() which returns non-zero value only if end of file has reached,
otherwise it returns 0.
11 feof
if (feof(fptr))
printf("\n End of file reached.");

scanf("%d %s",&st.rno,st.name); // read data for student structure


fwrite(&st, sizeof(struct student), 1, fptr);
12 fwrite Write binary content (1 student record) to the file
fwrite(st, sizeof(struct student), 58, fptr);
Write binary content (58 student record to the file
fread(&st, sizeof(struct student), 1, fptr);
Read binary content (1 student record) from the file
13 fread
fread(st, sizeof(struct student), 58, fptr);
Read binary content (58 student record) from the file
int position;
14 ftell position=ftell(fptr);
Tell the current position(no of bytes from the beginning) of the file pointer
fseek(fptr,sizeof(struct student)*(i-1),0);
Move the file pointer to ith record from the beginning of the file
fseek(fptr,sizeof(struct student)*(i-1),1);
15 fseek
Move the file pointer to ith record from the current record
fseek(fptr,sizeof(struct student)*(-i),2);
Move the file pointer to ith record from the end of the file
rewind(fptr);
16 rewind
Move the file pointer to the beginning of the file

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 46
Example : getc() and putc() Example: getw() and putw()
Write set of character to the file and read the same Finding average of numbers using sequential
and print access file
#include <stdio.h> #include<stdio.h>
int main() int main()
{ {
FILE *fptr; FILE *fptr;
char c; int i,m,n,sum=0;
fptr =fopen("Input.txt", "w"); fptr=fopen("file1.txt","w");
while((c=getchar())!=EOF) for(i=0;i<5;i++)
putc( c, fptr); {
fclose(fptr); scanf("%d",&m);
putw(m,fptr);
fptr =fopen("Input.txt","r"); }
c = getc(fptr); fclose(fptr);
while(!feof(fptr))
{ fptr=fopen("file1.txt","r");
printf("%c", c); for(i=0;i<5;i++)
c = getc(fptr); {
} n=getw(fptr);
fclose(fptr ); sum=sum+n;
return 0; }
printf("\nThe average is %d", sum/5);
}
Sample I/O: fclose(fptr);
Input : C Programming return 0;
Output : C Programming }
Sample I/O:
Input : 10 20 30 40 50
Output : The average is : 30

Example : fprintf() and fscanf() Example:fread() and fwrite()


Print the formatted content to the file and read the Write the structure content to binary file and read
same from the file the content from the binary file
#include<stdio.h> #include <stdio.h>
int main() #include <stdlib.h>
{
char name[30]; struct student
int i,rno; {
FILE *fptr; int rno;
fptr = fopen("one.txt", "w"); char name[30];
for(i=0;i<3;i++) };
{
scanf("%d %s", &rno,name); int main()
fprintf(fptr,"%d %s", rno,name); {
} int i;
fclose(fptr); struct student st,stp;
FILE *fptr;
fptr = fopen("one.txt", "r"); fptr = fopen("bdata.bin","wb");
for(i=0;i<3;i++) for(i = 0; i < 2; i++)
{ {
fscanf(fptr,"%d %s",&rno, name); scanf("%d %s",&st.rno,st.name);
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 47
printf("\n%s %d", rno, name); fwrite(&st, sizeof(struct student), 1, fptr);
} }
fclose(fptr); fclose(fptr);
return 0;
} fptr = fopen("bdata.bin","rb");
for(i = 0; i < 2; i++)
Sample I/O: {
Input : 1 arun fread(&st, sizeof(struct student), 1, fptr);
2 ashok printf("\n%d %s",st.rno,st.name);
3 bala }
Output :1 arun fclose(fptr);
2 ashok return 0;
3 bala }
Sample I/O:
Input : 1 arun
2 ashok
Output :1 arun
2 ashok

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 48
Example: Random Access File Example: Random Access File
Get 5 student data and print particular student Random Access
data Get 5 student record,
Update a particular student record,
Then print all the 5 records
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>

struct student struct student


{ {
int rno; int rno;
char name[30]; char name[30];
}; };

int main() int main()


{ {
int i; int i;
struct student st,stp; struct student st,stp;
FILE *fptr; FILE *fptr;
fptr = fopen("bdata.bin","wb"); fptr = fopen("bdata.bin","wb+");
for(i = 0; i < 5; i++) for(i = 0; i < 5; i++)
{ {
scanf("%d %s",&st.rno,st.name); scanf("%d %s",&st.rno,st.name);
fwrite(&st, sizeof(struct student), 1, fptr); fwrite(&st, sizeof(struct student), 1, fptr);
} }
fclose(fptr); rewind(fptr);
printf("Before updation");
fptr = fopen("bdata.bin","rb"); for(i = 0; i < 5; i++)
scanf("%d",&i); {
fseek(fptr,sizeof(struct student)*(i-1),0); fread(&st, sizeof(struct student), 1, fptr);
fread(&st, sizeof(struct student), 1, fptr); printf("\n%d %s",st.rno,st.name);
printf("\n%d %s",st.rno,st.name); }
fclose(fptr); scanf("%d",&i);
return 0; scanf("%d %s",&st.rno,st.name);
} fseek(fptr,sizeof(struct student)*(i-1),0);
fwrite(&st, sizeof(struct student), 1, fptr);
rewind(fptr);
printf("\nAfter updation");
for(i = 0; i < 5; i++)
{
fread(&st, sizeof(struct student), 1, fptr);
printf("\n%d %s",st.rno,st.name);
}

fclose(fptr);
return 0;
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 49
Command line arguments in C/C++

The most important function of C is main() function. It is mostly defined with a return type of int
and without parameters :
int main() { /* ... */ }
We can also give command-line arguments in C. Command-line arguments are given after the
name of the program in command-line.
To pass command line arguments, we typically define main() with two arguments : first argument
is the number of command line arguments and second is list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
argc (ARGument Count) is int and stores number of command-line arguments passed by the
user including the name of the program.
The value of argc should be non negative.
argv(ARGument Vector) is array of character pointers listing all the arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers
to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line
arguments.

// Name of program add.c


#include <stdio.h>

int main(int argc, char** argv)


{
int c;
c=atoi(argv[1])+atoi(argv[2]);
printf(“the sum of two numbers%d”,c);
return 0;
}
How to run the program:

From command line,

C:\tc\bin\add 10 20

The sum of two numbers 30

Properties of Command Line Arguments:


1. They are passed to main() function.
2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control program from outside instead of hard coding those values inside the
code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[n] points last argument.

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 50
To write a C Program to add, delete ,display ,Search and exit options for telephone details of
an individual into a telephone directory using random access file.

ALGORITHM:
1. Start.
2. Declare variables, File pointer and phonebook structures.
3. Create menu options.
4. Read the option .
5. Develop procedures for each option.
6. Call the procedure (Add, delete ,display ,Search and exit)for user chosen option.
7. Display the message for operations performed.
8. Stop

#include <stdio.h>
#include <conio.h>
#include <string.h>
struct person
{
char name[20];
long telno;
};
void appendData()
{
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","ab");
printf("*****Add Record****\n");
printf("Enter Name : ");
scanf("%s",obj.name);
printf("Enter Telephone No. : ");
scanf("%ld",&obj.telno);
fwrite(&obj,sizeof(struct person),1,fp);
fclose(fp);
}
void showAllData(){
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","rb");
printf("*****Display All Records*****\n");
printf("\n\n\t\tName\t\t\tTelephone No.");
printf("\n\t\t=====\t\t\t==========\n\n");
while(!feof(fp))
{
fread(&obj,sizeof(struct person),1,fp);
if(!feof(fp))
printf("%s %ld\n",obj.name,obj.telno);
}
fclose(fp);
getch();
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 51
void findData()
{
FILE *fp;
struct person obj;
char name[20];
int totrec=0;
clrscr();
fp=fopen("data.txt","rb");
printf("*****Display SpecificRecords*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))
{
fread(&obj,sizeof(struct person),1,fp);
if(strcmpi(obj.name,name)==0){
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
}
}
fclose(fp);
getch();
}

void update()
{
FILE *fp;
struct person obj;
char name[20];
int i=-1;
clrscr();
fp=fopen("data.txt","rb+");
printf("*****Display SpecificRecords*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))
{ i++;
fread(&obj,sizeof(struct person),1,fp);
if(strcmpi(obj.name,name)==0){
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
break;
}
}
printf("\nEnter new no :");
scanf("%ld",&obj.telno);
fseek(fp,(sizeof(struct person)*i),0);
fwrite(&obj,sizeof(struct person),1,fp);

fclose(fp);
getch();
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 52
void main()
{
char choice;
while(1)
{
clrscr();
printf("*****TELEPHONE DIRECTORY*****\n\n");
printf("1) Append Record\n");
printf("2) Find Record\n");
printf("3) Read all record\n");
printf("4) Update record\n");
printf("5) exit\n");
printf("Enter your choice : ");
fflush(stdin);
choice = getche();
switch(choice)
{
case'1' : //call append record
appendData();
break;
case'2' : //call find record
findData();
break;
case'3' : //Read all record
showAllData();
break;
case'4' : //Read all record
update();
break;
case'5' :
exit(1);
}
}
}

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 53
To write a C Program to Count the number of account holders whose balance is less than
the minimum balance using sequential access file.

ALGORITHM:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define MINBAL 500
struct Bank_Account
{
char no[10];
char name[20];
int balance;
};
struct Bank_Account acc;
void main()
{
long int pos1,pos2,pos;
FILE *fp;
char *ano,*amt;
char choice;
int type,i=-1,flag=0;
int bal;
do
{
clrscr();
fflush(stdin);
printf("1. Add a New Account Holder\n");
printf("2. Display\n");
printf("3. Deposit or Withdraw\n");
printf("4. Number of Account Holder Whose Balance is less than the Minimum Balance\n");
printf("Enter your choice : ");
choice=getchar();
switch(choice)
{
case '1' :
fflush(stdin);
fp=fopen("acc.dat","ab");
printf("\nEnter the Account Number : ");
gets(acc.no);
printf("\nEnter the Account Holder Name : ");
gets(acc.name);
printf("\nEnter the Initial Amount to deposit : ");
scanf("%d",&acc.balance);
fseek(fp,0,2);
fwrite(&acc,sizeof(acc),1,fp);
fclose(fp);
break;

PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 54
case '2' :
fp=fopen("acc.dat","rb");
printf("\nA/c Number\tA/c Holder Name Balance\n");
while(fread(&acc,sizeof(acc),1,fp)==1)
printf("%-10s\t\t%-20s\t%d\n",acc.no,acc.name,acc.balance);
fclose(fp);
break;

case '3' :
fflush(stdin);
fp=fopen("acc.dat","rb+");
printf("\nEnter the Account Number : ");
gets(ano);
i=-1;
while(!feof(fp))
{ i++;
fread(&acc,sizeof(acc),1,fp);
if(strcmp(acc.no,ano)==0)
{
printf("\nEnter the Type 1 for deposit & 2 for withdraw : ");
scanf("%d",&type);
printf("\nYour Current Balance is : %d",acc.balance);
printf("\nEnter the Amount to transact : ");
scanf("%d",&bal);
if(type==1)
acc.balance=acc.balance+bal;
else
acc.balance= acc.balance-bal;
break;
}
}
fseek(fp,sizeof(acc)*(i),0);
fwrite(&acc,sizeof(acc),1,fp);
fclose(fp);
break;
case '4' :
flag=0;
fp=fopen("acc.dat","rb");
while(fread(&acc,sizeof(acc),1,fp)==1)
{
if(acc.balance<MINBAL)
flag++;
}
printf("\nThe Number of Account Holder whose Balance less than the Minimum Balance :
%d",flag);
fclose(fp);
break;
}
printf("\nPress any key to continue....");
getch();
} while (choice<'5');
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 55

You might also like