0% found this document useful (0 votes)
25 views238 pages

All Units With Question

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
0% found this document useful (0 votes)
25 views238 pages

All Units With Question

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/ 238

CS3251 PROGRAMMING IN C 2023

UNIT I BASICS OF C PROGRAMMING


Introduction to programming paradigms – Applications of C Language - Structure of C program
- C programming: Data Types - Constants – Enumeration Constants - Keywords – Operators:
Precedence and Associativity - Expressions - Input/Output statements, Assignment statements –
Decision making statements - Switch statement - Looping statements – Preprocessor directives -
Compilation process.

1.1 INTRODUCTION TO PROGRAMMING PARADIGMS


➢ A programming paradigm is a philosophy, style, or general approach to write code.
➢ Paradigm can also be termed as method to solve some problem or do some task.
➢ Programming paradigm is an approach to solve problem using some programming
language or it is a method to solve a problem using tools and techniques that are available
to us following some approach.
➢ There are lots for programming language that are known but all of them need to follow
some strategy when they are implemented and this methodology/strategy is paradigms.
Apart from varieties of programming language there are lots of paradigms to fulfil each
and every demand. They are

1.1.1. Imperative programming paradigm:


➢ It is one of the oldest programming paradigms.
➢ It is based on Von Neumann architecture.
➢ It works by changing the program state through assignment statements.
➢ It performs step by step task by changing the state. The main focus is on how to achieve
the goal.
➢ The paradigm consists of several statements and after execution of all the result is stored.
Advantage:
❖ Very simple to implement
❖ It contains loops, variables etc.

Department of CSE Page 1


CS3251 PROGRAMMING IN C 2023

Disadvantage:
❖ Complex problem cannot be solved
❖ Less efficient and less productive
❖ Parallel programming is not possible
Examples of Imperative programming paradigm:
❖ C : developed by Dennis Ritchie and Ken Thompson
❖ Fortan : developed by John Backus for IBM
❖ Basic : developed by John G Kemeny and Thomas E Kurtz
Imperative programming is divided into three broad categories:
a) Procedural
b) OOP and
c) parallel processing.
These paradigms are as follows:
A) Procedural programming paradigm
➢ This paradigm emphasizes on procedure in terms of under lying machine model.
➢ There is no difference in between procedural and imperative approach.
➢ It has the ability to reuse the code and it was boon at that time when it was in use because
of its reusability.
Examples of Procedural programming paradigm:
➢ C : developed by Dennis Ritchie and Ken Thompson
➢ C++ : developed by Bjarne Stroustrup
➢ Java : developed by James Gosling at Sun Microsystems
➢ ColdFusion : developed by J J Allaire
➢ Pascal : developed by Niklaus Wirth
B) Object oriented programming
➢ The program is written as a collection of classes and object which are meant for
communication.
➢ The smallest and basic entity is object and all kind of computation is performed on the
objects only. More emphasis is on data rather procedure.
➢ It can handle almost all kind of real life problems which are today in scenario.
Advantages:
❖ Data security
❖ Inheritance
❖ Code reusability
❖ Flexible and abstraction is also present
Examples of Object Oriented programming paradigm:
➢ Simula : first OOP language
➢ Java : developed by James Gosling at Sun Microsystems
➢ C++ : developed by Bjarne Stroustrup
➢ Objective-C : designed by Brad Cox

Department of CSE Page 2


CS3251 PROGRAMMING IN C 2023

➢ Visual Basic .NET : developed by Microsoft


➢ Python : developed by Guido van Rossum
➢ Ruby : developed by Yukihiro Matsumoto
➢ Smalltalk : developed by Alan Kay, Dan Ingalls, Adele Goldberg
C) Parallel processing approach
➢ Parallel processing is the processing of program instructions by dividing them among
multiple processors.
➢ A parallel processing system posses many numbers of processor with the objective of
running a program in less time by dividing them.
➢ This approach seems to be like divide and conquer. Examples are NESL (one of the
oldest one) and C/C++ also supports because of some library function.
1.1.2. Declarative programming paradigm:
➢ It is divided as Logic, Functional, Database.
➢ In computer science the declarative programming is a style of building programs that
expresses logic of computation without talking about its control flow.
➢ It often considers programs as theories of some logic.
➢ It may simplify writing parallel programs.
➢ The focus is on what needs to be done rather how it should be done basically emphasize
on what code code is actually doing.
➢ It just declares the result we want rather how it has be produced.
➢ This is the only difference between imperative (how to do) and declarative (what to do)
programming paradigms. Getting into deeper we would see logic, functional and
database.
A) Logic programming paradigms
➢ It can be termed as abstract model of computation.
➢ It would solve logical problems like puzzles, series etc.
➢ In logic programming we have a knowledge base which we know before and along with
the question and knowledge base which is given to machine, it produces result.
➢ In normal programming languages, such concept of knowledge base is not available but
while using the concept of artificial intelligence, machine learning we have some models
like Perception model which is using the same mechanism.
B) Functional programming paradigms
➢ The functional programming paradigm has its roots in mathematics and it is language
independent.
➢ The key principle of this paradigm is the execution of series of mathematical functions.
The central model for the abstraction is the functions which are meant for some specific
computation and not the data structure.
➢ Data are loosely coupled to functions.The function hide their implementation.
➢ Function can be replaced with their values without changing the meaning of the program.
Some of the languages like perl, javascript mostly uses this paradigm.

Department of CSE Page 3


CS3251 PROGRAMMING IN C 2023

Examples of Functional programming paradigm:


❖ JavaScript : developed by Brendan Eich
❖ Haskell : developed by Lennart Augustsson, Dave Barton
❖ Scala : developed by Martin Odersky
❖ Erlang : developed by Joe Armstrong, Robert Virding
❖ Lisp : developed by John Mccarthy
❖ ML : developed by Robin Milner
❖ Clojure : developed by Rich Hickey
C)Database/Data driven programming approach
➢ This programming methodology is based on data and its movement. Program statements
are defined by data rather than hard-coding a series of steps.
➢ A database program is the heart of a business information system and provides file
creation, data entry, update, query and reporting functions.
➢ There are several programming languages that are developed mostly for database
application. For example SQL.
➢ It is applied to streams of structured data, for filtering, transforming, aggregating (such as
computing statistics), or calling other programs. So it has its own wide application.

1.2 REAL-WORLD APPLICATIONS OF C


Use of the C programming language is not limited to the development of operating
systems and applications. It is also used in GUI development, IDE development, etc
Some uses of C programming language:-
1. Operating Systems
2. Assemblers
3. Text Editors
4. Print Spoolers
5. Modern Programs
6. Databases
7. Utilities
1. Operating Systems:
A high-level programming language built in the C programming language was used to
construct the first operating system, which was UNIX.Windows Kernel, Linux Kernel and
Apple’s OS X kernel are mostly written in C.
2. GUI:
It stands for Graphical User Interface. The C programming language also helps in
developing popular adobe softwares like Photoshop, Premier Pro, Illustrator etc.
3. Embedded Systems:
In daily life, we use different embedded systems like coffee machines, microwaves,
climate control systems etc. These all are mostly programmed in C.
4. Database:

Department of CSE Page 4


CS3251 PROGRAMMING IN C 2023

The C programming language helps in developing the popular database management


system, MySQL.
5. Ease of Computation:
C provides faster computation in programs. The implementation of algorithms and data
structures is swift in C. With the help of C, you can perform high degree calculations such as
MATLAB, Mathematica etc.
6. Gaming:
C programming is relatively faster than Java or Python. It has been used in various
gaming applications and graphics. C programming language also helps in creating many popular
childhood games like Tic-Tac-Toe, The Snake game etc.
7. Development of New languages:-
Due to the fast execution and simplicity, many languages like Java, C++, Python, PHP,
PERL, JavaScript, etc were influenced by the development of C. In Python, C is used for
building standard libraries. The syntax and control structures of PERL, PHP and C++ are based
upon the C programming language.
8. Google:-
In the Google open source community, the projects are being handled by C/C++. And
C/C++ also helped in developing google file system and chromium browser.
9. Assemblers:-
Mainly used to translate Assembly language to Machine language. C also helped in
developing GNU assembler.
10. Text Editors:-
C also helped in creating various text editors like Vim, Gedit etc.
11. Drivers:-
Another application of C is to write driver softwares like Keyboard driver, Network
driver, mouse driver etc.
12. Interpreters:-
With the help of C programming language, you can create language interpreters. C
helped in developing different programming language interpreters like Python and MATLAB
interpreters etc.
13. Network Devices:-
Another application of C is to design network devices.
14. Compiler Design:-
C also helped in designing several popular compilers like Clang C, MINGW, Apple C
etc. This is one of the most popular uses of C language.

1.3 STRUCTURE OF C PROGRAM


C is a middle level, structured, core programming language. Every C program contains a
number of building blocks. These blocks should be written in a correct order and procedure. But
some blocks may be optional.

Department of CSE Page 5


CS3251 PROGRAMMING IN C 2023

In general, a C program is composed of the following sections:


Section 1: Documentation / Comments
Section 2: Pre-processor directives
Section 3: Global declarations
Section 4: Functions
• Section 1, 2 and 3 are optional
• Section 3 is essential.

Documentation / Comment section

Preprocessor section

Global declaration section

Function section

main ( )
{
Declaration part
Executable part
}

Sub program section


{
Body of the subprogram
}

structure of the C program

i) Documentation Section:
Comments are non executable statements. Comments are very helpful in identifying the
program features and underlying logic of the program.
✓ The multi line comment begins with ‘/*’ and end with ‘*/’.
✓ Single line comment statement start with double slash sign ‘//’.
Example:
• /* Matrix Addition Program */
• // Author : Joshna

Department of CSE Page 6


CS3251 PROGRAMMING IN C 2023

ii) Preprocessor Section:


It is used to link system library files, for defining the macros and for defining the
conditional inclusion.
✓ It starts with symbol (#).
✓ There is no termination symbol semicolon.
Example:
• #include <stdio.h>
• #define A 10
• # ifdef
• #endif
iii) Global Declaration Section:
Variables that are declared outside of all the function are called as global variables.
✓ It is accessed by all the functions
✓ It must be placed before the main function.
iv)Function Section:
Function section should contain only one main function and zero or more user defined
function.
Execution starts with the main function.
Every function consists of 2 parts
a) Header of the function
b) Body of the function
a) Header of the function
The general form of the header of the function is
[return_type] function_name([argument_list])
b) Body of the function
The body of the function consists of a set of statements enclosed within curly brackets
commonly known as braces. The statements are of two types.
Local declaration:
Variables that are declared within function are called as Local variables.
Executable statements:
Other statements following the declaration statements are used to perform various
tasks.

Department of CSE Page 7


CS3251 PROGRAMMING IN C 2023

Example
/*Addition of two numbers*/ Documentation Section
#include<stdio.h> Pre-processor directives
#include<conio.h>
#define A 10 Definition Section
int a=10; Global declarations
void main() Main() function
{
int b=20;
int c;
c=a+b; Execution Part
printf(“\n SUM=%d”,c);
getch();
}

1.4 C PROGRAMMING : DATA TYPES


Data type determines the set of values that a data item can take and the operations that
can be performed on the item. In C language data types are classified into
1. Basic Data type (Primitive Data Type)
2. User defined Data type
3. Derived Data type
Data types

Basic data type Derived data type User defined data type
char array typedef
int Structure enumeration
float function
double pointer
void

Fig 1.5 : Classification of Data Types


1.4.1 Basic Data Types:
There are five basic data types:
(i) Character - char
(ii) Integer - int
(iii) Single-Precision floating point - float
(iv) Double Precision floating point - double

Department of CSE Page 8


CS3251 PROGRAMMING IN C 2023

(v) No value available - void


a) Integer Data Type:
Integer type has the following sub categories. They are short int, int and long. Each of the
above may be signed or unsigned.
Data Type Size in Bytes Range of valid values
short int 1 -128 to 127
int 2 -32768 to 32767
Long 4 -231 to 231
Table 1.1: Integer Data Type
Example:
short int k;
int marks;
long qty;

b) Character Data Type:


To store a single character, declare the variables in char data type. Its size is 1 byte.
Example:
char choice;
choice = 'Y';
c) Floating Point type:
The ‘float’ data type represents single precision floating point number. Its size is 4 byte.
It uses 6 digits of precision.
The ‘double’ data type represents double precision floating point number. Its size is 8
byte. It uses 14 digits of precision.
Example :
float avg;
double k;
d) void data type
Void type holds no value. It is used in 3 cases.
1. To specify the return type of a function
2. To specify parameters of a function
3. To create generic pointers
1.4.2 Derived Data Types
a) Array
An array is a collection of similar data items that are stored under a common name.
Example :
int Marks [5] ;
b) Function
A function is a self contained block of program statements that performs a
particular task.

Department of CSE Page 9


CS3251 PROGRAMMING IN C 2023

c) Pointers
The pointer variable holds the memory address of another variable. It provides a
way of accessing a variable.
Example:
int x;
int *ptr = &x;
d) Structure
A structure is a collection of related data elements of different data type under a
single name.
Example:
struct student
{
int reg_no;
char name[20];
};
1.4.3 User defined Data types:
(a) typedef:
It allows the users to define an alternate (or) alias name for an existing data type,
and this can be used to declare variables.
Example:
typedef int Marks;
Marks M1, M2;
(b) Enumerated data type:
The C language provides another user defined data type called enumerated data type.
Syntax
enum identifier{value1, value 2….value );
Example
enum Day { Mon, Tue, Wed, Thu, Fri, Sat, Sun};
enum Day D1, D2;
D1 = Wed;
D2 = Sun;
1.5 CONSTANTS
A constant is an entity whose value can‟t be changed during the execution of a program.
Constants are classified as:
1. Literal constants
2. Qualified constants
3. Symbolic constants
1.5.1 Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating
point number, character or a string.

Department of CSE Page 10


CS3251 PROGRAMMING IN C 2023

Literal constants are of the following types.


a) Integer Literal constant
b) Floating point Literal constant
c) Character Literal constant
d) String Literal constan
a)Integer Literal constant
Integer Literal constants are integer values like -1, 2, 8 etc. The rules for writing integer
literal constant are:
➢ An Integer Literal constant must have at least one digit
➢ It should not have any decimal point
➢ It can be either positive or negative.
➢ No special characters and blank spaces are allowed.
➢ A number without a sign is assumed as positive.
➢ Octal constants start with 0.
➢ Hexadecimal constant start with 0x or 0X
b)Floating point Literal constant
Floating point Literal constants are values like -23.1, 12.8, 4e8 etc.. It can be
written in a fractional form or in an exponential form.
The rules for writing Floating point Literal constants in a fractional form:
• A fractional floating point Literal constant must have at least one digit.
• It should have a decimal point.
• It can be either positive or negative.
• No special characters and blank spaces are allowed.
The rules for writing Floating point Literal constants in an exponential form:
• A Floating point Literal constants in an exponential form has two parts: the
mantissa part and the exponent part. Both are separated by e or E.
• The mantissa part can be either positive or negative. The default sign is positive.
• The mantissa part should have at least one digit.
• The mantissa part can have a decimal point.
• The exponent part should have at least one digit
• The exponent part cannot have a decimal point.
• No special characters and blank spaces are allowed.
c)Character Literal constant
A Character Literal constant can have one or at most two characters enclosed
within single quotes. E.g, „’A’ , ‘a‟ , „ \n „.
It is classified into:
➢ Printable character literal constant
➢ Non-Printable character literal constant.
Printable character literal constant
All characters except quotation mark, backslash and new line characters

Department of CSE Page 11


CS3251 PROGRAMMING IN C 2023

enclosed within single quotes form a Printable character literal constant. Ex:
’A‟ ,’#’
Non-Printable character literal constant.
Non-Printable character literal constants are represented with the help of
escape sequences. An escape sequence consists of a backward slash (i.e. \)
followed by a character and both enclosed within single quotes.

d)String Literal constant


A String Literal constant consist of a sequence of characters enclosed within double
quotes. Each string literal constant is implicitly terminated by a null character.
E.g. “ABC”
1.5.2 Qualified constants
Qualified constants are created by using const qualifier.
E.g. const char a = „A‟
The usage of const qualifier places a lock on the variable after placing the value in it. So
we can‟t change the value of the variable a
1.5.3 Symbolic constants
Symbolic constants are created with the help of the define preprocessor directive.
For ex #define PI= 3.14 defines PI as a symbolic constant with the value 3.14. Each
symbolic constant is replaced by its actual value during the pre-processing stage.

1.6 ENUMERATION CONSTANT


Enumeration constant is the user defined constant based on the standard integer type.
They allow the programmer to name a finite set together with its elements.
Keyword : enum
Syntax
enum identifier{const1, const 2….constn );
Assigning value to enumeration constant
• When no value is assigned to enumeration constant,
Default value of const1 is 0
Default value of const2 is 1

Department of CSE Page 12


CS3251 PROGRAMMING IN C 2023

Example:
enum Day{ Monday, Tuesday, Wednesday, Thursday};
Monday=0
Tuesday=1
Wendesday=2
Thursday=3
Program:
#include <stdio.h>
#include<conio.h>
void main()
{
enum Day{ Monday =1, Tuesday, Wednesday, Thursday};
enum No{ A= 3, B };
printf("Wednesday = %d", Wednesday);
printf("B = %d ", B);
}
Output:
Wednesday=3
B=4

1.7 KEYWORDS
Keywords are reserved words, they have standard and predefined meaning.Keywords
cannot be used as normal identifiers. They must be written in lower case letter. There are 32
keywords available in C. The following table shows the keywords in C.

auto default extern int signed void


break do float long static union
case double for register struct unsigned
const else goto return switch volatile
continue enum if short typedef while
Table 1.2 : Keywords in C
1.8 OPERATORS
Operator is a symbol that performs the operation on one or more operands. C Languge
provides the following operators:
i. Arithmetic operators
ii. Relational operators
iii. Logical operators
iv. Assignment operators
v. Increment and Decrement operators
vi. Conditional operators

Department of CSE Page 13


CS3251 PROGRAMMING IN C 2023

vii. Bitwise operators


viii. Special operators
i) Arithmetic Operators:
Arithmetic operations like addition, subtraction, multiplication, division etc can be
performed by using arithmetic operators.
Operator Name Example
+ Addition 12 + 4
- Subtraction a–b
* Multiplication 2*9
/ Division a/3
% Remainder 13 % 3
(Modulo Division)
Table 1.3 : Arithmetic Operators
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a =15;
int b=10;
int add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul=a*b;
div= a/b;
mod= a%b;
printf( “addition=%d”,add);
prtintf(“subtraction=%d”,sub);
printf”multiplication=%d”,mul);
printf(“division=%d”,div);
printf(“modulo=%d”,mod);
getch();
}
Output:
Addition= 25
Subtraction=5
Multiplication=150
Division=1
Modulo=5

Department of CSE Page 14


CS3251 PROGRAMMING IN C 2023

ii) Relational Operators:


✓ Relational operators are used to compare two or more operands.
✓ We use relational expression in if, for and while statements.
✓ Relational expressions return either True (1) or False (0).
Operator Meaning
< is lesser than
<= is lesser than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Table 1.4: Relational Operators
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a =15;
int b=10;
printf( “a<b:%d”,a<b);
prtintf(“a<=b:%d”,a<=b);
printf”a>b:%d”,a>b);
printf(“a>=b:%d”,a>=b);
printf(“a==b:%d”,a==b);
printf(“a!=b:%d”,a!=b);
getch();
}
Output
a<b: 0
a<=b:0
a>b:1
a>=b:1
a==b:0
a!=b:1
iii) Logical Operators:
Logical operators are used to combine the results of two or more relational expressions.
Operator Meaning
Logical NOT
!
Logical AND
&&
Logical OR
||
Table 1.5: Logical Operators
Department of CSE Page 15
CS3251 PROGRAMMING IN C 2023

✓ Logical NOT is a unary operator that negates the logical value of its single operand.
✓ Logical NOT convert a 1 to 0, and 0 to 1.
✓ Logical AND produces 1 if both operands are 1, otherwise produce 0.
✓ Logical OR produces 0 if both operands are 0, otherwise it produces 1.
iv) Assignment Operator:
Assignment operator ‘=’ is used to assign a constant or a value of an expression or a
value of a variable to other variable.
Syntax
Variable = expression (or) value
Operators Example Explanation

Simple assignment operator = sum=10 10 is assigned to variable sum

+= sum+=10 sum=sum+10
-= sum-=10 sum = sum-10
Compound assignment *= sum*=10 sum = sum*10
operators /+ sum/=10 sum = sum/10
%= sum%=10 sum = sum%10
&= sum&=10 sum = sum&10
Table 1.6: Assignment Operator
v) Increment and Decrement Operators (unary):
• increment (++) - Adds one to the variables
• decrement (--) - Subtract one from the variable

Operator Meaning
++ x Pre increment
(Increment then display)
-- x Pre decrement
(decrement then display)
x ++ Post increment
(display then increment)
x -- Post decrement
(display then decrement)
Table 1.7: Increment and Decrement Operators
Example:
a=10;
++a =11
a++ =10
--a =9
a-- =10

Department of CSE Page 16


CS3251 PROGRAMMING IN C 2023

vi) Conditional Operator (or) Ternary Operator:


?: is known as conditional operator. It is equivalent to simple if then else statement. It
checks the condition and executes the exp1 if condition is true otherwise it execute exp2.
Syntax
condition ? exp1 : exp 2;
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5
int b = 3
int max;
max = a > b ? a : b ;
printf(“Maximum is %d”, max);
getch();
}
Output:
Maximum is 5
In this example, it checks the condition ‘a > b’, if it is true, then the value of ‘a’ is
assigned to ‘max’, otherwise the value of ‘b’ is assigned to ‘max’.
vii) Bitwise Operators:
✓ Bitwise operators are used to calculate the data at bit level.
✓ It operates on integers only.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
Bitwise NOT (or) One’s
~
complement

Table 1.8: Bitwise Operators


Bitwise AND ( & )
This operator compare the operands in corresponding bits position and produces 1 if both
operand bits are 1, otherwise produces 0.

Bitwise OR ( | )

Department of CSE Page 17


CS3251 PROGRAMMING IN C 2023

This operator compare the operands in corresponding bits position and produces 0 if both
operand bits are 0, otherwise produces 1.
Bitwise XOR (^ )
This operator compare the operands in corresponding bits position and produces 1 if both
operand bits are same, otherwise produces 0.
viii) Special Operators: (Miscellanous Operator)
C language supports some of the special operators.
Operators Meaning

, Comma operator

size of Size of operator

& and * Pointer operators

. and → Member selection operators Table


1.9: Special
Operators
Comma Operator: It is used to separate elements.
Example :
int X, Y;
sizeof Operator: It is used to return the size of the data type or variable.
Example :
sizeof(Y);
Member Selection Operators: It is used to refer structure or union member element.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int Y;
printf (“Size of Y is %d”, sizeof(Y));
getch();
}
Output:
Size of Y is 2
1.9 OPERATORS: PRECEDENCE AND ASSOCIATIVITY
An operator is a special symbol that is used to perform particular mathematical or logical
computations like addition, multiplication, comparison and so on. The value of operator is
applied to be called operands.
Precedence and Associativity are two characteristics of operators that determine the
evaluation order of subexpressions in absence of brackets.
Precedence of operators
The precedence rule is used to determine the order of application of operators in
evaluating sub expressions. The operator with the highest precedence is operated first.
Parenthesis operator has the highest priority.

Department of CSE Page 18


CS3251 PROGRAMMING IN C 2023

Associativity of operators
The associativity rule is applied when two or more operators are having same precedence
in the sub expression.
• An operator can be left-to-right associative or right-to-left associative.
• All operators with same precedence have same associativity

Table 1.10: Precedence and associativity

Department of CSE Page 19


CS3251 PROGRAMMING IN C 2023

Arithmetic Operator Precedance


Arithmetic evaluation is carried out using two phases from left to right.
• During the first phase, highest priority operators are evaluated.
• In the second phase, lowest priority operators are evaluated.
Precedance Operator
High * /%

Low +-

Table 1.11: Arithmetic Operator Precedance


Example:
Result= 6+4/ 2.
Phase1: (4/2 operation is evaluated first)
Result= 6+2
Phase2: (6+2 operation is evaluated next)
Result= 8
Program
#include<stdio.h>
#include<conio.h>
void main()
{
Result= 6+4/ 2;
printf(“Result=%d”,Result);
getch();
}
Output
Result= 8

1.10 EXPRESSIONS
An expression is a sequence of operators and operands that specifies the computation. An
operand can be a variable, constant or a function call. An operator is a symbol that is used to
write a mathematical, logical or relational expression.
Simple Expression
An expression that has only one operator is known as simple expression.
Example:
X=a+b;
X=++a;
Compound Expression
An expression that has more than one operator is known as compound expression.

Department of CSE Page 20


CS3251 PROGRAMMING IN C 2023

Example:
X=a+b*c/f;
Arithmetic Expression
An expression consisting of arithmetic operators is known as arithmetic expression.
Example:
X=a+b;
Logical Expression
An expression consisting of logical operators is known as Logical expression.
Example:
X=a>b;
Program
#include<stdio.h>
#include<conio.h>
void main()
{
Result= 6+4/ 2;
printf(“Result=%d”,Result);
getch();
}
Output
Result= 8

1.11 INPUT AND OUTPUT STATEMENTS


In ‘C’ language, there are two types of input and output statements. They are:
• Unformatted I/O statements
• Formatted I/O statements
Unformatted Input / Output Statements
In unformatted I/O statements, no need to specify the type & size of the data. It arranges
the data in any format.
(a) getchar()
The getchar( ) is an input function that reads a single character from the standard input
device ( keyboard ).
Syntax:
char variable;
variable = getchar ( );
Example:
char ch;
ch = getchar ( );
b) putchar()
The putchar( ) is an output function that writes a single character on the standard output
device ( monitor ).

Department of CSE Page 21


CS3251 PROGRAMMING IN C 2023

Syntax
putchar (variable);
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
char ch;
printf (“Enter any one character : ”);
ch = getchar ( );
printf (“The character you typed is ”);
putchar(ch);
}
Output :
Enter any one character : S
The character you typed is S
c) gets()
This function is used to accept a string from standard input device until ENTER key is
pressed.
Syntax
String_variable = gets();
d) puts()
This function is used to display a string to the standard output device.
Syntax
puts (String_variable)
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
char name[20];
printf (“Enter your name : ”);
name = gets( );
printf (“Your name is : ”);
puts(name);
}
Output :
Enter your name : Anand
Your name is : Anand

Department of CSE Page 22


CS3251 PROGRAMMING IN C 2023

e) getc()
The getc ( ) is an input function that reads a single character from the standard input
device ( keyboard ).
Syntax:
char variable;
variable = getc ( );
Example:
char ch;
ch = getchar ( );
f) putc()
The putc( ) is an output function that writes a single character on the standard output
device ( monitor ).
Syntax
putc(variable);
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
char ch;
printf (“Enter any one character : ”);
ch = getc( );
printf (“The character you typed is ”);
putc(ch);
}
Output :
Enter any one character : S
The character you typed is S
Formatted I/O Statements
In unformatted I/O statements, we need to specify the type & size of the data. It arranges
the data in particular format.
(a) scanf ()
Input data can be read from standard input device (keyboard) using scanf ( ) function.
Syntax
scanf (“Control String”, &var1, &var2, . . .);
Example
scanf (“%d %d”, &a, &b);
Control String:
Control string specifies the type of data to be read and its size. The following list
represents the possible control strings.

Department of CSE Page 23


CS3251 PROGRAMMING IN C 2023

%c - To read single character


%s - To read a string
%d - To read an integer
%f - To read a floating point number
Rules for scanf()
▪ Each variable name must be preceded by symbol (&).
▪ The control string and variables data type should match each other.
(b) printf ( )
Output data can be displayed in the standard output device (monitor) using printf( )
function.
Syntax
printf (“Control String”, var1, var2, . . .);
Example
printf (“%d %d”, a, b);
printf (“Factorial = %d”, fact);
Rules for printf()
▪ The control string and variables data type should match each other.
▪ The variable must be separated by commas and need not be preceded with ‘&’ symbol.
Program:
# include<stdio.h>
#include<conio.h>
void main ( )
{
int A, B, C;
printf (“Enter values for A and B : ”);
scanf (“%d %d”, &A, &B);
C = A + B;
printf(“Sum is %d”, C);
getch();
}

Output:
Enter values of A and B : 4 3
Sum is 7
(c) fscanf
This function is used in file processing to read data from a file.
(d) fprintf
This function is used in file processing to write data into a file.
The fscanf() & fprintf() are similar to scanf and printf except that they are used in file
processing.

Department of CSE Page 24


CS3251 PROGRAMMING IN C 2023

1.12 ASSIGNMENT STATEMENTS


Assignment statements assigns right of = symbol to left of = symbol. It assigns the value
to the variable.
Assignment operator symbol: =
In C language, there are five assignment operators. They are,
1. Simple Assignment Statements
2. Simultaneous Assignment Statements
3. Multiple Assignment Statements
4. Arithmetic Assignment Statements
5. Self replacement Assignment Statements
1.Simple Assignment Statements
It is used to assign one value to one variable.
Syntax:
Variable= value;
Example:
A=10;
2.Simultaneous Assignment Statements
It is used for multiple assignments simultaneously.
Syntax:
variable1= value1, variable2= value2,…… variablen= valuen;
Example:
A=10, B=5,C=7;
3.Multiple Assignment Statements
It is used to assign same value to multiple variables.
Syntax:
variable1, variable2 ,…… variablen= value;
Example:
A, B ,C=7;
4.Arithmetic Assignment Statements
It is used to assign a constant or a value of an expression or a value of a variable to other
variable.
Operators Example Explanation
-= sum-=10 sum = sum-10
*= sum*=10 sum = sum*10
/+ sum/=10 sum = sum/10
%= sum%=10 sum = sum%10
&= sum&=10 sum = sum&10
Table 1.12: Arithmetic Assignment Statements

Department of CSE Page 25


CS3251 PROGRAMMING IN C 2023

1.13 DECISION MAKING STATEMENTS


The order in which the program statements are executed is known as flow of control.
Decision making statements alters the default flow of control. There are 2 types of decision
making statements. They are,
✓ Conditional Branching Statements
✓ Unconditional Branching Statements
1.12.1 Conditional Branching Statements
In conditional branching, program control is transferred from one point to another based
upon the outcome of the condition. The conditional branching statements are:
a) if Statement
b) if-else Statement
c) Nested if Statement
d) if else if else statement
e) switch Statement
a) Simple if Statement
It check the given condition in if statement. If it is true then it will execute the body of if
statement, otherwise it skipped the body of if statement.
Syntax:
if (condition)
{
Statement block
}
Flow Chart:

False
conditi
on

True

statements

Program : Program To Check Whether The Number Is Positive


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

Department of CSE Page 26


CS3251 PROGRAMMING IN C 2023

void main ( )
{
int a;
printf (“\n Enter a number : ”);
scanf (“%d”, &a);
if ( a > 0)
printf (“The given number is positive number”);
getch();
}
Output
Enter a number :7
The given number is positive number
b) if - else Statement
It is a two way branching statement. If the condition is true then the True part statement
will be executed.If the condition is false then the False part statement will be executed.
Flowchart:

True False
if
conditi

True statements False statements

Syntax:
if ( condition)
{
True part Statement
}
else
{
False part Statement
}
Program: Check Whether the Number Is Odd Or Even
# include<stdio.h>

Department of CSE Page 27


CS3251 PROGRAMMING IN C 2023

#include<conio.h>
void main ( )
{
int n, r;
printf (“\n Enter a Number:”);
scanf (“%d”, &n);
r = n % 2;
if ( r == 0 )
printf (“Given Number is Even”);
else
printf (“Given Number is Odd”);
getch();
}
Output:
Enter a Number: 6
Given Number is Even
c) Nested if Statement
The if statement within another if statement is called as nested if statement.
Syntax:
if ( condition1 )
{
if ( condition2)
{
Inner if True part Statement
}
else
{
Inner if False part Statement
}
}
else
{
Outer if False part Statement
}
It checks the condition1 and if it is true it check the inner if condition2. This type of
nested if is useful when a series of decisions are involved.
Program :
# include<stdio.h>
#include<conio.h>
void main ( )

Department of CSE Page 28


CS3251 PROGRAMMING IN C 2023

{
int Mark;
printf (“Give your Mark”);
scanf (“%d”, &Mark);
if ( Mark < 50 )
printf(“Failed”);
else
{
if ( Mark < 60 )
printf(“Second Class”);
else
printf (“First Class”);
}
getch();
}
Output
Give your mark : 68
First class
d) if-else if- else statement
If the else part of if statement contain another if statement, then the else and the if
statement can be combined. It is called else if ladder.
Syntax :

if ( condition1 )

Statement block 1

else if ( condition2)

Statement block 2

else if ( condition3 )

Statement block 3

else

Statement block 4

If the condition1 evaluated is true, the statement block1 is executed. If the condition2 is true,
then statement block2 is executed and so on. If none of the conditions are true, then the statement
block4 is executed.

Department of CSE Page 29


CS3251 PROGRAMMING IN C 2023

Flowchart:

False
Conditio
n

True
True
False
Statement 1 Conditio
n

True False
Statement 2 Conditio
n

Statement 3 Default statement

Program : Find Largest Among Three Numbers


# include<stdio.h>
#include<conio.h>
void main ( )
{
int a, b, c;
printf (“Enter three numbers : ”);
scanf (“%d %d %d”, &a, &b, &c);
if (a > b) && (a > c)
printf(“Biggest Number is %d”, a);

Department of CSE Page 30


CS3251 PROGRAMMING IN C 2023

else if (b > c)
printf(“Biggest Number is %d”, b);
else
printf (“Biggest Number is %d”, c);
getch();
}
Output :
Enter three numbers : 40 -50 35
Biggest Number is 40
e) switch Statement
It is a multi way branching statement. It first evaluates the expression in switch statement.
That result is compared with each case value one by one. Whenever a match found, it execute the
statements given in the corresponding case statement.If none of the case value matches with the
result it executes the default section.

Switch( Expression)

Value
1?
Statement Block 1

Value
2?

Statement Block 2


..
Value
N?
Statement Block N

Statement Block D

Department of CSE Page 31


CS3251 PROGRAMMING IN C 2023

Syntax:
switch (Expression)
{
case value 1:
Statement block 1
break;
case value 2:
Statement block 2
break;
...
case value n:
Statement block n
break;
default:
Default Statement block }
Rules for Writing Switch Statement
✓ The expression used in switch statement must be an integer or a character data.
✓ The case labels must be character or integer constant.
✓ Each case block must be terminated by break statement. Otherwise, all statements
that are followed by matched cases are executed.
✓ The default clause is optional & usually placed at the end.
✓ The case keyword must terminate with colon ( : )
✓ No two case constants are identical.
Program : Perform Arithmetic Operation Using Switch statement
# include<stdio.h>
#include<conio.h>
void main ( )
{
float value1, value2;
char operator;
printf (“Type your expression : ”);
scanf (“%f %c %f”, &value1, &operator, &value2);
switch(operator)
{
case ‘+’ :
printf (“%f”, value1 + value2);
break;
case ‘-’ :
printf (“%f”, value1 - value2);
break;

Department of CSE Page 32


CS3251 PROGRAMMING IN C 2023

case ‘*’ :
printf (“%f”, value1 * value2);
break;
case ‘/’ :
printf (“%f”, value1 / value2);
break;
default :
printf (“unknown operator”);
}
getch();
}
Output
Type your expression: 10 + 5
15
1.12.2 Unconditional Branching Statement
In an unconditional branching, program control is transfer from one point to another
without checking the condition. Following are the unconditional branching statements.
i) goto
ii) break
iii) continue
iv) return
i) goto Statement
✓ ‘C’ provides the goto statement to transfer control unconditionally from one place to
another place in the program.
✓ The goto statement can move the program control almost anywhere in the program.
✓ The goto statement requires a label.
Syntax:
goto label; label:
………. ……..
………. ……..
label: goto label;

Program : Check Whether the Given Number is Prime or Not Using goto & return.
# include<stdio.h>
# include<conio.h>
void main ( )
{
int No, i;
printf (“Give the number : ”);
scanf (“%d” , &No);

Department of CSE Page 33


CS3251 PROGRAMMING IN C 2023

for ( i = 2 ; i <= No / 2; i++ )


{
if ( No / i == 0 )
goto stop;
}
printf (“ Given Number is a Prime Number”);
return;
stop : printf (“ Given Number is not a Prime Number”);
}
Output:
Give the number : 17
Given Number is a Prime Number
ii) break Statement
✓ It is used within a looping statement or switch statement.
✓ The break statement is used to terminate the loop.
✓ In switch statement each case block must be terminated with break statement to exit
from switch.
Syntax:
break;
Example:
Refer switch example program.
iii) continue Statement
✓ It is used within looping statements.
✓ When the continue statement is used inside the loop, it skip the statements which are
available after this statement in the loop and go for the next iteration.
Syntax:
continue;
Program : Display 1 To 10 Except 5
# include<stdio.h>
#include<conio.h>
void main ( )
{
int i;
for (i =1; i <= 10; i++ )
{
if ( i == 5 )
continue;
printf (“ %d ”, i);
getch();
}

Department of CSE Page 34


CS3251 PROGRAMMING IN C 2023

Output:
1 2 3 4 6 7 8 9 10

break continue

Break statement takes the control to the Continue statement takes the control to
outside of the loop the beginning of the loop.

It is used in loop & switch statements This can be used only in loop statements

Table 1.13: Difference Between break and continue Statements


(d) return Statement
A return statement terminates the execution of a function and returns the control to the
calling function.
The general form of a return statement is
return;
OR
return expression;
OR
return(expression);

1.14 LOOPING STATEMENTS


✓ The loop is defined as the block of statements which are repeatedly executed for a
specified number of times or until a particular condition is satisfied.
✓ If there is a single statement in the loop, the blocking braces is not necessary. If more
than one statement in the loop then the loop statements must be placed within braces.
The following are the loop statements in ‘C’.
a) for
b) while
c) do – while
a) for Loop
We use for loop when we know exactly how many times the loop statements are
repeated.
Syntax:
for ( initialization; condition; incrementing / decrementing)
{
Statements
}
Initialization:
It has the initial value for the counter variable. In a for loop, initialization is
executed first. It is executed only once i.e., for the first iteration only.

Department of CSE Page 35


CS3251 PROGRAMMING IN C 2023

Condition:
The condition represents a test expression.
Incrementing / decrementing:
After completing every iteration, the counter variable must be increased or
decreased. Otherwise it may leads to an infinite loop.

Flowchart

False
Conditio
n

Body of for
statements

Exit from loop


Program: Print the Sum of the Series 1 + 2 + 3 + 4 . . . up to N terms
#include<stdio.h>
#include<conio.h>
void main ( )
{
int i, sum = 0, n;
printf (“Enter the number of terms”);
scanf (“%d”, &n);
for (i = 1; i <= n; i++ )
sum = sum+ i;
printf (“ Sum = %d”, sum);
getch();
}
Output
Enter the number of terms 5
Sum=15

Department of CSE Page 36


CS3251 PROGRAMMING IN C 2023

b) while Loop
while loop is a pre testing loop. The conditional expression is tested before the body
is executed. If the condition is true the loop will be repeated otherwise stop the
iteration. If the very first time itself the condition failed the loop will not be executed
at least one time.
Syntax:
while (condition)
{
Body of the loop
}
Flowchart:

Conditio
n

Body of while
statements

exit from loop

Program: Print the Sum of the Series 1 + 2 + 3 + 4 . . . up to N terms


#include<stdio.h>
#include<conio.h>
void main ( )
{
int i, sum = 0, n;
printf (“Enter the number of terms”);
scanf (“%d”, &n);
i=1;
while( i <= n)

Department of CSE Page 37


CS3251 PROGRAMMING IN C 2023

{
sum = sum+ i;
i++;
}
printf (“ Sum = %d”, sum);
getch();
}
Output
Enter the number of terms 5
Sum=15
c) do…while Loop
It is an exit checking loop. In do...while loop the test condition is given at the end of the
loop. Therefore the body of the loop will be executed at least once. If the test condition is
true, then repeat the body of the loop otherwise exit from loop.
Syntax:
do
{
Body of loop statements
} while (test expression);

Flowchart:

Body of Loop

Conditio
n

Statement Below Loop

Program: Print the Sum of the Series 1 + 2 + 3 + 4 . . . up to N terms


#include<stdio.h>
#include<conio.h>
void main ( )
{

Department of CSE Page 38


CS3251 PROGRAMMING IN C 2023

int i, sum = 0, n;
printf (“Enter the number of terms”);
scanf (“%d”, &n);
i=1;
do
{
sum = sum+ i;
i++;
} while( i <= n);
printf (“ Sum = %d”, sum);
getch();
}

Output
Enter the number of terms 5
Sum=15
Difference Between while and do . . . while
while do….while
Condition is tested at the beginning of Condition is tested at the end of the
the loop loop
Some time the loop will not be Loop will be executed at least once
executed at least once. even though the condition is false.
Table 1.14: Difference Between while and do . . . while
1.15 PRE-PROCESSOR DIRECTIVES
It is used to link system library files, for defining the macros and for defining the
conditional inclusion. It starts with symbol (#). There is no termination symbol semicolon. The
preprocessor directives can appear anywhere in a program but are generally placed at the
beginning of a program before the function main.
Example:
• #include <stdio.h>
• #define A 10
• # ifdef
• #endif
a) #include Preprocessor Directive
It inserts a particular header from another file. For example, if we include a #include
<stdio.h> directive, it replaces the directive with the contents of the stdio.h header file. It has
two forms
• #include <filename>
– For standard library header files
– Searches predesignated directories

Department of CSE Page 39


CS3251 PROGRAMMING IN C 2023

• #include "filename"
– Searches in current directory
– Normally used for programmer-defined files

b) #define Preprocessor Directive: symbols


The #define directive creates symbolic constants (constants represented as symbols)
Syntax
#define identifier replacement-text
Example
#define PI 3.14159
It replaces all subsequent occurrences of the symbolic constant PI with the numeric
constant 3.14159.
c) #define Preprocessor Directive: Macros
A macro is an identifier defined in a #define pre-processor directive.
Example
#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
area = CIRCLE_AREA( 4 );
becomes
area = ( 3.14159 * ( 4 ) * ( 4 ) );
• Multiple arguments
#define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) )
rectArea = RECTANGLE_AREA( a + 4, b + 7 );
becomes
rectArea = ( ( a + 4 ) * ( b + 7 ) );
d) #undef preprocessor Directive
Symbolic constants and macros can be discarded by using the #undef preprocessor directive.
• Directive #undef “undefines” a symbolic constant or macro name.
• Once undefined, a name can be redefined with #define.
e) #if, #else, #elif(conditionals) preprocessor Directive
The #if command checks whether a controlling conditional expression evaluates to zero
or nonzero.
Example
#if 1
/* This block will be included */
#endif
#if 0
/* This block will not be included */
#endif
f) #endif preprocessor Directive
The #endif command ends a block started by #if, #ifdef, or #ifndef.

Department of CSE Page 40


CS3251 PROGRAMMING IN C 2023

#if /* some expression */


:
#elif /* another expression */
:
/* imagine many more #elifs here ... */
:
#else
/* The optional #else block is selected if none of the previous #if or
#elif blocks are selected */
:
#endif /* The end of the #if block */
g) #ifdef,#ifndef preprocessor Directive
• The #ifdef command is similar to #if, code block is selected if a macro name is
defined.
#ifdef NAME
is equivalent to
#if defined NAME
• The #ifndef command is similar to #ifdef, except that the test is reversed:
#ifndef NAME
is equivalent to
#if !defined NAME
h) #pragma preprocessor Directive
The pragma (pragmatic information) directive issues special commands to the compiler,
using a standardized method.. The #pragma directive provides a way to request special behavior
from the compiler. Pragmas are used within the source program.
#pragma token(s)
i) #line preprocessor Directive
This preprocessor directive is used to set the file name and the line number of the line
following the directive to new values.
#line 100
starts line numbering from 100 beginning with the next source code line.
j) #error Preprocessor Directives
It prints error message on stderr.
Syntax:
#error tokens
It prints an implementation-dependent message including the tokens specified in the
directive.The tokens are sequences of characters separated by spaces.
Example,
 #error 1 - Out of range error
It contains 6 tokens.

Department of CSE Page 41


CS3251 PROGRAMMING IN C 2023

1.16 COMPILATION PROCESS


Compilation is the process of converting the high level language program into machine
understandable form (Machine language). If the compiler found any syntax errors, the compiler
list down the error list. These errors should be corrected and recompiled.
In Windows, we use turbo editor to type the C program in the computer. In Linux we use
vi editor to type the C program in the computer. Then save it in hard disk by giving a file name
with an extension ‘.c’. For example, matrix.c
It includes,
• Pre processor
• Compilation
• Assembly
• Linking
Compiling the program:
After type the C program using standard ‘C’ editor we have to compile the program.
Compilation is the process of converting the high level language program into machine
understandable form (Machine language).

Fig. 1.8: Compilation Process


Linking the program with system library:
‘C’ program is the collection of predefined functions. These functions are already written
and stored in some standard ‘C’ header files. These are part of C compiler. Therefore before
executing a ‘C’ program, we need to link with system libraries.
Executing the program:
This is the process of running and testing the program with sample data.

Department of CSE Page 42


CS3251 PROGRAMMING IN C 2023

A Simple C Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
printf(“Hello”);
}
Output
Hello
Every C program must contain a function called main. All C program starts execution
from main function. Every program may have zero or more user defined function.

PART A (2 Marks with Answers)


1. What is external storage class? (APRIL/MAY 2018)
It is the external storage class for all global variables. It is declared out of the main
function.
Keyword: extern
Scope: Global i.e everywhere in the program.
Default initial value: 0(zero).
Lifetime: Till the program doesn't finish its execution, we can access global variables.
Syntax: extern datatype var1,var2,…..,varn;
2. How does the preprocessor work? (APRIL/MAY 2018)
It is used to link system library files, for defining the macros and for defining the
conditional inclusion. It starts with symbol (#). There is no termination symbol semicolon. The
preprocessor directives can appear anywhere in a program but are generally placed at the
beginning of a program before the function main.
Example:
• #include <stdio.h>
• #define A 10
3. Distinguish between character and string.
character String.
It is a single character. It is a sequence of characters.
It is enclosed by single quotes. It is enclosed by double quotes.

Example : ‘C’ Example : “Computer”

Syntax: char c; Syntax: char c[10];


4. Define programming paradigm.
Program is a set of instructions required for processing. Paradigm means pattern or model.
Programming paradigm refers to how program is written in order to solve the problem. They are

Department of CSE Page 43


CS3251 PROGRAMMING IN C 2023

procedural, functional, object-oriented, logic programming. Some of the programming languages


are
• Fortran
• Cobol
• Basic
• Pascal
• C
5. What are keywords? Give an example
Keywords are reserved words, they have standard and predefined meaning. Keywords
cannot be used as normal identifiers. They must be written in lower case letter. There are 32
keywords available in C.
Example : auto, break, char, continue, else, if, switch, struct, union.
6. What do you mean by variables in ‘C’ ?
A variable is an identifier that is used to represent some specified type of information.
Syntax: datatype variablename;
Example : int marks;
7. Identify the use of ternary or conditional operator.
?: is known as conditional operator. It is equivalent to simple if then else statement. It
checks the condition and executes the exp1 if condition is true otherwise it execute exp2.
Syntax : condition ? exp1 : exp 2;
Example : a>b ? a: b
8 . What is mean by Operators precedence and associativity?
• The precedence is used to determine how an expression involving more than one operator
is evaluated. The operator at higher level of precedence is evaluated first.
• The operator of same precedence evaluated from either from left to right or right to left
depending on level is known as associativity.
9. What is a compilation process?
Compilation is the process of converting the high level language program into machine
understandable form (Machine language). If the compiler found any syntax errors, the compiler
list down the error list. These errors should be corrected and recompiled.
It includes,
• Pre processor
• Compilation
• Assembly
• Linking
10. How to create enumeration constants?
Enumeration constant is the user defined constant based on the standard integer type.
They allow the programmer to name a finite set together with its elements.
Keyword: enum
Syntax : enum identifier{const1, const 2….constn );

Department of CSE Page 44


CS3251 PROGRAMMING IN C 2023

Example: enum Day{ Monday, Tuesday, Wednesday, Thursday};


11. Generalize the types of I/O statements available in ‘C’.
• Unformatted Input / Output statements
o Input : getc(), getchar(), gets(), getche(), getch()
o Output : putc(), putchar(), puts().
• Unformatted Input / Output statements
o Input : scanf(), fscanf()
o Output : printf(), fprintf()
12. Classify the different types of storage classes.
There are mainly four types of storage classes. They are
• Automatic (auto)
• Static
• External (extern)
• Register
13. Differentiate switch( ) and nested if statement
Switch( ) Nested if
The switch( ) can test only constant values. nested if can evaluate relational or logical
expressions.of characters.
In switch( ) case, nested if can be used. In nested if statements, switch can be used
14. Give the difference between ++a and a++.
• ++a is known as pre increment where the value is incremented by one and then the
operation is done.
• a++ is known as post increment where the operation is done first and then the value
is incremented by one.

15. Summarize the various types of C operators.


• Arithmatic operators
• Relational operators
• Logical operators
• Assignment operators
• Increment and decrement operators
• Conditional or Ternary operators
• Bitwise operators
• Special operators (sizeof, & and * , . and -->)
16. What is a global variable and local variable?
• Variables that are declared outside of all the function are called as global
variables. It can be used inside any part of the program.
• Variables that are declared inside function are called as local variables. It can be
used only within the program.

Department of CSE Page 45


CS3251 PROGRAMMING IN C 2023

Example
a=10;
main()
{
b=30;
printf(“a and b=%d%d”,a,b);
}
a is the global variable and b is the local variable
17. Differentiate break and continue statement.
Break Continue
Terminate loop Skip iteration & continue with next iteration.
Takes the control to outside of the loop. Takes control to the beginning of the loop.
It used in both looping and switch It is used only in looping statement
statements.
18. What are the different data types available in C?
There are five basic data types:
(i) Character - char
(ii) Integer - int
(iii) Single-Precision floating point - float
(iv) Double Precision floating point - double
(v) No value available - void
19. Distinguish between while and do...while statement in C.
while do...while
(i) Some time the loop will not be (i) Loop is executed at least once.
executed minimum one time.
(ii) The condition is checked at the (ii) The condition is checked at the end
beginning of the loop of the loop
20. Mention the various Decisions making statement available in C.
The conditional branching statements are:
if ,if-else , Nested if, if else if else, switch Statement
The unconditional branching statements are.
Goto, break, continue, return
21. What is the use of sizeof operator in C?
The sizeof operator is used to return the size/ number of bytes of an variable or data type..
Example : sizeof(a), If a is an integer then it will return 4
22. What are the types of looping statements available in C?
C language has the following looping statements.
1. for loop
2. while loop
3. do...while loop

Department of CSE Page 46


CS3251 PROGRAMMING IN C 2023

PART B (Possible Questions)


1. a) Explain the different types of operators used in C with necessary program (8)
b) Write the C program to check the integer is palindrome or not. (5) (APRIL/MAY 2018)
2. Describe the decision making statements and looping statements in C (13) (APRIL/MAY
2018)
3. Write about the need and types of looping statements in C language and discuss with
examples.
4. Differentiate entry and exit checked conditional constructs with an example.
5. Write about the need and types of branching statements in C language and discuss
with examples.
6. Write a program to check whether a given number is prime or not.
7. Write a program to find the sum of digits of an integer.
8. Write a C program to find roots of a quadratic equation.
9. Explain the different data types available in C.
10. What are constants? Explain the various types of constants.
11. Describe structure of C program using Calculator program example.
12. Illustrate the storage class specifiers with example.
13. Discuss about the constants, expressions and statements in ‘C’.
14. Explain in detail about the operator precedence and associativity with example.
15. Explian in about assignment statements with an example.
16. Write about needs and use of enumeration constant with an example.

PART C (Possible Questions)


1. What is an operator? Explain the arithmetic, relational, logical and assignment operators in C
language.
2. Write a C program to calculate the area and volume of a circle.
3. Write a C program to convert the integer into the corresponding floating point number.
4. Write a C program to find whether a number is even or odd.
5. Write a C program to calculate the sum of numbers from m to n.
6. Write a C program to calculate the average of first n numbers.
6. Write a C program to determine whether a given number is a prime or a composite number.
7. Write a C program to determine whether the entered character is a vowel or not
8. Write the C program to check the integer is palindrome or not.
9. Write the C program to reverse a Number.
10. Write the C program to compute factorial and Fibonacci of a number
11. Write the C program to convert Fahrenheit to Celsius.
12. Write a C program for the following :
a. To check whether a given year is leap or not.(4)
b. To find the roots of a quadratic equation.(8)
c. To convert the temperature given in Fahrenheit to Celsius(4)
13. Develop a C program for the following :
a. To find the area and circumference of a circle with radius r.(4)
b. To find the sum of first 100 integers.(6)
c. To reverse the digits of a number.

Department of CSE Page 47


CS3251 PROGRAMMING IN C 2023

ADDITIONAL PROGRAMS
1. Find the Area and Circumference of a Circle
# include <stdio.h>
# include <conio.h>
void main()
{
float r, area, circum;
clrscr();
printf("Enter the value of radius : ");
scanf("%f", &r);
area = 3.14 * r * r;
circum = 2 * 3.14 * r;
printf("Area of a given Circle : %f\n ", area);
printf("Circumference of a given Circle : %f", circum);
getch();
}
Output:
Enter the value of radius : 5
Area of a given Circle : 78.5
Circumference of a given Circle : 31.4
2. Find the Biggest of Two Numbers
# include<stdio.h>
# include<conio.h>
void main()
{
int a, b;
clrscr();
printf("Enter two values\n");
scanf("%d %d", &a, &b);
if ( a > b)
printf("a is the Biggest data ");
else
printf("b is the Biggest data");
getch();
}
Output:
Enter two values
8
5
a is the Biggest data

Department of CSE Page 48


CS3251 PROGRAMMING IN C 2023

3. Find the Biggest Among Three Numbers


# include<stdio.h>
# include<conio.h>
void main()
{
int a, b, c;
printf("Enter a, b , c values\n");
scanf("%d %d %d", &a, &b, &c);
if (( a > b ) && ( a > c ))
printf("A is big");
else if ( b > c )
printf("B is big");
else
printf("C is big");
getch();
}
Output:
Enter a, b , c values
2
5
6
C is big
4. Find the Area of a Triangle
# include<stdio.h>
# include<conio.h>
# include<math.h>
void main()
{
int a, b, c;
float s, area;
clrscr();
printf("Enter the value for 3 sides of a triangle\n");
scanf("%d %d %d", &a, &b, &c);
s = ( a + b + c ) / 2;
area = sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
printf("\nArea of triangle = %f", area);
getch();
}
Output:
Enter the value for 3 sides of a triangle

Department of CSE Page 49


CS3251 PROGRAMMING IN C 2023

5
6
7
Area of triangle=14.696939
5. Convert Fahrenheit To Celsius
# include<stdio.h>
# include<conio.h>
void main()
{
float cel, fahr;
clrscr();
printf("Enter the Fahrenheit value\n");
scanf("%f", &fahr);
cel = ( fahr - 32 ) / 1.8;
printf("Celcious value = %f", cel);
getch();
}
Output:
Enter the Fahrenheit value
68
Celsius value = 20
6. Convert Celsius To Fahrenheit
# include<stdio.h>
# include<conio.h>
void main()
{
float cel, fahr;
clrscr();
printf("Enter the Celsius value\n");
scanf("%f", &cel);
fahr = ( ( 1.8 * cel ) + 32 );
printf("Fahrenheit value = %f", fahr);
getch();
}
Output:
Enter the Celsius value
20
Fahrenheit value = 68
7. Check Whether the Given Year is a Leap Year or Not
# include<stdio.h>

Department of CSE Page 50


CS3251 PROGRAMMING IN C 2023

# include<conio.h>
void main()
{
int year;
clrscr();
printf("Enter a Year\n");
scanf("%d", &year);
if ( year % 4 == 0 )
{
printf("Given Year is a Leap Year");
}
else
{
printf("Given Year is not a Leap Year");
}
getch();
}
Output:
Enter a Year
2000
Given Year is a Leap Year
8. Check Whether the Given Number is Odd or Even
# include<stdio.h>
# include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a Number\n");
scanf("%d", &n);
if ( n % 2 == 0)
{
printf("%d is an Even Number", n);
}
else
{
printf("%d is an Odd Number", n);
}
getch();
}

Department of CSE Page 51


CS3251 PROGRAMMING IN C 2023

Output:
Enter a Number
8
8 is an Even Number
9. Generate Fibonacci Series.
# include <stdio.h>
# include <conio.h>
void main()
{
int f1, f2, f3, i, n;
clrscr();
f1 = 0;
f2 = 1;
printf("\n Enter how many time generate Fibonacci Series");
scanf("%d", &n);
printf("\n Fibonacci Series\n");
printf("\t %d \t %d", f1, f2);
for ( i = 3 ; i <= n ; i++ )
{
f3 = f1 + f2;
f1 = f2;
f2 = f3;
printf("\t %d" ,f3);
}
getch();
}
Output:
Enter how many time generate Fibonacci Series
6
Fibonacci Series
0 1 1 2 3 5
10. Check Whether the Given Number is Prime or Not
# include<stdio.h>
# include<conio.h>
void main()
{
int num, i, count = 0;
clrscr();
printf("Enter a Number: ");
scanf("%d", &num);

Department of CSE Page 52


CS3251 PROGRAMMING IN C 2023

for ( i = 2 ; i <= num / 2 ; i++)


{
if ( num % i == 0 )
{
count++;
break;
}
}
if ( count == 0 && num != 1 )
printf("%d is a Prime Number", num);
else
printf("%d is not a Prime Number", num);
getch();
}
Output:
Enter a Number: 5
5 is a Prime Number
11. Check Whether the Given Number is Armstrong or Not
# include<stdio.h>
# include<conio.h>
void main()
{
int num, r, sum = 0, temp;
clrscr();
printf("Enter a Number : ");
scanf("%d", &num);
temp = num;
while ( num != 0 )
{
r = num % 10;
num = num / 10;
sum = sum + ( r * r * r );
}
if ( sum == temp )
printf("%d is an Armstrong Number", temp);
else
printf("%d is not an Armstrong Number", temp);
getch();
}
Output:

Department of CSE Page 53


CS3251 PROGRAMMING IN C 2023

Enter a Number
153
153 is an Armstrong Number
12. Reverse a Number
#include<stdio.h>
#include<conio.h>
void main()
{
int num, digit, reverse = 0;
clrscr();
printf ("Enter any Positive Number : ");
scanf("%d", &num);
while ( num > 0 )
{
digit = num % 10;
reverse = reverse * 10 + digit;
num = num / 10;
}
printf("Reversed of the given Number : %d", reverse);
getch();
}
Output:
Enter any Positive Number : 127
Reversed of the given Number : 721
13. Check Whether the Given Number is Palindrome or Not
#include<stdio.h>
#include<conio.h>
void main()
{
int num, digit, reverse = 0;
int original;
clrscr();
printf ("Enter any Number : ");
scanf("%d", &num);
original = num;
while ( num > 0 )
{
digit = num % 10;
reverse = reverse * 10 + digit;
num = num / 10;

Department of CSE Page 54


CS3251 PROGRAMMING IN C 2023

}
if (reverse == original)
printf("\n The Number is Palindrome \n");
else
printf("\n The Number is not a Palindrome\n ");
getch();
}
Output:
Enter any number
525
The Number is Palindrome
14. Find the Sum of Digits of a Positive Number
#include<stdio.h>
#include<conio.h>
void main()
{
int num, sum = 0, digit;
clrscr();
printf("Enter a Positive Number: ");
scanf("%d", &num);
while ( num != 0)
{
digit = num % 10;
num = num / 10;
sum = sum + digit;
}
printf("Sum of digits of number: %d",sum);
getch();
}

Output:
Enter a Positive Number: 123
Sum of digits of number: 6
15. Count the Number of Digits in a Number
#include<stdio.h>
#include<conio.h>
void main()
{
int num, count = 0;
printf("Enter a Number: ");

Department of CSE Page 55


CS3251 PROGRAMMING IN C 2023

scanf("%d", &num);
while(num != 0)
{
num = num / 10;
count++;
}
printf("Total Number of Digits is : %d", count);
getch();
}
Output:
Enter a Number: 823
Total Number of Digits is : 3
16. Find the Factorial of a Given Number
#include<stdio.h>
#include<conio.h>
void main()
{
int fact = 1, i, num;
clrscr();
printf("Enter a Number : ");
scanf("%d", &num);
for ( i = 1 ; i <= num ; i++)
{
fact = fact * i;
}
printf("Factorial of %d = %d", num, fact);
getch();
}
Output:
Enter a Number :4
Factorial of 3 = 24
17. Swapping of Numbers
#include <stdio.h>
#include<conio.h>
void main()
{
int x, y, temp;
clrscr();
printf("Enter the value of x and y \n");
scanf("%d%d", &x, &y);

Department of CSE Page 56


CS3251 PROGRAMMING IN C 2023

printf("Before Swapping : \n“);


printf(“\t x = %d \t y = %d \n", x, y);
temp = x;
x = y;
y = temp;
printf("After Swapping : \n“);
printf(“\t x = %d \t y = %d \n", x, y);
}
Output:
Enter the value of x and y
4
5

Department of CSE Page 57


CS 3251 PROGRAMMING IN C 2023

UNIT II ARRAYS AND STRINGS


Introduction to Arrays: Declaration, Initialization – One dimensional array –Two dimensional
arrays - String operations: length, compare, concatenate, copy – Selection sort, linear and binary
search.

2.1. INTRODUCTION TO ARRAYS:

➢ An Array is a collection of similar data elements.


➢ These data elements have the same data type.
➢ The elements of the array are stored in consecutive memory locations and are referenced
by an index (also known as subscript).
➢ Subscript indicates an ordinal number of the elements counted from the beginning of the
array.

Definition:
An array is a data structure that is used to store data of the same type. The position of
an element is specified with an integer value known as index or subscript.
Features of Array
✓ An array is a derived data type. It is used to represent a collection of elements of the
same data type.
✓ Array elements are counted from 0 to size-1.
✓ The elements can be accessed with array name and the index. The index specifies the
position of the element.
✓ The elements in an array are stored in continuous memory location. The starting
memory location is represented by the array name and it is known as the base address
of the Array.
Advantage of 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
Types of array:
1. Single dimensional array
2. Multi-dimensional array
2.2 DECLARATIONS OF ARRAYS
Array has to be declared before using it in C Program. Declaring Array means
specifying three things.

Department of CSE Page 58


CS 3251 PROGRAMMING IN C 2023

Data_type Data Type of Each Element of the array


Array_name Valid variable name
Size Dimensions of the Array
Syntax:
datatype name[size];
Here, the type can be either int, float, double, char or any oher valid data type. The
number within the brackets indicates the size of the array, i.e., the maximum number of
elements that can be stored in the array.
ex: int marks[10]
2.3 INITIALIZATION OF ARRAYS
➢ Elements of the array can also be initialized at the time of declaration as in the case
of every other variable.
➢ When an array is initialized, we need to provide a value for every element in the
array.
➢ Arrays are initialized by writing,

datatype array_name[size] = { list of values};


The values are written with curly brackets and every value is separated by a comma. It is a
compiler error to specify more number of values than the number of elements in the array.

ex: int marks[5] = {90, 92, 78, 82, 58};

2.4 ONE DIMENSIONAL ARRAY


If the array has only one subscript then it is called one dimensional or single dimensional
array. An array is a collection of homogeneous (similar) data items that are stored under one
common name.
Characteristics of One Dimensional Array
✓ Array size must be positive number.
✓ Array elements are counted from 0 to size-1.
✓ String arrays are terminated with null character ('\0').
2.4.1 Declaration of an Array
Arrays must be declared before they are used so that the compiler can allocate space for them
in memory.
Syntax for array declaration
data type array_name [size];
o The data type specifies the array elements data type.
o Size indicates the maximum number of elements that can be stored in the array.
Example
float height [10];
The above array declaration represents the array name is height, we can store a maximum
of 10 elements and the array elements are floating point data type.

Department of CSE Page 59


CS 3251 PROGRAMMING IN C 2023

Different data type declaration of array


1. int a[5];

a[0] a[1] a[2] a[3] a[4]


2. float b[5];

b[0] b[1] b[2] b[3] b[4]


3. char m[5];

m[0] m[1] m[2] m[3] m[4]


Fig. 2.1 Different data type declaration of array
2.4.2 Array Initialization
The array elements can be initialized when they are declared otherwise they will take
garbage values.
Compile time initialization
Arrays can be initialized at compile time.
Syntax:
data type array_name [size] = {value 0, value 1, . . . , value n-1)
The initialized values are specified within curly braces separated by commas.
Example:
int Marks [3] = {70, 80, 90};
This statement declares the variable Marks as an array of 3 elements and will be assigned
the values specified in list as below.
70 Marks [0]
80
Marks [1]
90
Marks [2]
Fig. 2.2: Array Initialization
Like ordinary variables, the values to the array can be initialized as follows.
int Marks[3];
Marks [0] = 70;
Marks [1] = 80;
Marks [2] = 90;
Character array can be initialized as follows:
char gender[2] = {'M','F'};
Runtime initialization
Arrays can be initialized at run time.

Department of CSE Page 60


CS 3251 PROGRAMMING IN C 2023

Example:
int a[2];
scanf(“%d%d”,&a[0],&a[1]);
Program: Calculate the average marks of the student
# include<stdio.h>
#include<conio.h>
void main()
{
int m[5],i,sum=0,n;
float avg;
printf(“enter number of subject \n”);
scanf(“%d”,&n);
printf(“enter marks \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
avg=(float)sum/n;
printf(“average=%f”,avg);
getch()
}
Output:
Enter number of subject
5
Enter marks of students
55
60
78
85
90
Average=73.6
2.5 TWO DIMENSIONAL ARRAYS
If the array has two subscripts then it is called two dimensional array or matrix. Two
dimensional arrays are used in situation where a table of values needs to be stored. A 2D array is
an array of 1-D arrays and can be visualized as a plane that has rows and columns.
2.5.1 Declaration
Two dimensional arrays must be declared before they are used so that the compiler can
allocate space for them in memory.

Department of CSE Page 61


CS 3251 PROGRAMMING IN C 2023

Syntax for declaration


datatype array_name [row size] [col size];
• The data type specifies the array elements data type.
• rowsize indicates the size of row
• colsize indicates the size of column
Example
int matrix[5] [5];
char name[10] [20]; // 10 rows 20 columns
The above array declaration represents the array name is height, we can store a maximum
of 10 elements and the array elements are floating point data type.
a
[0][0] [0][1] [0][2] [0][3] [0][4]

[1][0] [1][1] [1][2] [1][3] [1][4]


a[3][5]
[2][0] [2][1] [2][2] [2][3] [2][4]

Fig. 2.3: Memory layout representation


2.5.2 Initialization
The array elements can be initialized when they are declared otherwise they will take
garbage values.
Compile time initialization
Arrays can be initialized at compile time.
Syntax
datatype array_name [row size] [col size];= {value 0, value 1, . . . , value n-1};
The initialized values are specified within curly braces separated by commas.
Example:
int matrix[3][5] = { {2, 6, 7,8,9} , {10, -50, 3,5,6},{2,4,6,8,20} };

2 6 7 8 9

10 -50 3 5 6

2 4 6 8 20

Fig. 2.4: Memory Representation of 2DArray


Runtime initialization
Arrays can be initialized at run time.
Example:
int a[2][2];

Department of CSE Page 62


CS 3251 PROGRAMMING IN C 2023

scanf(“%d%d”,&a[0][0],&a[0][1],&a[1][0],&a[1][1]);
Program: Find the addition of two matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int a[25][25],b[25][25], c[25][25], i, j m, n;
clrscr();
printf(“\n Enter the rows and columns of two matrices… “);
scanf(“%d %d “, &m, &n)
printf(“\n Enter the elements of A matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“\n Enter the elements of B matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j] + b[i][j];
printf(“\n The addition of two matrices”);
for(i=0;i<m;i++)
{
printf(“\n”);
for(j=0;j<n;j++)
{
printf(“\t %d”,c[i][j]);
}
}
getch();
}
Output:
Enter the rows and columns of two matrices…. 3 3
Enter the elements of A matrix
1 2 3
4 5 6
7 8 9
Enter the elements of B matrix
1 2 3

Department of CSE Page 63


CS 3251 PROGRAMMING IN C 2023

4 5 6
7 8 9
The addition of two matrixes
2 4 6
8 10 12
14 16 18
2.6 STRING OPERATIONS (LENGTH, COMPARE, CONCATENATE, COPY)
String is a collection of characters. In C language array of characters are called string. It
is enclosed within double quotes. E.g. “INDIA” is a string. Each character of string occupies 1
byte of memory. The last character is always ‘\0’.
Declaration of a String
Strings can be declared like a one dimensional array.
Syntax:
char string_name[size];
Example:
char name[30];
char dept[20];
String Initialization
The string can be initialized as follows:
char dept[10] = “CSE”;
OR
char dept[] = {‘C’, ‘S’, ‘E’,’\0’};
In the above example, ‘\0’ is a null character and specifies end of the string. Here string is
assigned character by character.
String Handling / Manipulation Function:
For string handling, we must include <string.h> header file in program
Function Purpose

strlen () Used to find length of a string


strcpy () Used to copy one string to another
strcat () Used to concatenate two strings
strcmp () Used to compare characters of two strings
strlwr () Convert strings into lower case
strupr () Convert strings into upper case
strrev () Used to reverse a string

Table 2.1: String Handling Function

Department of CSE Page 64


CS 3251 PROGRAMMING IN C 2023

2.6.1 String Length


strlen() function is used to find the length of a string. It is used to count and return the
number of characters present in a string. The terminating character (‘\0’) is not counted.
Syntax
temp_variable = strlen(string_name);

Example
s= “hai”;
strlen(s)-> returns 3.
Program:
# include<stdio.h>
#include<conio.h>
# include <string.h>
void main()
{
char name[10];
printf(“Enter string:”);
scanf(“%s”,name);
int length;
length = strlen(name);
printf(“\n String length of %s is %d”, name, length);
getch();
}
Output:
Enter string: APPLE
String length of APPLE is 5
2.6.2 String Copy
It copies the source string to the destination string or used to copy the contents of one
string to another string variable
Syntax
strcpy(destination,source);

Example

s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); // s2 is copied to s1. i.e. s1=welcome.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>

Department of CSE Page 65


CS 3251 PROGRAMMING IN C 2023

void main()
{
char source[10];
printf(“Enter string:”);
scanf(“%s”,source);
char target[10];
strcpy(target, source);
printf(“\n Source string is %s”, source);
printf(“Target string is %s, target);
getch();
}
Output:
Enter string : COMPUTER
Source string is COMPUTER
Target string is COMPUTER
2.6.3 String concatenation
strcat() is used to concatenate or combine two strings together.
Syntax:
strcat (string1, string2);
String2 is concatenated at the end of string1 and the result is stored in string1.
Example
s1=“hai ”;
s2= “welcome”;
strcat(s1,s2); // s2 is joined with s1. Now s1 is hai welcome.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char source[10];
printf(“Enter string1:”);
scanf(“%s”,source);
char target[10];
printf(“Enter string 2:”);
scanf(“%s”,target);
strcat(source, target);
printf(“After concatenation source string is : %s”, source);
getch();
}

Department of CSE Page 66


CS 3251 PROGRAMMING IN C 2023

Output:
Enter string1 : Computer
Enter string2 : Programming
After concatenation source string is: Computer Programming
2.6.4 String Compare
strcmp() function compares two strings to check whether they are same or different. The
two strings are compared character by character until end of one string is reached or a mismatch
character found.
• If two strings are identical, strcmp() returns a value zero
• If they are not equal it returns the numeric difference between the first non-
matching characters.
• if the strcmp() returns positive then string1 is greater and negative means string2
is greater.
Syntax:
strcmp(string1, string2);
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char source[10];
printf(“Enter string1:”);
scanf(“%s”,source);
char target[10];
printf(“Enter string 2:”);
scanf(“%s”,target);
int diff;
diff = strcmp (source, target);
if (diff == 0 )
printf(“Both strings are identical”);
else
printf(“Both strings are not identical”);
getch();
}
Output:
Enter String 1: Computer
Enter String 2: Programming
Both strings are not identical

Department of CSE Page 67


CS 3251 PROGRAMMING IN C 2023

2.7 SORTING
Sorting is the process of arranging elements either in ascending or in descending order.
Some of the sorting Methods are,
• Selection Sort
• Bubble Sort
• Merge sort
• Quick sort
2.7.1 Selection Sort
It finds the smallest element in the list & swaps it with the element present at the head of
the list. It is a very simple and natural way of sorting a list.
Steps:
• In selection sort the first element is compared with the remaining elements.
• If the first element is larger than the other elements, it should be interchanged.
• In the second iteration, the second element is compared with the following elements
and interchange if not in order.
• This step is continued for various iterations, until the elements are sorted in an order.
Example : (44, 33, 55, 22, 11)
Iteration 1: First compare first element with all other element.
44, 33, 55, 22, 11 Compare 44 & 33. Not in order. So swap.
33, 44, 55, 22, 11 Compare 33 & 55. It is in order. So don't swap.
33, 44, 55, 22, 11 Compare 33 & 22. Not in order. So swap.
22, 44, 55, 33, 11 Compare 22 & 11. Not in order. So swap.
11, 44, 55, 33, 22 Now first element is in correct order.
Iteration 2: Now compare second element with all other element.
11, 44, 55, 33, 22 Compare 44 & 55. It is in order . So don't swap.
11, 44, 55, 33, 22 Compare 44 & 33. Not in order . So swap.
11, 33, 55, 44, 22 Compare 33 & 22. Not in order . So swap.
11, 22, 55, 44, 33 Now first two elements are in correct order.
Iteration 3: Now compare third element with all other element.
11, 22, 55, 44, 33 Compare 55 & 44. Not in order . So swap.
11, 22, 44, 55, 33 Compare 44 & 33. Not in order . So swap.
11, 22, 33, 55, 44 Now first three elements are in correct order.
Iteration 4: Now compare fourth element with all other element.
11, 22, 33, 55, 44 Compare 55 & 44. Not in order . So swap.
11, 22, 33. 44, 55 Now first 4 elements are in correct order.
Balance only one element is there. So sorting is over.
Program:
#include <stdio.h>
#include<conio.h>
void main()

Department of CSE Page 68


CS 3251 PROGRAMMING IN C 2023

{
int i, j, temp, n, a[10];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; i++)
printf("%d\n", a[i]);
printf("The numbers arranged in descending order are given below \n");
for(i=n-1;i>=0;i--)
printf("%d\n",a[i]);
getch();
}
Output:
Enter the value of N
4
Enter the numbers
10 2 5 3
The numbers arranged in ascending order are given below
2
3
5
10
The numbers arranged in descending order are given below
10
5
3
2

Department of CSE Page 69


CS 3251 PROGRAMMING IN C 2023

2.8 SEARCHING
Searching is to find a particular element in a list of elements. Following are some of the
searching methods.
1. Linear Search
2. Binary Search
2.8.1 Linear Search (or) Sequential Search:
This is the simplest method of searching a data in an array. This can be applied in an
unsorted array. Its time complexity is O ( n ).
Steps:
• In Linear search, we start the search from first location.
• If data found we stop otherwise search continues with next location.
• The above step is repeated until we reach the last location.
• Whenever we reach end of the list, the data is not found.
Example 1:
Consider the array elements: 3, 15, 12, 13, 8 and
Element to be searched = 13
Steps:
First we compare 13 with first element 3 - No match
Then compare 13 with second element 15 – No match
Then compare 13 with third element 12 – No match
Then compare 13 with fourth element 13 – Match.
Thus, the data found at location 4.
Example 2:
Consider the array elements: 3, 15, 12, 13, 8 and
Element to be searched (key) = 7
Steps:
First we compare 7 with first element 3 - No match
Then compare 7 with second element 15 – No match
Then compare 7 with third element 12 – No match
Then compare 7 with fourth element 13 – No match.
Then compare 7 with fifth element 8 – No match.
Now we reached the end of the list. So we say that “data not found”.
Program: Linear Search
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);

Department of CSE Page 70


CS 3251 PROGRAMMING IN C 2023

printf("Enter the elements of the array: ");


for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++)
{
if(a[i]==m)
{
printf("Element is in the position %d\n",i+1);
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
getch();
}

Output:
Enter the size of an array: 4
Enter the elements of the array: 4 3 5 1
Enter the number to be search: 5
Element is in the position 3
2.8.2 Binary Search:
Binary search can be applied only on sorted data. It is faster than linear search. Its time
complexity is O(log n)
Steps:
• First check the search element at the middle of the list
• If the middle element is the search key, then the data found. Stop the searching.
• If the key to be searched is smaller than the middle element then continue with the
bottom half of the list.
• If the key to be searched is greater than the middle element then continue with the top
half of the list
• Repeat the above steps till the sub array not possible further divide.
Example:
Consider the array elements
10, 15, 17, 23, 45, 60, 75
And the search element key = 15

Department of CSE Page 71


CS 3251 PROGRAMMING IN C 2023

1st Iteration:
High = 7, Low =1
Mid = (low + high) / 2 = (1 + 7) / 2 = 8/2 = 4
Array [mid] = Array[4] = 23
Here 15 < 23 search continues on the left side of the array
Therefore new High = mid -1 = 4 – 1 = 3
The sub list = 10, 15, 17
2nd iteration:
High = 3, Low = 1
Mid = (low + high) / 2 = (1 + 3) / 2 = 4 / 2 = 2
Array[mid] = Array[2] = 15
Here Array[mid] = key. i.e., 15 = 15
Thus data found at mid. i.e., at location 2.
Program : Binary Search
#include<stdio.h>
#include<conio.h>
void main()
{
int A[10], i, n, key,c=0;
int mid, low, high;
printf(“Enter the size of an array:”);
scanf(“%d”, &n);
printf(“Enter the elements in ascending order :”);
for( i = 1; i <= n; i++)
scanf(“%d”, &A[i]);
low = 1; high = n;
printf(“Enter the number to be searched:”);
scanf(“%d”, &key);
while ( low <= high)
{
mid = (low + high) / 2;
if ( A[mid] == key)
c=1;
break;
else if ( A[mid] < Key )
low = mid+ 1;
else
high = mid – 1;
}
if(c==0)

Department of CSE Page 72


CS 3251 PROGRAMMING IN C 2023

printf("The number is not found.");


else
printf("The number is found.");
getch();
}
Output:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21
Enter the number to be searched: 11
The number is found.

PART A (2 Marks with Answers)


1. What is array? Write the syntax for multi dimensional array. (APRIL/MAY 2018)
An array is a collection of homogeneous (similar) data items that are stored under one
common name. Individual data item (array elements) in an array is identified by index or
subscript enclosed in square brackets with array name.
Syntax for multi dimensional array
datatype array_name [size1] [size2]…..[sizen];
• The data type specifies the array elements data type.
• Size1, size2 indicates the size of dimensions
2. Design C Program to compare two string. (APRIL/MAY 2018)
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char source[10];
printf(“Enter string1:”);
scanf(“%s”,source);
char target[10];
printf(“Enter string 2:”);
scanf(“%s”,target);
int diff;
diff = strcmp (source, target);
if (diff == 0 )
printf(“Both strings are identical”);
else
printf(“Both strings are not identical”);
getch();
}

Department of CSE Page 73


CS 3251 PROGRAMMING IN C 2023

Output:
Enter String 1: Computer
Enter String 2: Programming
Both strings are not identical
3. List out the features of Arrays.
• An array is a derived data type. It is used to represent a collection of elements of the same
data type.
• The elements can be accessed with array name and the index. The index specifies the
position of the element.
• The elements in an array are stored in continuous memory location.
• The starting memory location is represented by the array name and it is known as the
base address of the Array.
4. Define a float array of size 5 and assign 5 values to it.
void main( )
{
float a[5] = {26.9, 32.4, 84.2, 20.0, 78.1};
}
5. Identify the main elements of an array declaration.
Arrays must be declared before they are used so that the compiler can allocate space for them
in memory.
Syntax :
datatype arrayname[size]; [OR]
datatype arrayname[array_size]={list_of_values};
Example
int marks[6]={3,7,8,9,5,4};
6. How to create a two dimensional array?
If the array has two subscripts then it is called two dimensional array or matrix.
Syntax
datatype array_name [row size] [col size];= {value 0, value 1, . . . , value n};
• The data type specifies the array elements data type.
• rowsize indicates the size of row
• colsize indicates the size of column

Example:
int matrix[3][5] = { {2, 6, 7,8,9} , {10, -50, 3,5,6},{2,4,6,8,20} };
7. What are the different ways of initializing array?
Values can be assigned to an array by normal declaration otherwise they hold garbage
values. Arrays can be initialized in following two ways :
i. At compile time
ii. At Run time

Department of CSE Page 74


CS 3251 PROGRAMMING IN C 2023

Syntax:
datatype array_name [size] = {value 0, value 1, . . . , value n-1};
The initialized values are specified within curly braces separated by commas.
Example:
int Marks [3] = {70, 80, 90};
8. What is the use of ‘\0’ and ‘%s’?
• ‘\0’ is the escape sequence for null character it is automatically added at the end of the
string.
• ‘%s’ is a format specifier for string. It is used in scanf( ) and printf( ) functions to get the
string input or to print string output.
9. Define string.
String is a collection of characters. In C language array of characters are called string. It
is enclosed within double quotes. E.g. “INDIA” is a string. Each character of string occupies 1
byte of memory. The last character is always ‘\0’.
Syntax:
char string_name[size];
Example
char name[30];
10. Write a C program to find the length of given string.
# include<stdio.h>
#include<conio.h>
# include <string.h>
void main()
{
char name[10];
printf(“Enter string:”);
scanf(“%s”,name);
int length;
length = strlen(name);
printf(“\n String length of %s is %d”, name, length);
getch();
}
Output:
Enter string: APPLE
String length of APPLE is 5
11. Name library functions used for string handling.
Function Purpose

strlen () Used to find length of a string


strcpy () Used to copy one string to another
strcat () Used to concatenate two strings

Department of CSE Page 75


CS 3251 PROGRAMMING IN C 2023

strcmp () Used to compare characters of two strings


strlwr () Convert strings into lower case
strupr () Convert strings into upper case
strrev () Used to reverse a string
12. How to initialize a string? Give an example.
The string can be initialized as follows:
char dept[10] = “CSE”;
OR
char dept[] = {‘C’, ‘S’, ‘E’,’\0’};
In the above example, ‘\0’ is a null character and specifies end of the string. Here string is
assigned character by character.
13. Differentiate between Linear search and Binary search.

Linear search Binary search.


This can be applied in an unsorted array It can be applied only on sorted data.
Its time complexity is O(n) Its time complexity is O(log n)
Slow Fast
14. What is the starting and ending index of an array?
• 0 is the starting index of an array
• n-1 is the ending index of an array
15. What is the difference between an array and pointer?

Array Pointer

Array allocates space automatically 1.Pointer is explicitly assigned to point to an


allocated space

2.It cannot be resized. 2.It can be resized using realloc ().

3.It cannot be reassigned. 3.Pointers can be reassigned.

4.Size of(array name) gives the number 4.Sezeof(pointer name) returns the number of
of bytes occupied by the array. bytes used to store the pointer variable.
16. What are the types of Arrays?

1. One-Dimensional Array

2. Two-Dimensional Array

3. Multi Dimensional Array

Department of CSE Page 76


CS 3251 PROGRAMMING IN C 2023

17. Differentiate break and continue statement.


Break Continue
Terminate loop Skip iteration & continue with next iteration.
Takes the control to outside of the loop. Takes control to the beginning of the loop.
It used in both looping and switch It is used only in looping statement
statements.
18. Write a C program to copy given string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char source[10];
printf(“Enter string:”);
scanf(“%s”,source);
char target[10];
strcpy(target, source);
printf(“\n Source string is %s”, source);
printf(“Target string is %s, target);
getch();
}
Output:
Enter string : COMPUTER
Source string is COMPUTER
Target string is COMPUTER
19. What is sorting? List types.
Sorting is the process of arranging elements either in ascending or in descending order.
Sorting Methods are following,
• Selection Sort
• Bubble Sort
• Merge sort
• Quick sort
20. What is meant by selection sort?
It finds the smallest element in the list & swaps it with the element present at the
head of the list. It is a very simple and natural way of sorting a list.
• In selection sort the first element is compared with the remaining elements.
• If the first element is larger than the other elements, it should be interchanged.
• In the second iteration, the second element is compared with the following elements
and interchange if not in order.
• This step is continued for various iterations, until the elements are sorted in an order.

Department of CSE Page 77


CS 3251 PROGRAMMING IN C 2023

21. What is meant by searching?


Searching is to find a particular element in a list of elements. Following are some of the
searching methods.
1. Linear Search
2. Binary Search
22. Write a C program to concatenate two strings.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char source[10];
printf(“Enter string1:”);
scanf(“%s”,source);
char target[10];
printf(“Enter string 2:”);
scanf(“%s”,target);
strcat(source, target);
printf(“After concatenation source string is : %s”, source);
getch();
}
Output:
Enter string1 : Computer
Enter string2 : Programming
After concatenation source string is: Computer Programming

PART B (Possible Questions)


1. Write the C program to multiply two matrices which will be entered by user. The user will
enter the order of a matrix and then its elements and similarly input the second matrix. If the
entered orders of 2 matrices are same they cannot be multiplied by each other, then error
message is displayed on the screen (13) (APRIL/MAY 2018)
2. a) What are the different types of string function? Describe with their purpose (5)
b) Write the C program to find the number of vowels, consonants, digits and white space in a
string. (8) (APRIL/MAY 2018)
3. Explain in detail about array declaration and initialization with example program
4. Write a C program to sort the n numbers using selection sort
5. Describe the following functions with examples.
(i) strlen() (ii) strcpy() (iii)strcat() (iv)strcmp()

Department of CSE Page 78


CS 3251 PROGRAMMING IN C 2023

6. Discuss about the following :-


(i).Advantages and disadvantages of linear and binary search.(8)
(ii).Discuss briefly runtime initialization of a two dimensional array.(8)
7. Explain in detail about matrix operation with suitable examples
8. Explain in detail about two dimensional array declaration and initialization with example
program.

PART C (Possible Questions)


1. Write a C program to calculate mean for an array of elements.
2. Write a C program to find the determinant of the 3 x 3 matrix.
3. (i) Explain the need for array variables. Describe the following with respect to arrays:-
Declaration of array and accessing an array element.
(ii) Write a C program to re-order a one-dimensional array of numbers in descending order.
4. Write a C program to perform the following matrix operations:
(i) Addition (ii) subtraction (iii) Scaling
5. Write a C program to calculate mean and median for an array of elements.
6. .(i). Write a C program to find average marks obtained by a of 30 students in a test.
(ii).Write short notes on Reading and Writing string. (6)
7. Write a C program to multiply two matrixes of the 3 x 3 order.
8. Write a C program to perform the following matrix operations:
(i) Transpose (ii) determinant (iii) Scaling
9. Write a C program to find whether the given string is palindrome or not without using string
functions.
10. Develop a C program to search an element from the array.
11. Write a C program to sort the n numbers using selection sort

Department of CSE Page 79


CS 3251 PROGRAMMING IN C 2023

ADDITIONAL PROGRAMS
1. C program to calculate mean for an array of elements.

#include <stdio.h>
#include<conio.h>
void main()
{
int m[5],i,sum=0,n;
float mean;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
mean=sum/n;
printf(“Mean=%f”,mean);
}
Output:
Enter number of students
5
Enter marks of students
55
60
78
85
90
Mean=73.6
2. Computing Median:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,temp,n,a[20],sum=0;
float median;
printf("Enter n:");
scanf("%d",&n);
printf(“Enter numbers”);

Department of CSE Page 80


CS 3251 PROGRAMMING IN C 2023

for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(n%2==0)
{
median=((a[n/2]+a[n/2 -1])/2.0);
}
else
{
median=a[n/2];
}
printf("\n the median value is %f",median);
getch();
}
Output:
Enter n:5
Enter numbers: 10 20 30 40 50
The median value is 30
3. Computing Mode:
#include<stdio.h>
#include<conio.h>
void main()
{
int maxvalue = 0, maxCount = 0, i, j,a[20],n,count=0;
printf("Enter N:");
scanf("%d",&n);
printf(“Enter numbers”);

Department of CSE Page 81


CS 3251 PROGRAMMING IN C 2023

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


{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for (j = i+1; j < n;j++)
{
if(a[j] == a[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxvalue = a[i];
printf("\nThe mode value is %d",maxvalue);
}
}
getch();
}
Output:
Enter the N value:5
Enter 1 Number:0
Enter 2 Number:6
Enter 3 Number:7
Enter 4 Number:2
Enter 5 Number:7
The mode value is 74.
4. Matrix Multiplication
#include<stdio.h>
#include<conio.h>
void main()
{
int a[25][25],b[25][25], c[25][25], i, j m, n;
clrscr();
printf(“\n Enter the rows and columns of two matrices… “);
scanf(“%d %d “, &m, &n);
if ( m != n )
{
printf(“Matrix multiplication not possible”);

Department of CSE Page 82


CS 3251 PROGRAMMING IN C 2023

return;
}
printf{“\n Enter the elements of A matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf{“\n Enter the elements of B matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
for(k=0; k<n; k++)
c[i][j] =c[i][j]+ a[i][k] * b[k][j];
printf(“\n The multiplication of two matrices”);
for(i=0;i<m;i++)
{
printf(“\n”);
for(j=0;j<n;j++)
{
printf(“\t %d”,c[i][j]);
}
}
getch();
}
Output
Enter order of matrix A : 2 2
Enter order of matrix B : 2 2
Enter matrix A elements
2 3
4 1
Enter matrix B elements
1 2
3 2
The multiplication of two matrices
11 10
7 10
5. Matrix Scaling
#include<graphics.h>
#include<stdlib.h>

Department of CSE Page 83


CS 3251 PROGRAMMING IN C 2023

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int graphdriver=DETECT,graphmode,errorcode;
int i;
int x2,y2,x1,y1,x,y;
printf("Enter the 2 line end points:");
printf("x1,y1,x2,y2");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
initgraph(&graphdriver,&graphmode,"c:\\tc\\bgi");
line(x1,y1,x2,y2);
printf("Enter scaling co-ordinates ");
printf("x,y");
scanf("%d%d",&x,&y);
x1=(x1*x);
y1=(y1*y);
x2=(x2*x);
y2=(y2*y);
printf("Line after scaling");
line(x1,y1,x2,y2);
getch();
closegraph();
}
Output:

Department of CSE Page 84


CS 3251 PROGRAMMING IN C 2023

6. Matrix Determinant of 2x2 matrix

a b
A=
c d
|A| = ad - bc
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],i,j;
long determinant;
printf("Enter the 4 elements of matrix: ");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);

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


for(i=0;i<2;i++)
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
printf("\nDeterminant of 2X2 matrix: %ld",determinant);
getch();
}
Output:
Enter the 4 elements of matrix 4 8 3 9
4 8
3 9
Determinant of 2x 2 matrix : 12
7. Determinant of 3X3 matrix:
a b c
A= d e f
g h i

|A| = a(ei-fh)-b(di-gf)+c(dh-eg)

Department of CSE Page 85


CS 3251 PROGRAMMING IN C 2023

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
long determinant;
printf("Enter the 9 elements of matrix: ");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nThe matrix is\n");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
}
determinant = a[0][0]*((a[1][1]*a[2][2]) - (a[2][1]*a[1][2])) -a[0][1]* (a[1][0] *
a[2][2] - a[2][0]*a[1][2]) + a[0][2]*(a[1][0]*a[2][1] - a[2][0]*a[1][1]);
printf("\n Determinant of 3X3 matrix: %ld", determinant);
getch();
}
Output:
Enter the 9 elements of matrix: 1 2 3 4 5 6 7 8 9
1 2 3
4 5 6
7 8 9
Determinant of 3X3 matrix:0
8. Matrix Transpose
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j,m,n;
printf("How many rows");
scanf("%d",&m);
printf("How many columns");
scanf("%d",&n);
printf("\nEnter the matrix:\n");

Department of CSE Page 86


CS 3251 PROGRAMMING IN C 2023

for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d",a[i][j]);
printf("\nTranspose of given matrix:\n");
for(i=0;i<m;++i)
for(j=0;j<n;++j)
printf("%d ",a[j][i]);
getch();
}
Output:
How many rows 2
How many columns 2
Enter the matrix: 1 2 3 4
1 2
3 4
Transpose of given matrix:
1 3
2 4
9. Check Whether the Given String is Palindrome or Not
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[15], b[15];
int i, j, length;
printf(“\n Enter the String : ”);
scanf(“%s”, a);
length = strlen(a);
j=0;
for ( i = length-1 ; i >= 0 ; i--)
{
b[j] = a[i];
j++;
}
b[j] = ’\0’;
if ( strcmp(a,b) == 0 )

Department of CSE Page 87


CS 3251 PROGRAMMING IN C 2023

printf(“The Given String is a Palindrome”);


else
printf( “The Given String is not a Palindrome”);
getch();
}
Output:
Enter the String: malayalam
The Given String is a Palindrome
10. Find the Reverse of a String
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char Str[20];
clrscr();
printf(“Enter the String :”);
scanf(“%s”, Str);
printf(“The Reversed String is %s”, strrev(Str) );
getch();
}
Output:
Enter the String : CSE
The Reversed String is ESC
11. Count the Number of Vowels in a String
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[200];
int i,vowels=0,consonants=0,digits=0,spaces=0,specialCharacters=0;
printf("Enter a string:\n");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||str[i]=='o' || str[i]=='u' || str[i]=='A' ||str[i]=='E'
|| str[i]=='I' || str[i]=='O' ||str[i]=='U')
{
vowels++;

Department of CSE Page 88


CS 3251 PROGRAMMING IN C 2023

}
else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z'))
{
consonants++;
}
else if(str[i]>='0' && str[i]<='9')
{
digits++;
}
else if (str[i]==' ')
{
spaces++;
}
else
{
specialCharacters++;
}
}
printf("\nVowels = %d",vowels);
printf("\nConsonants = %d",consonants);
printf("\nDigits = %d",digits);
printf("\nWhite spaces = %d",spaces);
printf("\nSpecial characters = %d",specialCharacters);
getch();
}
Output
Enter a string: geeks for geeks121
Vowels = 5
Consonant = 8
Digit =3
White spaces =2
Special Characters =0
12. Find the Largest and Smallest Number in the Given Array
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, temp, n, a[10];
printf("Enter the value of N \n");
scanf("%d", &n);

Department of CSE Page 89


CS 3251 PROGRAMMING IN C 2023

printf("Enter the numbers \n");


for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Large=%d”,a[n-1]);
printf(“Small=%d”,a[0]);
getch();
}
Output:
Enter the value of N :4
Enter the numbers
10 2 5 3
Large= 10
Small=2

Department of CSE Page 90


CS3251 PROGRAMMING IN C 2023

UNIT III FUNCTIONS AND POINTERS


Modular programming - Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion, Binary Search using recursive functions –
Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers –
Parameter passing: Pass by value, Pass by reference.

3.1 MODULAR PROGRAMMING


Modular programming is the process of subdividing a computer program into separate
sub-programs. A module is a separate software component. It can often be used in a variety of
applications and functions with other components of the system.

Some programs might have thousands or millions of lines and to manage such programs
it becomes quite difficult as there might be too many of syntax errors or logical errors present in
the program, so to manage such type of programs concept of modular programming approached.

Modular programming emphasis on breaking of large programs into small problems to


increase the maintainability, readability of the code and to make the program handy to make any
changes in future or to correct the errors.

FUNCTIONS
Function is defined as the block of organized, reusable code that is used to perform the
specific action. 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:
a) Based on who develops the function
b) Based on the function prototype
a) Based on the function prototype
Function prototype is a declaration statement that identify function with function name,
data type, a list of a arguments
b) Based on who develops the function
There are two types.
• Library functions
• User-defined functions

Department of CSE Page 91


CS3251 PROGRAMMING IN C 2023

Library(Pre-defined) function User defined function


Contains Pre-defined set of functions The user defined the functions
User cannot understand the internal User can understand internal working
working
Source code is not visible Source code is visible
User cannot modify the function User can modify the function
Example: printf( ), scanf( ). Example: sum() , square( )
Table 3.1: Library Vs User-defined function
Elements of user defined function (or) Steps in writing a function in a program
1. Function Declaration (Prototype declaration)
2. Function Call
3. Function Definition

3.2 FUNCTION PROTOTYPE


Function prototype is a declaration statement that identifies function with function name,
data type, a list of a arguments. All the function need to be declared before they are used. (i.e.
called)
Syntax:
returntype functionname (parameter list);

• Return type – data type of return value. It can be int, float, double, char, void etc.
• Function name – name of the function
• Parameter type list –It is a comma separated list of parameter types.
Example:
int add(int a, int b);
Function declaration must be terminated with a semicolon(;).
Types of function prototypes:
1. Function with no arguments and no return values
2. Function with arguments and no return values
3. Function with arguments and one return values
4. Function with no arguments and with return values
Prototype 1: Function with no arguments and no return values
• This function doesn’t accept any input and doesn’t return any result.
• These are not flexible.
Program
#include<stdio.h>
#include<conio.h>
void show(); //function prototype
void main()
{

Department of CSE Page 92


CS3251 PROGRAMMING IN C 2023

show( ); //function call


getch();
}
void show( ) //function definition
{
printf(“Hai \n”);
}
Output:
Hai
Prototype 2: Function with arguments and no return values
Arguments are passed through the calling function. The called function operates on the
values but no result is sent back.
Program
#include<stdio.h>
#include<conio.h>
void show(int);
void main()
{
int a;
printf(“Enter the value for a \n”);
scanf(“%d”, &a);
show(a);
getch();
}
void show(int x)
{
printf(“Value =%d”, x);
}
Output:
Enter the value for a: 10
Value = 10
Prototype 3: Function with arguments and return values
• Arguments are passed through the calling function
• The called function operates on the values.
• The result is returned back to the calling function.
Program
#include<stdio.h>
#include<conio.h>
float circlearea(int);
void main()

Department of CSE Page 93


CS3251 PROGRAMMING IN C 2023

{
int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r);
printf(“Area of a circle =%d\n”, area);
getch();
}
int circlearea(int r1)
{
return 3.14 * r1 * r1;
}
Output:
Enter the radius
2
Area of circle = 12.000
Prototype 4: Function with no arguments and with return values
• This function doesn’t accept any input and doesn’t return any result.
• The result is returned back to the calling function.
Program
#include<stdio.h>
#include<conio.h>
float circlearea();
void main()
{
float area;
area=circlearea();
printf(“Area of a circle =%d\n”, area);
getch();
}
int circlearea()
{
int r=2;
return 3.14 * r * r;
}
Output:
Enter the radius 2
Area of circle = 12.000

Department of CSE Page 94


CS3251 PROGRAMMING IN C 2023

3.3 FUNCTION DEFINITION


It is also known as function implementation. When the function is defined, space is
allocated for that function in memory.
Syntax
returntype functionname (parameter list)
{
statements;
return (value);
}
Example
int abc(int, int, int) // Function declaration
void main()
{
int x,y,z;
abc(x,y,z) // Function Call


}
int abc(int i, int j, int k) // Function definition
{
…….
….
return (value);
}
Every function definition consists of 2 parts:
a) Header of the function
b) Body of the function
a) Header of the function
The header of the function is not terminated with a semicolon. The return type and the
number & types of parameters must be same in both function header & function declaration.
Syntax:
returntype functionname (parameter list)

Where,
• Return type – data type of return value. It can be int, float, double, char, void etc.
• Function name – name of the function
• Parameter type list –It is a comma separated list of parameter types.
b) Body of the function
• It consists of a set of statements enclosed within curly braces.

Department of CSE Page 95


CS3251 PROGRAMMING IN C 2023

• The return statement is used to return the result of the called function to the
calling function.
Program:
#include<stdio.h>
#include<conio.h>
float circlearea(int); //function prototype
void main()
{
int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r); //function call
printf(“Area of circle =%f\n”, area);
getch();
}
float circlearea(int r1)
{
return 3.14 * r1 * r1; //function definition
}

Output:
Enter the radius
2
Area of circle = 12.000

3.4 FUNCTION CALL


Function call is used to invoke the function. So the program control is transferred to that
function. A function can be called by using its name & actual parameters.
Function call should be terminated by a semicolon ( ; ).
Syntax:
Functionname(argumentlist);
Example
int abc(int, int, int) // Function declaration
void main()
{
int x,y,z;
abc(x,y,z) // Function Call

Department of CSE Page 96


CS3251 PROGRAMMING IN C 2023

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


{
…….
….
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:
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.
Program:
#include<stdio.h>
#include<conio.h>
float circlearea(int); //function prototype
void main()
{
int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r); //function call
printf(“Area of a circle =%f\n”, area);
getch();
}
float circlearea(int r1)
{
return 3.14 * r1 * r1; //function definition
}
Output:
Enter the radius
2
Area of circle = 12.000

Department of CSE Page 97


CS3251 PROGRAMMING IN C 2023

3.5 BUILT IN FUNCTIONS (STRING FUNCTIONS, MATH FUNCTIONS):


Library functions are predefined functions. These functions are already developed by
someone and are available to the user for use.
3.5.1 MATHEMATICAL FUNCTIONS
These are defined in math.h header file. Math functions perform the mathematical
calculations. Some of the built-in math functions are,
S.No. Function & Description
1 double acos(double x)
Returns the arc cosine of x in radians.
2 double asin(double x)
Returns the arc sine of x in radians.
3 double atan(double x)
Returns the arc tangent of x in radians.
4 double atan2(double y, double x)
Returns the arc tangent in radians of y/x.
5 double cos(double x)
Returns the cosine of a radian angle x.
6 double cosh(double x)
Returns the hyperbolic cosine of x.
7 double sin(double x)
Returns the sine of a radian angle x.
8 double sinh(double x)
Returns the hyperbolic sine of x.
9 double tanh(double x)
Returns the hyperbolic tangent of x.
10 double exp(double x)
Returns the value of e raised to the xth power.
11 double frexp(double x, int *exponent)
The returned value is the mantissa and the integer pointed to by
exponent is the exponent. The resultant value is x = mantissa * 2 ^ exponent.
12 double ldexp(double x, int exponent)
Returns x multiplied by 2 raised to the power of exponent.
13 double log(double x)
Returns the natural logarithm (base-e logarithm) of x.
14 double log10(double x)
Returns the common logarithm (base-10 logarithm) of x.

Department of CSE Page 98


CS3251 PROGRAMMING IN C 2023

15 double modf(double x, double *integer)


The returned value is the fraction component (part after the decimal),
and sets integer to the integer component.

16 double pow(double x, double y)


Returns x raised to the power of y.

17 double sqrt(double x)
Returns the square root of x.

18 double ceil(double x)
Returns the smallest integer value greater than or equal to x.

19 double fabs(double x)
Returns the absolute value of x.

20 double floor(double x)
Returns the largest integer value less than or equal to x.

21 double fmod(double x, double y)


Returns the remainder of x divided by y.

Table 3.2: Mathematical Functions


Program:
#include<stdio.h>
#include <math.h>
#include<conio.h>
void main()
{
printf("\n%f",ceil(3.6));
printf("\n%f",ceil(6.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(7.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;
}

Department of CSE Page 99


CS3251 PROGRAMMING IN C 2023

Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
3.5.2 STRING FUNCTIONS
Library of String functions:
Header file:string.h
Example:
Functions Descriptions

strlen() Determines the length of a String

strcpy() Copies a String from source to destination

strcmp() Compares two strings

strlwr() Converts uppercase characters to lowercase

strupr() Converts lowercase characters to uppercase

String operations (length, compare, concatenate, copy) Refer Section 2.4 in pageno: 81.
strlwr() function
It converts all the uppercase characters in that string to lowercase characters.
Syntax
strlwr(string_name);
Example.
str[10]= “HELLO”;
strlwr(str);
puts(str);
Output:
hello
strupr() function
It converts all the lowercase characters in that string to uppercase characters.
Syntax
strupr(string_name);

Department of CSE Page 100


CS3251 PROGRAMMING IN C 2023

Example
str[10]= “HEllo”;
strupr(str);
puts(str);
Output:
HELLO
strrev() function
It is used to reverse the string.
Syntax
strrev(string_name);
Example
str[10]= “HELLO”;
strrev(str);
puts(str);
Output:
OLLEH
Program for string reverse:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main ()
{
char str[20] = “Computer”;
printf(“Given string = %s\n”, str);
printf (“The reverse string = %s”, strrev(str));
getch();
}
Output:
Given string = Computer
The reverse string = retupmoC
3.6 RECURSION
Recursion is defined as the function that calls itself repeatedly until condition is reached.
But while using recursion, programmers need to be careful to define an exit condition from the
function; otherwise it will go into an infinite loop.
Syntax:
Function1()
{
Function1();
}

Department of CSE Page 101


CS3251 PROGRAMMING IN C 2023

Example:
Calculating the factorial of a number
Fact (n)= n*fact(n-1);
6! = 6*fact(n);
6! = 6 *5*fact(4)
6! = 6 * 5 * 4 *fact(3)
6! = 6 * 5 * 4 * 3 *fact(2)
6! =6 *5 * 4 * 3 *2 * fact(1)
6! = 6 *5 * 4 * 3 *2 * 1
6!=120
Advantage of recursion
• Recursion makes program elegant and cleaner.
• All algorithms can be defined recursively which makes it easier to visualize and
prove.
• Reduce unnecessary calling of function
• Easy to solve complex problems
Direct Recursion:
A function is directly recursive if it calls itself.
A( )
{
….
A( ); // call to itself
….
}
Indirect Recursion:
Function calls another function, which in turn calls the original function.
A( )
{

B( );

}
B( )
{

A( );// function B calls A

}
Linear Recursion - It makes only one recursive call.
Binary Recursion - It calls itself twice.
N-ary recursion - It calls itself n times.

Department of CSE Page 102


CS3251 PROGRAMMING IN C 2023

Program 1 : Find factorial using recursion


#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n, Result;
printf(“\n Enter any number:”);
scanf(“%d”, &n);
Result = fact(n);
printf (“Factorial value = %d”, Result);
getch();
}
int fact (int x)
{
if (x == 0)
return 1;
else
return x * fact(x – 1);
}
Output:
Enter any number: 4
Factorial value = 24
Program 2 : Generate the Fibonacci Series Using Recursive Function
#include<stdio.h>
#include<conio.h>
int fib(int val);
void main ()
{
int i, n;
printf(“Enter the number”);
scanf (“%d”, &n);
printf(“\n Fibonacci sequence:”);
for (i = 0 , i < n, i++)
printf(“%d ”, fib(i));
getch();
}
int fib (int n)
{
if (n== 0)

Department of CSE Page 103


CS3251 PROGRAMMING IN C 2023

{
return 0;
}
else if (n == 1)
{
return 1;
}
else
return fib(n – 1) + fib (n– 2);
}
Output
Enter the number: 6
Fibonacci sequence : 0 1 1 2 3 5
Program 3 : Find the GCD of Two Positive Integer Numbers
#include<stdio.h>
#include<conio.h>
int gcd (int a, int b)
void main ()
{
int a, b;
printf(“\n Enter the two numbers:”);
scanf (“%d%d”, &a, &b);
printf(“\n The GCD of %d and %d is = %d”, a, b, gcd (a,b));
}

int gcd(int i, int j)


{
int remainder;
remainder = i %j;
if (remainder == 0)
return j;
else
return gcd (j, remainder);
}
Output:
Enter the two numbers: 48 18
The GCD of 48 and 18 is = 6
Program 4 : Towers of Hanoi Using Recursion
#include <stdio.h>
#include<conio.h>

Department of CSE Page 104


CS3251 PROGRAMMING IN C 2023

void towers(int, char,char,char);


void main()
{
int disk=3;
towers(disk, 'A', 'C', 'B');
getch();
}
void towers(int disk, char left, char right, char temp)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", left, right);
return;
}
towers(disk- 1, left, temp, right);
printf("\n Move disk %d from peg %c to peg %c", disk, left, right);
towers(num - 1, temp, right, left);
}
Output
Enter the number of disks : 3
The sequence of moves involved in the Tower of Hanoi are :
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C
3.7 BINARY SEARCH USING RECURSIVE FUNCTIONS
➢ Binary Search is a search algorithm that is used to find the position of an element (target
value ) in a sorted array.

➢ The array should be sorted prior to applying a binary search.

➢ Binary search is also known by these names, logarithmic search, binary chop, half
interval search.

Working
The binary search algorithm works by comparing the element to be searched by the
middle element of the array and based on this comparison follows the required procedure.

Department of CSE Page 105


CS3251 PROGRAMMING IN C 2023

Case 1 − element = middle, the element is found return the index.

Case 2 − element > middle, search for the element in the sub-array starting from middle+1 index
to n.

Case 3 − element < middle, search for element in the sub-array starting from 0 index to middle -
1.

Program:

/* BINARY SEARCH PROGRAM IN C USING RECURSION - BINARYSEARCH.C */


#include<stdio.h>
#include<stdlib.h>
#define size 10
int binsearch(int[], int, int, int);
int main()
{
int num, i, key, position;
int low, high, list[size];
printf("\nEnter the total number of elements");
scanf("%d", &num);
printf("\nEnter the elements of list :");
for (i = 0; i < num; i++)
{
scanf("%d", &list[i]);
}
low = 0;
high = num - 1;
printf("\nEnter element to be searched : ");
scanf("%d", &key);
position = binsearch(list, key, low, high);
if (position != -1)
{
printf("\nNumber present at %d", (position + 1));
}
else
printf("\n The number is not present in the list");
return (0);
}
/ Binary search function for binary search
int binsearch(int a[], int x, int low, int high)
{

Department of CSE Page 106


CS3251 PROGRAMMING IN C 2023

int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (x == a[mid])
{
return (mid);
}
else if (x < a[mid])
{
binsearch(a, x, low, mid - 1);
}
else
{
binsearch(a, x, mid + 1, high);
}
}
OUTPUT:
Enter the total number of elements 7
Enter the elements of list 10 21 32 43 54 65 76
Enter element to be searched 32
Number present at 3
3.8 POINTERS
Pointer is a variable that stores the address of a variable or a function. Pointer is a
derived data type. It is declared same as other variables but prior to variable name an asterisk ‘*’
operator is used.
Benefits of Pointers
• Reduce the length of the program.
• Support dynamic memory management.
• Pointers save memory space.
• More efficient in handling arrays.
• Execution speed increased.
• Used to return multiple values from a function.
Declaring a Pointer
The pointer variable is declared by using * operator.
syntax
datatype * pointervariable;

Example:
char *ptr;

Department of CSE Page 107


CS3251 PROGRAMMING IN C 2023

float *P1;
Pointer Initialization
The process of assigning the address of a variable to a pointer variable is known as
initialization. This is done through (&) ampersand operator.
Syntax:
Pointer variable = & variablename;
Example:
int n, *p;
p = &n;

3.9 POINTER OPERATORS


Pointer is a variable that stores the address of a variable or a function. There are 2 pointer
operators in C. They are,
1. Referencing operator
2. Dereferencing operator
Operator Operator Name Purpose

Dereferencing Operator
* OR Gives Value stored at Particular address
indirection operator

Referencing Operator
& OR Gives Address of Variable
address of (&) operator
Table 3.3: Pointer Operators
Referencing operator: (&)
& operator is a unary operator that returns the memory address of its operand. It is used
to find the address of variable For example, if var is an integer variable, then &var is its
address. Reference operator is also known as address of (&) operator.
Eg) float a=12.5;
float *p;
p=&a;

a 12.5
1000

P 1000
2000
Fig. 3.1: Pointer P Referencing the variable a

Department of CSE Page 108


CS3251 PROGRAMMING IN C 2023

Dereferencing operator
The second operator is indirection Operator *, and it is the complement of &. It is a unary
operator that returns the value of the variable located at the address specified by its operand. This
operator is also known as indirection operator or value- at-operator
Example

int b;
12 int a=12;
a int *p;
1000 p=&a;
b=*p; \\value pointed by p(or)value
1000 at 1000=12,
p so b=12
2000
Fig. 3.2: Pointer P Dereferencing the variable a
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int Mark = 73,
int *Ptr;
Ptr = &Mark;
printf(“The value of the variable Mark = %d \n”, *Ptr);
printf(“The address of the variable Mark = %d \n”, Ptr);
getch();
}

Output:
The value of the variable Mark = 73
The address of the variable Mark = 4082
For every execution time the compiler may allot the different memory. So, the address of
the variable may be different when we execute the program next time.
NULL Pointer
The pointer variable that is assigned NULL value is called Null pointer. NULL pointer is
a special pointer that does not point anywhere. It does not hold the address of any object or
function. It has numeric value 0
Example: for Null Pointer
int *ptr = 0;

Department of CSE Page 109


CS3251 PROGRAMMING IN C 2023

( or )
int *ptr = NULL;
Use of null pointer:
• As an error value
• As a sentinel value
• To stop indirection in a recursive strucure
3.10 POINTER ARITHMETIC
Pointer is a variable that stores the address of a variable or a function.
Valid operation
• Pointer can be added with a constant
• Pointer can be subtracted with a Constant
• Pointer can be Incremented or Decremented
Not Valid operation
• Two pointers cannot be added
• Two pointers cannot be subtracted
• Two pointers cannot be multiplied
• Two pointers cannot be divided
Example:
int a=10
int *p=&a;
p=p+1;
• The pointer holds the address 2000. This value is added with 1.
• The data type size of the constant is added with the address. p= 2000+(2*1)=2002
The following table shows the pointer arithmetic.
S.no Operator Type of Type of Result Example Initial Final Description
operand 1 operand 2 type value value
1 Addition (+) Pointer to int Pointer Result =
type T to type initial value
T of ptr +int
operand *
sizeof (T)

Eg. int * int int * p=p+5 p=2000 2010 2000+5*2=


2010

Department of CSE Page 110


CS3251 PROGRAMMING IN C 2023

2 Increment Pointer to Pointer Post


(++) type T - to type increment
T Result =
initial value
of pointer

Pre-
increment
Result =
initial value
of pointer +
sizeof (T)
Eg. post float* - float* ftr=p++ ftr=? ftr=2000
increment p=2000 p=2004 Value of ptr =
Value of ptr
+sizeof(T)
3 Subtraction Pointer to int Pointer Result =
- type T to type initial value
T of ptr - int
operand *
sizeof (T)
E.g. float* int float* p=p-1 p=2000 1996 2000 – 1 * 4
= 2000-
4=1996
4 decrement Pointer to Pointer Post
type T - to type decrement
T Result =
initial value
of pointer
Pre-
decrement
Result =
initial value
of pointer –
sizeof(T)

Eg.pre float* - float* ftr=--p ftr=? ftr=1996 Value of ptr =


decrement p=2000 p=1996 Value of ptr –
sizeof(T)
Table 3.4: Pointer Arithmetic

Department of CSE Page 111


CS3251 PROGRAMMING IN C 2023

Program : Addition of Integers with Pointer


#include<stdio.h>
#include<conio.h>
void main ()
{
int a[5] = {10, 5, 20, 5, 2};
int i, sum = 0
for (i = 0; i < 5; i++)
sum = sum+*(a + i);
printf (“Total = %d”, sum);
getch();
}
Output:
Total = 42
Program : Subtraction of Pointers
#include<stdio.h>
#include<conio.h>
void main ()
{
double a[2], *p, *q;
p = a; // Assign a[0] address to p
q = p + 1; // Assign a[1] address to q
printf(“No. Of elements between p & q = %d”, q - p);
getch();
}
Output:
No. Of elements between p & q = 2
3.11 ARRAYS AND POINTERS
Array is a group of homogeneous data stored sequentially in memory. Pointer is a
variable that stores the address of a variable or a function. Pointers & arrays are having close
relationship. An array name itself is an address or pointer. It points to the address of first
element (0th element) of an array.
i) Array name itself is an address or pointer
It means array name itself is the address of first element. If there is an array with a name
Mark then &Mark[0] and Mark represent the first element address. Similarly, Mark + k and
&Mark[k] refer the address of element k in Mark array.
Program
#include<stdio.h>
void main()
{

Department of CSE Page 112


CS3251 PROGRAMMING IN C 2023

int a[3]={10,15,20};
printf(“First element of array is at %u\n”, a);
printf(“2nd element of array is at %u\n”, a+1);
printf(“3nd element of array is at %u\n”, a+2); 1000 1002 1004
}
Output 10 15 20
First element of array is at 1000
2nd element of array is at 1002
3nd element of array is at 1004
ii) Operation in array done by using pointers in c language.
Any operation that involves array subscripting is done by using pointers in c language.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3]={10,15,20};
printf(“Elements are %d %d %d\n”, a[0],a[1],a[2]);
printf(“Elements are %d %d %d\n”, *(a+0),*(a+1),*(a+2);
getch();
}
Output:
Elements are 10 15 20
Elements are 10 15 20

3.12 ARRAY OF POINTERS


Array is a group of homogeneous data stored sequentially in memory. Pointer is a
variable that stores the address of a variable or a function. Array of pointer can be declared as
datatype *ptrname[size];
Example:
int a=10,b=20,c=30;
int *b[3]={&a,&b,&c};
a b c
10 20 30
4000 4100 4400

b 4000 4100 4400

5000 5002 5004

Fig 3.3: Array of Pointers

Department of CSE Page 113


CS3251 PROGRAMMING IN C 2023

Program
#include <stdio.h>
#include<conio.h>
void main()
{
int num = 10;
int score = 12;
int run = 123;
int goal = 3;
int *ptr[4];
ptr[0] = &num;
ptr[1] = &score;
ptr[2] = &run;
ptr[3] = &goal;
printf("num: %d\n", *ptr[0]);
printf("score: %d\n", *ptr[1]);
printf("run: %d\n", *ptr[2]);
printf("goal: %d\n", *ptr[3]);
getch();
}
Output
num: 10
score: 12
run: 123
goal: 3

3.13 PARAMETER PASSING


In C language, there are two methods for parameter passing. They are,
 Call by Value or Pass by Value
 Call by Reference or Pass by Reference

Call by Value Call by Reference

Values of actual arguments are passed to formal Address of actual arguments is passed to formal
arguments. arguments.

Actual & formal parameters refer different location Actual & formal parameters refer same location

Changes made in formal parameters not reflected Changes made in formal parameters reflected
back to the calling function back to the calling function

There is no Possibility of Wrong Data Manipulations There is a Possibility of Wrong Data


Manipulations

Table 3.5: Call by Value Vs Call by Reference

Department of CSE Page 114


CS3251 PROGRAMMING IN C 2023

3.13.1 Call by Value (Pass by Value)

While calling a function, the values of actual parameters are passed to the formal
parameters. Therefore the called function works on the copy and not on original values of actual
parameters.
When arguments are passed by value, C allocates separate memory for formal arguments
and copy the actual argument value in that location. Therefore the changes made on formal
parameters will not affect the actual parameter.
Syntax for call by value:
functionname(arguments list);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf(“\n In Swap, x=%d and y=%d”, x,y);
}
Output:
Before swapping: a =10 and b =20
In Swap, x=20 and y=10
After swapping: a =10 and b = 20
Explanation:
In the above program, before calling the swap function, the value of a is 10 and the value
of b is 20. During the function call, the values of a and b are passed to x and y. In the swap
function, the values of x and y are swapped. Now, x has the value 20 and y has the value 10. But
this change does not get reflected in the value of a and b.

Department of CSE Page 115


CS3251 PROGRAMMING IN C 2023

Main function
a b

10 20

1000 1002
Swap function
x 20 y
10

2000 2002
After swap function
x y

20 10

2000 2002
Fig 3.4 : Call by Value - example program
3.13.2 Call by Reference (Pass by Reference)
In this method, the address of the actual argument, in the calling function are copied into
the formal arguments of the called function. That is the actual & formal arguments refer same
memory location. Therefore the changes made on formal parameters will affect the actual
parameter of the calling function.
Example:
#include<stdio.h>
#include<conio.h>
void swap(int *, int *)
void main()
{
int a = 10, b = 20;
printf(“Before swap a = %d, b = %d \n”, a,b);
swap (&a, &b);
printf(“After swap a = %d, b = %d”, a, b);
getch();
}
void swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;

Department of CSE Page 116


CS3251 PROGRAMMING IN C 2023

*y = temp;
printf(“\n In Swap, x=%d and y=%d”, *x,*y);
}
Output:
Before swap a = 10, b = 20
In Swap, x=20 and y=10
After swap a = 20, b = 10
Explanation:
In the above program, before calling the swap function, the value of a is 10 and the value
of b is 20. During the function call, the references of a and b are passed to x and y. In the swap
function, the values of x and y are swapped. Now, x has the value 20 and y has the value 10. This
change gets reflected in the value of a and b.

Main function
a b

10 20

1000 1002
Swap function
x 20 y
10

1000 1002
After swap function
20 x y10

1000 1002
Fig 3.5 : Call by Reference - example program

Department of CSE Page 117


CS3251 PROGRAMMING IN C 2023

PART A (2 Marks with Answers)


1. List advantage of recursion. (APRIL/MAY 2018)
• Recursion makes program elegant and cleaner.
• All algorithms can be defined recursively which makes it easier to visualize and
prove.
• Reduce unnecessary calling of function
• Easy to solve complex problems
2. What is null pointer? When null pointer is used? (APRIL/MAY 2018)
The pointer variable that is assigned NULL value is called Null pointer. NULL pointer is
a special pointer that does not point anywhere. It has numeric value 0
Example: for Null Pointer
int *ptr = 0;
Use of null pointer:
• As an error value
• As a sentinel value
• To stop indirection in a recursive strucure
3. What is a function?
Function is defined as the block of organized, reusable code that is used to perform the
specific action. A function is a subprogram of one or more statements that performs a specific
task when called. There are two types of functions.
• Library functions
• User-defined functions
4. What is the need for functions?
• Code reusability
• Better readability
• Reduction in code redundancy
• Easy to debug & test.
• To reduce the complexity of large programs
• To save Memory
5. What are the uses of pointer?
• Reduce the length of the program.
• Support dynamic memory management.
• Pointers save memory space.
• More efficient in handling arrays.
• Execution speed increased.
• Used to return multiple values from a function.

6. What are pointer operators in C?

Department of CSE Page 118


CS3251 PROGRAMMING IN C 2023

Operator Operator Name Purpose

Dereferencing Operator (or)


* Gives Value stored at Particular address
indirection operator

Referencing Operator (or)


& Gives Address of Variable
address of (&) operator
7. Compare actual parameter & formal argument
• Actual parameter: Specified in the function call statement. Used to supply the input
values to the function either by copy or reference
• Formal argument: Specified in the function definition statement. It takes either copy or
address of the actual arguments
void main()
{
area=circlearea(r); // Actual parameter
}
int circlearea(int r1) // Formal argument
{
}
8. How is pointer arithmetic done?
Valid operation
• Pointer can be added with a constant
• Pointer can be subtracted with a Constant
• Pointer can be Incremented or Decremented
Not Valid operation
• Two pointers cannot be added
• Two pointers cannot be subtracted
• Two pointers cannot be multiplied
• Two pointers cannot be divided
9. List out any 4 math functions
S.No. Function & Description

1. double cos(double x)
Returns the cosine of a radian angle x.

2. double sin(double x)
Returns the sine of a radian angle x.

3. double exp(double x)

Department of CSE Page 119


CS3251 PROGRAMMING IN C 2023

Returns the value of e raised to the xth power.

4. double log(double x)
Returns the natural logarithm (base-e logarithm) of x.

5. double pow(double x, double y)


Returns x raised to the power of y.

6. double sqrt(double x)
Returns the square root of x.
10. What is a function prototype?
Function prototype is a declaration statement that identifies function with function name,
data type, a list of a arguments. All the function need to be declared before they are used. (i.e.
called).
Syntax:
returntype functionname (parameter 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.
Example:
int add(int a, int b);
11. Differentiate call by value and call by reference.
In C language, there are two methods for parameter passing. They are,
 Call by Value or Pass by Value
 Call by Reference or Pass by Reference
Call by Value Call by Reference

Values of actual arguments are passed to formal Address of actual arguments is passed to
arguments. formal arguments.

Actual & formal parameters refer different Actual & formal parameters refer same
location location
Changes made in formal parameters not Changes made in formal parameters
reflected back to the calling function reflected back to the calling function

There is no Possibility of Wrong Data There is a Possibility of Wrong Data


Manipulations Manipulations

Department of CSE Page 120


CS3251 PROGRAMMING IN C 2023

12. What are types of function prototypes?


1. Function with no arguments and no return values
2. Function with arguments and no return values
3. Function with arguments and one return values
4. Function with no arguments and with return values
13. What are the elements of user defined function?
1. Function Declaration (Prototype declaration)
2. Function Calls
3. Function Definition
14. State the advantages of user defined functions over pre-defined function.
Library(Pre-defined) function User defined function
Contains Pre-defined set of functions The user defined the functions
User cannot understand the internal User can understand internal working
working
Source code is not visible Source code is visible
User cannot modify the function User can modify the function

15. Write the disadvantages of recursion.


• If the speed of the program is vital then, you should avoid using recursion.
• Recursions use more memory and are generally slow. Instead, you can use loop.
16. What is meant by Recursion?
Recursion is defined as the function that calls itself repeatedly until condition is reached.
But while using recursion, programmers need to be careful to define an exit condition from the
function; otherwise it will go into an infinite loop.
Syntax:
Function1()
{
Function1();
}
Example:
Calculating the factorial of a number:
Fact (n)= n*fact(n-1);
17. What is mean by pointer? How it is declared?
Pointer is a variable that stores the address of a variable or a function. Pointer is a derived
data type. It is declared same as other variables but prior to variable name an asterisk ‘*’ operator
is used.
Syntax :
datatype * pointervariable;
Example:
char *ptr;

Department of CSE Page 121


CS3251 PROGRAMMING IN C 2023

18. When array of pointers is used?


Array is a group of homogeneous data stored sequentially in memory. Pointer is a
variable that stores the address of a variable or a function. Array of pointer can be declared as,
datatype *ptrname[size];
Example:
int a=10,b=20,c=30;
int *b[3]={&a,&b,&c};
19. Write the syntax for function call and function definition

Syntax for function call


Functionname(argumentlist);
Syntax for function definition

returntype functionname (parameter list)

statements;

return (value);

20. What is the difference between Array and Pointer?


Array Pointer
Array allocates space automatically Pointer is explicitly assigned to point to an
allocated space
It cannot be resized It can be resized using realloc()
It cannot be reassigned It can be reassigned
Size of array name gives the number of bytes Size of pointer name returns the number of
occupied by the array pointer used to store the pointer variable.

PART B (Possible Questions)


1. i) Explain the purpose of a function prototype. And specify the difference between user
defined function and built-in-function (8) (APRIL/MAY 2018)
ii) Write the program to find the value of sin(x) using series up to the given accuracy and also
print the sin(x) using library function (5)
2. What is the difference between pass by value and pass by reference? Write the C coding for
swapping two numbers using pass by reference (13) (APRIL/MAY 2018)
3. Describe about pointers and their operations that can be performed on it.
4. What is an array of pointers and what is pointer to an array? Explain in detail with example

Department of CSE Page 122


CS3251 PROGRAMMING IN C 2023

5. Demonstrate about function declaration, function definition and function call.


6. Discuss about the classification of functions depending upon their inputs and output (parameters)
7. Explain in detail about Pass by Value and Pass by reference.
8. Explain in detail about recursive function with sample code.
9. Explain any six built in functions of string and math.

PART C (Possible Questions)


1. Write a C program for designing Scientific calculator using built-in functions
2. Write a C program for Swapping of two numbers and changing the value of a variable
using pass by reference.
3. i) Write a C program to sort the given N names given by user.

ii) Write notes on formal and actual argument functions.


4. Write a C program for Binary Search using recursive functions

5. i) Write a C program for Computation of Sine series.

ii) Summarize the difference between array and pointer.

6. Discuss about passing arrays to function.


7. Write the C program to accept two strings by user and concatenate them and display string to
user.
8. Write the C program to compute square root of a number.
9. Write the C program to accept two numbers by user , compute power and display result to user.
Otherwise display error to user.
10. Write the program to find the value of sin(x) using library function.

Department of CSE Page 123


CS3251 PROGRAMMING IN C 2023

ADDITIONAL PROGRAMS
1. Computation of sine series:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
float x, sum, t;
printf(" Enter the value for x : ");
scanf("%f",&x);
printf(" Enter the value for n : ");
scanf("%d",&n);
x=x*3.14159/180;
t=x;
sum=x;
/* Loop to calculate the value of Sine */
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf(" The value of Sin(%f) = %.4f",x,sum);
getch();
}
Output:
Enter the value for x :45
Enter the value for n: 5
The value of Sin(0.7853980 = 0.7071
2. Scientific calculator using built-in functions:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int choice, i, a, b;
float x, y, result;
do
{
printf(“\nSelect your operation (0 to exit):\n”);
printf(“1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n”);

Department of CSE Page 124


CS3251 PROGRAMMING IN C 2023

printf(“5. Square root\n6. X ^ Y\n7. X ^ 2\n8. X ^ 3\n”);


printf(“9. 1 / X\n10. X ^ (1 / Y)\n11. X ^ (1 / 3)\n”);
printf(“12. 10 ^ X\n13. X!\n14. %\n15. log10(x)\n16. Modulus\n”);
printf(“17. Sin(X)\n18. Cos(X)\n19. Tan(X)\n20. Cosec(X)\n”);
printf(“21. Cot(X)\n22. Sec(X)\n”);
printf(“Enter your Choice: “);
scanf(“%d”, &choice);
if(choice == 0)
exit(0);
switch(choice)
{
case 1:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x + y;
printf(“\nResult: %f”, result);
break;
case 2:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x – y;
printf(“\nResult: %f”, result);
break;
case 3:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x * y;
printf(“\nResult: %f”, result);
break;
case 4:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);

Department of CSE Page 125


CS3251 PROGRAMMING IN C 2023

result = x / y;
printf(“\nResult: %f”, result);
break;
case 5:
printf(“Enter X: “);
scanf(“%f”, &x);
result = sqrt(x);
printf(“\nResult: %f”, result);
break;
case 6:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = pow(x, y);
printf(“\nResult: %f”, result);
break;
case 7:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, 2);
printf(“\nResult: %f”, result);
break;
case 8:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, 3);
printf(“\nResult: %f”, result);
break;
case 9:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, -1);
printf(“\nResult: %f”, result);
break;
case 10:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);

Department of CSE Page 126


CS3251 PROGRAMMING IN C 2023

result = pow(x, (1/y));


printf(“\nResult: %f”, result);
break;
case 11:
printf(“Enter X: “);
scanf(“%f”, &x);
y = 3;
result = pow(x, (1/y));
printf(“\nResult: %f”, result);
break;
case 12:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(10, x);
printf(“\nResult: %f”, result);
break;
case 13:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1;
for(i = 1; i <= x; i++)
{
result = result * i;
}
printf(“\nResult: %.f”, result);
break;
case 14:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = (x * y) / 100;
printf(“\nResult: %.2f”, result);
break;
case 15:
printf(“Enter X: “);
scanf(“%f”, &x);
result = log10(x);
printf(“\nResult: %.2f”, result);
break;

Department of CSE Page 127


CS3251 PROGRAMMING IN C 2023

case 16:
printf(“Enter X: “);
scanf(“%d”, &a);
printf(“\nEnter Y: “);
scanf(“%d”, &b);
result = a % b;
printf(“\nResult: %d”, result);
break;
case 17:
printf(“Enter X: “);
scanf(“%f”, &x);
result = sin(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 18:
printf(“Enter X: “);
scanf(“%f”, &x);
result = cos(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 19:
printf(“Enter X: “);
scanf(“%f”, &x);
result = tan(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 20:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / (sin(x * 3.14159 / 180));
printf(“\nResult: %.2f”, result);
break;
case 21:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / tan(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 22:
printf(“Enter X: “);

Department of CSE Page 128


CS3251 PROGRAMMING IN C 2023

scanf(“%f”, &x);
result = 1 / cos(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
default:
printf(“\nInvalid Choice!”);
}
} while(choice);
getch();
}
Output
Select your operation (0 to exit):\n”);
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square root
6. X ^ Y
7. X ^ 2
8. X ^ 3
9. 1 / X
10. X ^ (1 / Y)
11. X ^ (1 / 3)
12. 10 ^ X
13. X!
14. %
15. log10(x)
16. Modulus
17. Sin(X)
18. Cos(X)
19. Tan(X)
20. Cosec(X)
21. Cot(X)
22. Sec(X)
Enter your Choice: 3
Enter x: 4
Enter y: 5
Result= 20

Department of CSE Page 129


CS3251 PROGRAMMING IN C 2023

3. Binary search using recursive functions:


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

Department of CSE Page 130


CS3251 PROGRAMMING IN C 2023

}
else
{
printf("\nElement %d Found at Position %d\n", element, position + 1);
}
getch();
}
Output:
Enter the Limit of Elements in Array: 5
Enter 5 Elements in Array:
1 2 3 4 5
Enter Element To Search:3
Element 3 Found at Position 3
4. Sorting of names
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include<conio.h>
static int myCompare (const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char **) b);
}
void sort(const char *arr[], int n)
{
qsort (arr, n, sizeof (const char *), myCompare);
}
void main ()
{
const char *arr[] = {"computer", "science", "Language"};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
printf("Given array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
sort(arr, n);
printf("\nSorted array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
getch();
}

Department of CSE Page 131


CS3251 PROGRAMMING IN C 2023

Output
Given array is
0: computer
1: science
2: Language
Sorted array is
0: computer
1: Language
2: Language
5. Changing the value of a variable using pass by reference
#include<stdio.h>
#include<conio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
Output:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10
6. Check a given string is palindrome or not
# include<stdio.h>
#include<string.h>
#include<conio.h>
void main ()
{

Department of CSE Page 132


CS3251 PROGRAMMING IN C 2023

int diff;
char input[20], copy[20];
printf (“Enter input string :”);
scanf (“%s”, input);
strupr(input); // convert into upper case letter
strcpy(copy, input); // take a copy of the input string
strrev(copy); // reverse the input string
diff = strcmp(input, copy); //compare input & reverse copy
if(diff == 0)
printf (“Given String is a palindrome”);
else
printf(“Given string is not a palindrome”);
getch();
}
Output:
`Enter input string: malayalam
Given string is a palindrome
7. Sum of Natural Numbers Using Recursion
#include <stdio.h>
#include<conio.h>
int addNumbers(int n);
void main()
{
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Sum = %d",addNumbers(num));
getch();
}
int addNumbers(int n)
{
if(n != 0)
return n + addNumbers(n-1);
else
return n;
}
Output:
Enter a positive integer: 20
Sum = 210

Department of CSE Page 133


CS3251 PROGRAMMING IN C 2023

8. Calculate power using recursion


#include <stdio.h>
#include<conio.h>
int power(int n1, int n2);
int main()
{
int base, powerRaised, result;
printf("Enter base number: ");
scanf("%d",&base);
printf("Enter power number(positive integer): ");
scanf("%d",&powerRaised);
result = power(base, powerRaised);
printf("%d^%d = %d", base, powerRaised, result);
return 0;
}
int power(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*power(base, powerRaised-1));
else
return 1;
}
Output:
Enter base number: 3
Enter power number(positive integer): 4
3^4 = 81

Department of CSE Page 134


CS3251 PROGRAMMING IN C 2023

UNIT IV
STRUCTURES AND UNION
Structure - Nested structures – Pointer and Structures – Array of structures – Self referential
structures – Dynamic memory allocation - Singly linked list – typedef – Union - Storage classes
and Visibility.

4.1 STRUCTURE

Structure is a user defined data type that allows you to hold different data type of
elements. Each element in the structure is called as member. It is used to store student
information, employee information, product information, book information etc.
Defining structure

A structure is a collection of variables of different types under a single name. It is


used for storing different types of data.
A structure is declared by using the keyword ‘struct’ . The members of the structure are
defined within the body of the structure.
Syntax:
struct structurename
{
Datatype member1;
Datatype member2;
. . .
Datatype member n;
} structurevariable1, structurevariable2, . . . structurevariablen;
Example:
struct student
{
int RegNo;
char name[20], dept[10];
}S1, S2;
Here, student’ is a structure name, S1 & S2 are structure variables and RegNo, name and
dept are structure members.
4.1.1 Declaring structure
We can declare variable for the structure, so that we can access the member of structure
easily. There are two ways to declare structure variable:
1. By using struct keyword within main() function
2. By declaring variable at the time of defining structure.
Method1:
It should be declared within the main function.

Department of CSE Page 135


CS3251 PROGRAMMING IN C 2023

struct employee
{
int id;
char name[50];
float salary;
};
void main
{
struct employee e1, e2;
}
Method2:
Declare the variable of the structure at the time of defining the structure.
struct employee
{
int id;
char name[50];
float salary;
}e1,e2;
Which approach is good
• If no. of variable are not fixed, use method1. It provides you flexibility to declare the
structure variable many times.
• If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in
main() fuction.
Accessing members of structure
There are two ways to access structure members:
1. By using . (member or dot operator)
2. By using -> (structure pointer operator)

Syntax:
structurevariable.membername
structurevariable→membername
Example:
S1.name
S1→name
4.1.2 Initialization of Structure
Like normal variables, the structure variables can also be initialized. A structure is
initialized by assigning some constants to the members of the structure. By default, the members
of type int and float are initialized to zero and the members of type char and string are initialized
to ‘\0’

Department of CSE Page 136


CS3251 PROGRAMMING IN C 2023

Method 1
struct student
{
int Reg_No;
char name[20];
}S1 = {4001, “Joshna”};
Method 2
struct student
{
int Reg_No;
char name[20];
};
void main()
{
struct student S1 = {4001, “Joshna”};
}
Program: Store student Information and Display it Using Structure
#include <stdio.h>
#include<conio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;
void main()
{
printf("Enter student information:\n");
printf("Enter student name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("Displaying Information:\n");
printf("Name: %s\n”,s.name);
printf("Roll number: %d\n",s.roll);
printf("Marks: %f\n", s.marks);
getch();
}
Department of CSE Page 137
CS3251 PROGRAMMING IN C 2023

Output
Enter information:
Enter name: Jack
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Jack
Roll number: 23
Marks: 34.5

4.2 NESTED STRUCTURES


A structure can be placed within another structure is called nesting of structures.
Structures can contain other structures as members. Nested structure is also called as structure
within structure.
Declaration of nested structure
There are two ways to declare nested structure in c language:
a) By separate structure
b) By Embedded structure
a) Separate structure
We can create 2 structures, but dependent structure should be used inside the main
structure as a member.
Syntax
struct structure1
{
----------
----------
};
struct structure2
{
----------
----------
struct structure1 v1;
}v2;
Example
struct Date
{
int dd;
int mm;
int yyyy;
};
Department of CSE Page 138
CS3251 PROGRAMMING IN C 2023

struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
b) Embedded structure
We can define structure within the structure also. It requires less code than previous way.
But it can't be used in many structures.
Syntax:
struct structure1
{
---
---
struct structure2
{
---
---
---
} v1;
}v2;
Example
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp;
Accessing Nested Structure
We can access the member of nested structure by Outer Structure. Nested Structure
members are accessed using dot operator.
Here, Date‘ structure is nested within Employee Structure. Members of the ‘Date‘ can be
accessed using ’employee’. emp1 & doj are two structure names (Variables)
• Accessing Month Field : emp1.doj.month
• Accessing day Field : emp1.doj.day
Department of CSE Page 139
CS3251 PROGRAMMING IN C 2023

• Accessing year Field : emp1.doj.year


Program
#include <stdio.h>
#include<conio.h>
struct Employee
{
char name[20];
int no;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp;
void main()
{
printf("\nEnter Employee Name : ");
scanf(“%s”,&emp.name);
printf(“Employee number:”);
scanf(“%d”,& emp.no);
printf("\nEmployee Salary : “);
scanf(“%f",&emp.salary);
printf("\nEmployee DOJ : “);
sacnf(“%d/%d/%d", &emp.doj.date,&emp.doj.month,&emp.doj.year);
printf(“*******Employee information”);
printf("\nEmployee Name : %s",emp.name);
printf("\nEmployee Number : %d",emp.no);
printf("\nEmployee Salary : %f",emp.salary);
printf("Employee DOJ: %d/%d/%d",emp.doj.date,emp.doj.month, emp.doj.year );
getch();
}
Output :
Employee Name : Jayden
Employee Number : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990

Department of CSE Page 140


CS3251 PROGRAMMING IN C 2023

4.3 POINTER AND STRUCTURES


Structure is a user defined data type that allows you to hold different data type of
elements. Structures can be created and accessed using pointers. A pointer variable of a structure
can be created as below:
Syntax:
struct structurename
{
Datatype member1;
Datatype member2;
. . .
Datatype member n;
} *ptr;
(or)
struct structurename
{
Datatype member1;
Datatype member2;
. . .
Datatype member n;
};
void main()
{
struct structurename *ptr;
}
Accessing the members of a structure by pointer
We use the arrow operator -> ( member selection operator) to access the members of a
structure via pointer variable.
Syntax
ptrName->member
Example
printf("First Name: %s", ptr->firstname);
Assigning structure variable to pointer
We use the following syntax to assign a structure variable address to a pointer.
ptrName = &structVarName;
In the following example we are assigning the address of the structure variable std to the
structure pointer variable ptr. So, ptr is pointing at std.
Example
ptr = &std;

Department of CSE Page 141


CS3251 PROGRAMMING IN C 2023

Program:
#include <stdio.h>
#include <conio.h>
struct student
{
char name[50];
int roll;
float marks;
}s;
void main()
{
struct student *ptr;
ptr = &s;

printf("Enter student information:\n");


printf("Enter student name: ");
scanf("%s", &ptr→name);
printf("Enter roll number: ");
scanf("%d", &ptr→roll);
printf("Enter marks: ");
scanf("%f", &ptr→marks);
printf("Displaying Information:\n");
printf("Name: %s\n”,ptr→name);
printf("Roll number: %d\n",ptr→roll);
printf("Marks: %f\n", ptr→marks);
getch();
}
Output
Enter student information:
Enter student name: Jacks
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Jacks
Roll number: 23
Marks: 34.5
4.4 ARRAY OF STRUCTURES
The array of structures is used to store information about multiple entities of different
data types. The array of structures is also known as the collection of structures. An array of

Department of CSE Page 142


CS3251 PROGRAMMING IN C 2023

structures in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities.
Syntax
struct structname
{ Datatype member1;
Datatype member2;
. . .
Datatype member n;
}arrayname[ size];
struct structurename
{ Datatype member1;
Datatype member2;
. . .
Datatype member n;
};
void main()
{
struct structurename arrayname[size];
}
Example
struct student
{ int rollno;
float marks;
}s[2];

s[1] s[2]

int rollno float marks int rollno float marks

Fig 4.1: Array of Structures for student structure


Program
#include<stdio.h>
#include <conio.h>
struct student
{
int rollno;
char name[10];
};

Department of CSE Page 143


CS3251 PROGRAMMING IN C 2023

void main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
getch();
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonu
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Raja
Student Information List:
Rollno:1, Name:Sonu
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Raja

Department of CSE Page 144


CS3251 PROGRAMMING IN C 2023

4.5 SELF REFERENTIAL STRUCTURES


Self Referential structures are those structures that have one or more pointers which point
to the same type of structure, as their member. In other words, structures pointing to the same
type of structures are self-referential in nature.
Syntax:
struct structname
{
Datatype member1;
Datatype member2;
. . .
Datatype member n;
};
Example:
struct node
{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
Types of Self Referential Structures
• Self Referential Structure with Single Link
• Self Referential Structure with Multiple Links
Self Referential Structure with Single Link: These structures can have only one self-pointer as
their member. The following example will show us how to connect the objects of a self-
referential structure with the single link and access the corresponding data members. The
connection formed is shown in the following figure.

10 20 30 40 X
ob1 ob2
Fig 4.2: Self Referential Structure with Single Link
Program
#include <stdio.h>
#include<conio.h>
struct node

Department of CSE Page 145


CS3251 PROGRAMMING IN C 2023

{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1

// Intialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
getch();
}
Output:
30
40
Self Referential Structure with Multiple Links:
Self referential structures with multiple links can have more than one self-pointers. Many
complicated data structures can be easily constructed using these structures. Such structures can
easily connect to more than one nodes at a time. The following example shows one such
structure with more than one links.

X 10 20
30
ob1 ob2 ob3
Fig 4.3: Self Referential Structure with Multiple Links

Department of CSE Page 146


CS3251 PROGRAMMING IN C 2023

Applications:
Self referential structures are very useful in creation of other complex data structures like:
• Linked Lists
• Stacks
• Queues
• Trees
• Graphs etc

4.6 DYNAMIC MEMORY ALLOCATION


The process of allocating memory at the time of execution or at the runtime is called
dynamic memory allocation. It means dynamically allocate only the amount of memory needed.
The program must include <stdlib.h> to support the dynamic memory allocation.
The comparison between Static memory allocation and Dynamic memory allocation is
given below:
Static memory allocation Dynamic memory allocation
Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while executing Memory can be increased while executing
program. program.
Used in array. Used in linked list.
Table 4.1: Static memory allocation Vs Dynamic memory allocation
Need of Dynamic Memory Allocation
• Sometimes amount of data cannot be predicted beforehand
• Number of data items keeps changing during program execution
Memory Allocation Functions
1. malloc( )
Allocates requested number of bytes (block of memory) and returns a pointer to
the first byte of the allocated space
2. calloc( )
Allocates space for an array of elements, initializes them to zero and then returns
a pointer to the memory.
3. free( )
Frees previously allocated space.
4. realloc( )
Modifies the size of previously allocated space.
4.6.1. malloc( )
A block of memory can be allocated using the function malloc.
Syntax
type *p;
p = (type *) malloc (byte_size);

Department of CSE Page 147


CS3251 PROGRAMMING IN C 2023

Example
p = (int *) malloc(100 * sizeof(int));
A memory space equivalent to 100 times the size of an int bytes is reserved. The
address of the first byte of the allocated memory is assigned to the pointer p of type int.

400 bytes of space


Fig 4.4: memory allocation using malloc( )
• cptr = (char *) malloc (20);
Allocates 20 bytes of space for the pointer cptr of type char
• sptr = (struct stud *) malloc(10*sizeof(struct stud));
Allocates space for a structure array of 10 elements. sptr points to a structure
element of type struct stud.
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);

Department of CSE Page 148


CS3251 PROGRAMMING IN C 2023

free(ptr);
getch();
}
Output:
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
4.6.2 calloc( )
Allocates space for an array of elements, initializes them to zero and then returns a
pointer to the memory.
Synatx:
ptr=(cast-type*)calloc(number, byte-size)
Example:
int *ptr = calloc(10, sizeof (int));

Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
Department of CSE Page 149
CS3251 PROGRAMMING IN C 2023

getch();
}
Output:
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
Diffrence between malloc() and calloc()
calloc() malloc()
calloc() initializes the allocated memory with 0 malloc() initializes the allocated memory with
value. garbage values.
Number of arguments is 2 Number of argument is 1
Syntax : Syntax :
ptr=(cast-type*)calloc(number, byte-size) p = (type *) malloc (byte_size);

4.6.3 realloc()
It modifies the size of previously allocated space. If memory is not sufficient for malloc()
or calloc(), we can reallocate the memory by realloc() function. It changes the memory size.
Synatx:
ptr=realloc(ptr, new-size)
Program
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void main ()
{
char *str;
str = (char *) malloc(15);
strcpy(str, "computer programming");
printf("String = %s”, str);
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcpy(str, "computer programming and c programming");
printf("String = %s”,str);
free(str);
getch();
}
Output
String = computer programming
String = computer programming and c programming

Department of CSE Page 150


CS3251 PROGRAMMING IN C 2023

4.6.4 free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on their own. We must explicitly use free() to release the space.
Syntax
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.

4.7 SINGLY LINKED LIST


A singly linked list is a data structure consisting of a sequence of nodes where each data
points to the next data. Each node stores,
• Data (element)
• pointer to the next node

Singly Linked List in C


struct node
{
int data;
struct node* next;
};
The node structure has two members:
• data stores the information
• next pointer holds the address of the next node.
Basic operation of singly list list.
• Create Linked List
• Traverse a linked list
• Insert elements to linked list
• Delete from a linked list
4.7.1 . Creating a Node
To create the node, sizeof() is used to determine size in bytes of an element in C and
malloc() is used to dynamically allocate a single block of memory in C.
struct LinkedList *node; //Define node as pointer of data type struct LinkedList
node createNode()
{
node temp; // declare a node
temp = (node)malloc(sizeof(struct LinkedList));
temp->next = NULL;// make next point to NULL
return temp;//return the new node
Department of CSE Page 151
CS3251 PROGRAMMING IN C 2023

}
4.7.2 Traverse a linked list
Displaying the contents of a linked list is very simple. We keep moving the temp node to
the next one and display its contents.
struct node *temp = head;
printf("\n\nList elements are - \n");
while(temp != NULL)
{
printf("%d --->",temp->data);
temp = temp->next;
}
4.7.3 Insert elements to linked list
We can insert elements to either beginning, middle or end of linked list.
Insert at beginning
• Allocate memory for new node
• Store data
• Change next of new node to point to head
• Change head to point to recently created node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = head;
head = newNode;
Insert at end
• Allocate memory for new node
• Store data
• Traverse to last node
• Change next of last node to recently created node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = NULL;
struct node *temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
Insert to middle
• Allocate memory and store data for new node

Department of CSE Page 152


CS3251 PROGRAMMING IN C 2023

• Traverse to node just before the required position of new node


• Change next pointers to include new node in between
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
struct node *temp = head;
for(int i=2; i < position; i++)
{
if(temp->next != NULL)
{
temp = temp->next;
}
}
newNode->next = temp->next;
temp->next = newNode;
4.7.4. Delete from a linked list
We can delete either from beginning, end or from a particular position.
Delete from beginning
• Point head to the second node
head = head->next;
Delete from end
• Traverse to second last element
• Change its next pointer to null
struct node* temp = head;
while(temp->next->next!=NULL){
temp = temp->next;
}
temp->next = NULL;
Delete from middle
• Traverse to element before the element to be deleted
• Change next pointers to exclude the node from the chain
for(int i=2; i< position; i++)
{
if(temp->next!=NULL)
{
temp = temp->next;
}
}
Program for Singly Linked List:
#include<stdio.h>
#include<stdlib.h>
Department of CSE Page 153
CS3251 PROGRAMMING IN C 2023

#include<conio.h>
struct node
{
int data;
struct node *next;
};
void display(struct node* head)
{
struct node *temp = head;
printf("\n\nList elements are - \n");
while(temp != NULL)
{
printf("%d --->",temp->data);
temp = temp->next;
}
}
void insertAtMiddle(struct node *head, int position, int value)
{
struct node *temp = head;
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;
int i;
for(i=2; inext != NULL)
{
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
void insertAtFront(struct node** headRef, int value)
{
struct node* head = *headRef;
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;
newNode->next = head;
head = newNode;
*headRef = head;
}
Department of CSE Page 154
CS3251 PROGRAMMING IN C 2023

void insertAtEnd(struct node* head, int value)


{
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;
newNode->next = NULL;
struct node *temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
void deleteFromFront(struct node** headRef)
{
struct node* head = *headRef;
head = head->next;
*headRef = head;
}
void deleteFromEnd(struct node* head)
{
struct node* temp = head;
while(temp->next->next!=NULL)
{
temp = temp->next;
}
temp->next = NULL;
}
void deleteFromMiddle(struct node* head, int position)
{
struct node* temp = head;
int i;
for(i=2; inext != NULL)
{
temp = temp->next;
}
temp->next = temp->next->next;
}
void main()
{
Department of CSE Page 155
CS3251 PROGRAMMING IN C 2023

struct node *head;


struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Assign data values */
one->data = 1;
two->data = 2;
three->data = 3;
/* Connect nodes */
one->next = two;
two->next = three;
three->next = NULL;
/* Save address of first node in head */
head = one;
display(head); // 1 --->2 --->3 --->
insertAtFront(&head, 4);
display(head); // 4 --->1 --->2 --->3 --->
deleteFromFront(&head);
display(head); // 1 --->2 --->3 --->
insertAtEnd(head, 5);
display(head); // 1 --->2 --->3 --->5 --->
deleteFromEnd(head);
display(head); // 1 --->2 --->3 --->
int position = 3;
insertAtMiddle(head, position, 10);
display(head); // 1 --->2 --->10 --->3 --->
deleteFromMiddle(head, position);
display(head); // 1 --->2 --->3 --->
}

Output
List elements are -
1 --->2 --->3 --->
List elements are -
4 --->1 --->2 --->3 --->
List elements are -
1 --->2 --->3 --->
List elements are -
1 --->2 --->3 --->5 --->
List elements are -
1 --->2 --->3 --->

Department of CSE Page 156


CS3251 PROGRAMMING IN C 2023

List elements are -


1---->2 --->10 --->3 --->

4. 8 TYPEDEF
The typedef keyword allows us to create a new data type name from an existing data type. It
does not create a new data type but introduces a new name for existing type. A typedef
declaration does not reserve storage. We cannot use the typedef specifier inside a function
definition.
Syntax
typedef dataype newdatatype;
Example:
typedef int INTEGER;
INTEGER num=29;
Here, INTEGER is the new name of data type int.
Program
#include<stdio.h>
#include<conio.h>
typedef char uchar;
void main()
{
uchar ch = 'a';
printf("ch: %c\n", ch);
getch();
}
Output
ch : a
typedef in structure
We can use typedef with a structure. If the typedef keyword is given before the keyword
struct, then the struct becomes a new type. For example,
typedef struct student
{
int regno;
char name[20];
};
Now, student is the new data type. The variables of the structure student can be declared
as follows:
student stud;
Program

Department of CSE Page 157


CS3251 PROGRAMMING IN C 2023

#include <stdio.h>
#include <string.h>
typedef struct student
{
int id;
char name[20];
float percentage;
} status;
void main()
{
status record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
getch();
}
Output
Id is: 1
Name is: Raju
Percentage is: 86.500000

4.9 UNION
Union is an user defined datatype in C programming language. It is a collection of
variables of different datatypes in the same memory location. We can define a union with many
members, but at a given point of time only one member can contain a value.
Syntax:
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition.
Example:
union Data
Department of CSE Page 158
CS3251 PROGRAMMING IN C 2023

{
int i;
float f;
char str[20];
} data;
Same memory location can be used to store multiple types of data.
Example: Program to display total memory size occupied by the union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
Output:
Memory size occupied by data : 20
4.9.1 Accessing Union Members
To access any member of a union, use the member access operator (.). The member
access operator is coded as a period between the union variable name and the union member.
You would use union keyword to define variables of union type.
Example
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
Department of CSE Page 159
CS3251 PROGRAMMING IN C 2023

data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}

Output :
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
4.9.2 Difference between structure and union

STORAGE CLASSES AND VISIBILITY


4.10 STORAGE CLASSES
A storage class defines the scope and life-time of variables and functions within a C
Program. It determines the part of memory.
Storage Class of a variable determine
1. Storage area of the variable
2. Initial value of variable,if not initialized
3. Lifetime of the variable
4. Linkage of a variable or function
In C, There are 4 storage classes. They are,
1. Automatic Storage class
2. External Storage class

Department of CSE Page 160


CS3251 PROGRAMMING IN C 2023

3. Static Storage class


4. Register Storage class
4.10.1 Automatic Storage class: auto
The auto storage class is the default storage class for all local variables. It is the
temporary memory space.
Scope: Variable defined with auto storage class is local to the function in which they are
defined.
Default Initial Value: Any random value i.e garbage value.
Lifetime: Till the end of the function/method block where the variable is defined.
Syntax:
auto datatype var1,var2,…..,varn;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
// or
auto int a; //Both are same
….
}
4.10.2 External or Global Storage class: extern
It is the external storage class for all global variables. It is declared out of the main
function.
Scope: Global i.e everywhere in the program.
Default initial value: 0(zero).
Lifetime: Till the program doesn't finish its execution, we can access global variables.
Syntax:
extern datatype var1,var2,…..,varn;
Example
#include<stdio.h>
Department of CSE Page 161
CS3251 PROGRAMMING IN C 2023

#include<conio.h>
extern int a; // global variable
void main()
{
…..
}

4.10.3 Static Storage class : static


The static storage class is the default storage class for all global variables. It is the
permanent memory space. It is declared out of the main function
Scope: Local to the block in which the variable is defined
Default initial value: 0(Zero).
Lifetime: Till the whole program doesn't finish its execution.
Syntax:
static datatype var1,var2,…..,varn;
Example
#include<stdio.h>
#include<conio.h>
static int a; // both are same
//or
int a;
void main()
{
…..
}
4.10.4 Register Storage class: register
It is the special storage area within the computer’s central processing unit.
Scope: Local to the function in which it is declared.
Default initial value: Any random value i.e garbage value
Lifetime: Till the end of function/method block, in which the variable is defined.
Syntax:
register datatype var1,var2,…..,varn;

Department of CSE Page 162


CS3251 PROGRAMMING IN C 2023

Example
#include<stdio.h>
#include<conio.h>
void main()
{
register int a;
register int b;
…..
}
Summary of storage classes

S.No Storage Storage Initial Lifetime Linkage


class value
1 auto Memory Garbage Automatic NO
2 register CPU register Garbage Automatic NO
3 static Memory 0 Static Internal
4 extern Memory 0 Static External
4.11 VISIBILITY

➢ Visibility of a variable is defined by how a variable is accessible inside a program.


➢ A variable is visible within its scope and hidden outside the scope.
➢ A variable's visibility controls how much of the rest of the program may access it.
➢ Visibility and Scope of a variable are very similar to each other but every available
variable (in the scope) is not necessarily accessible (visible) in a C program.

Example

#include <stdio.h>
int main() {
int scope; // outer scope variable
scope = 10;
// inner block of code
{
float scope; // inner scope
scope = 2.98;
printf("Inner block scope : %f\n", scope);
}
printf("Outer block scope : %d\n", scope);
return 0;
Department of CSE Page 163
CS3251 PROGRAMMING IN C 2023

}
Output

Inner block scope : 2.980000


Outer block scope : 10

PART A (2 Marks with Answers)


1. State the meaning of root word struct (APRIL/MAY 2018)
To define a structure in C, we must use the struct keyword. Structure is a user defined
data type that allows you to hold different data type of elements.
Syntax:
struct structurename
{
Datatype member1;
Dat type member2;
. . .
Datatype member n;
} structurevariable1, structurevariable2, . . . structurevariablen;
2. Specify the use of typedef (APRIL/MAY 2018)
The typedef keyword allows us to create a new data type name from an existing data
type. It does not create a new data type but introduces a new name for existing type. A typedef
declaration does not reserve storage. We cannot use the typedef specifier inside a function
definition.
Syntax
typedef dataype newdatatype;
Example
typedef int INTEGER;
INTEGER num=29;
3. Compare arrays and structures.

Department of CSE Page 164


CS3251 PROGRAMMING IN C 2023

Arrays Structures
An array is a collection of data items of A structure is a collection of data items of
same data type. different data types.
Arrays can only be declared. Structures can be declared and defined.

There is no keyword for arrays. The keyword for structure is struct.


An array name represents the address of the A structure name is known as tag. It is a
starting element. Shorthand notation of the declaration.

4. Define Structure in C
Structure is a user defined data type that allows you to hold different data type of
elements. Each element in the structure is called as member. A structure is declared by using the
keyword ‘struct’ followed by an structure name followed by the body of the structure.
Syntax:
struct structurename
{
Datatype member1;
Dat type member2;
. . .
Datatype member n;
} structurevariable1, structurevariable2, . . . structurevariablen;
Example:
struct student
{
int RegNo;
char name[20], dept[10];
}S1, S2;
5. What is dynamic memory allocation?
The process of allocating memory at the time of execution or at the runtime is called
dynamic memory allocation. It means dynamically allocate only the amount of memory needed.
The dynamic memory allocation functions in C are malloc( ), calloc( ), free( ) and realloc( ).

Department of CSE Page 165


CS3251 PROGRAMMING IN C 2023

6. What are Self Referential structures?


Self Referential structures are those structures that have one or more pointers which point
to the same type of structure, as their member. In other words, structures pointing to the same
type of structures are self-referential in nature.
7. What is array of structures?
The array of structures is used to store information about multiple entities of different
data types. The array of structures is also known as the collection of structures.
Syntax
struct structname
{
Datatype member1;
Datatype member2;
. . .
Datatype member n;
}arrayname[ size];
void main()
{
struct structurename arrayname[size];
}
8. What are the various dynamic memory allocation functions?
a. malloc() - Used to allocate blocks of memory in required size of bytes.
b. free() - Used to release previously allocated memory space.
c. calloc() - Used to allocate memory space for an array of elements.
d. realloc() - Used to modify the size of the previously allocated memory space.
9. What is singly linked list?
A singly linked list is a data structure consisting of a sequence of nodes where each data
points to the next data. Each node stores,
• Data (element)
• poniter to the next node

Department of CSE Page 166


CS3251 PROGRAMMING IN C 2023

10. What is meant by nested structure?


A structure can be placed within another structure is called nesting of structures.
Structures can contain other structures as members. Nested structure is also called as structure
within structure.
11. List the types of Self Referential Structures.
The types of Self Referential Structures are:
• Self Referential Structure with Single Link
• Self Referential Structure with Multiple Links
12. What is meant by structure initialization?
A structure is initialized by assigning some constants to the members of the structure. By
default, the members of type int and float are initialized to zero and the members of type char
and string are initialized to ‘\0’. For example,
struct student
{
int Reg_No;
char name[20];
}S1 = {4001, “Joshna”};
13. Write a C program to find the size of a structure.
Program:
typedef struct b1
{
char bname[30];
int ssn;
int pages;
}book;
book b1 = {"Let Us C","1000",90};
int main()
Department of CSE Page 167
CS3251 PROGRAMMING IN C 2023

{
printf("\nSize of Structure : %d",sizeof(b1));
return(0);
}
Output:
Size of Structure : 26
14. Mention any two application of singly linked list
• It can be used to implement Stacks , Queues.
• It can also be used to implement Graphs in Adjacency list representation.
• It can be used to implement Hash Tables.

15. What is the need of typedef?


The typedef keyword allows us to create a new data type name from an existing data
type. Typedefs can be used to simplify the existing type declaration syntax of complex data
structures consisting of struct and union types.
16. Differentiate malloc and calloc.

malloc calloc
The name malloc stands for memory The name calloc stands for contiguous
allocation. allocation.

Does not initialize the memory allocated Initializes the allocated memory to ZERO
malloc() takes one argument - number calloc() take two arguments- number of
of bytes. blocks and size of each block.

Syntax: Syntax:

void * malloc(size_t n); void * calloc(size_t n, size_t size);


Allocates n bytes of memory.
Allocates a contiguous block of memory

malloc is faster than calloc. calloc takes little longer than malloc
because of the extra step of initializing the
allocated memory by zero.

17. How to create a node in linked list?

Department of CSE Page 168


CS3251 PROGRAMMING IN C 2023

The basic thing is to create a node. It can be done by using the malloc function.
start = (node*) malloc(sizeof(node))
This statement creates the starting node of list. A block of memory whose size is equal to
the sizeof(node) is allocated to the node pointer start. Typecasting is used because otherwise
malloc will return pointer to character

PART B (Possible Questions)


1. Define structure in C, specify the pointer & structure with example (13) (APRIL/MAY 2018)
2. i) Write C program for accessing structre member through pointer using dynamic memeory
allocation (6) (APRIL/MAY 2018)
ii) Wrte short notes on singly linked list and specify how the node are created in singly linked
list (7)
3. Explain about the structures and its operations.
4. Demonstrate about pointers to structures, array of structures and nested structures
5. Explain with an example the self‐referential structure.
6. Discuss about the following: ‐
(i).Singly linked list and operation.
(ii).Advantage and disadvange of Singly linked list.
7. (i).How to Accessing the structure member through pointer using dynamic memory allocation.
(ii). Referencing pointer to another address to access the memory.
8. (i).What is a structure? Express a structure with data members of various types and declare
two structure variables. Write a program to read data into these and print the same.
(ii).Justify the need for structured data type.
9. (i).What is the need for structure data type? Does structure bring additional overhead to a
program? Justify.
(ii). Write short note on structure declaration.

PART C (Possible Questions)


1. Write a C program using structures to prepare the students mark statement.
2. Write a C program using structures to prepare the employee pay roll of a company.

Department of CSE Page 169


CS3251 PROGRAMMING IN C 2023

3. Write a C program to read the details of book name, author name and price of 200 books in a
library and display the total cost of the books.
4. Illustrate a C program to store the employee information using structure and search a
particular employee details.
5. Define a structure called student that would contain name, regno and marks of five subjects
and percentage. Write a C program to read the details of name, regno and marks of five subjects
for 30 students and calculate the percentage and display the name, regno, marks of 30 subjects
and percentage of each student.
6. Write a C program to print the Employee Salary Details Using Structure.
7. Explain singly linked list and write C Program to Implement Singly Linked List using
Dynamic Memory Allocation.

ADDITIONAL PROGRAMS
1. Student Grade(Mark Details) Using Structure
#include <stdio.h>
#include <conio.h>
struct Student
{
int rollno;
char name[30];
int mark1, mark2, mark3, total;
float Avg;
char grade;
} S[25];
void main()
{
int i, n;
clrscr();
printf(“ Enter the Number of Students : ”);
Department of CSE Page 170
CS3251 PROGRAMMING IN C 2023

scanf(“%d”, &n);
for ( i = 0 ; i < n ; i++)
{
printf(“ \n\n Enter the student %d details:”, i+1);
printf(“\n Rollno : ”);
scanf(“%d”, &S[i].rollno);
printf(“\n Name : ”);
scanf(“%s”, S[i].name);
printf(“\n Give 3 Subjects Mark”);
scanf(“%d %d %d”, &S[i].mark1, &S[i].mark2, &S[i].mark3);
S[i].total = S[i].mark1 + S[i].mark2 + S[i].mark3;
S[i].Avg = S[i].total / 3;
if ( S[i].Avg < 40 )
S[i].grade =’D’;
else if ( S[i].Avg < 60 )
S[i].grade=’C’;
else if ( S[i].Avg < 80 )
S[i].grade=’B’;
else
S[i].grade=’A’;
}
printf(“\t\t Student Mark List \n”);
printf(“\n Rollno Name \t Mark1 \t Mark2 \t Mark3 \t Total Average Grade ”);
for ( i = 0 ; i < n ; i++)
{
printf(“\n %d \t %s”, S[i].rollno, S[i].name);
printf(“\t %d \t %d \t %d \n”, S[i].mark1, S[i].mark2, S[i].mark3);
printf(“\t %d %4.2f \t %c”, S[i].total, S[i].avg, S[i].grade);
}

Department of CSE Page 171


CS3251 PROGRAMMING IN C 2023

getch();
}
Output:
Enter the Number of Students : 2
Enter the student 1 details:
Rollno :100
Name : Sujith
Give 3 Subjects Mark : 60 75 45
Enter the students 2 details:
Rollno : 101
Name : Joshna
Give 3 Subjects Mark : 78 80 85
Student Mark List
Rollno Name Mark1 Mark2 Mark3 Total Average Grade
100 Sujith 60 75 45 180 60.00 B
101 Joshna 78 80 85 243 81.00 A
2. Employee Salary Details Using Structure
include <stdio.h>
#include <conio.h>
struct emp
{
int emp_code;
char emp_name[30];
float basic_pay, hra, da;
float tax, gross_pay, net_pay;
};
void main()
{
int i, n;
struct emp E[50];
Department of CSE Page 172
CS3251 PROGRAMMING IN C 2023

printf(“ Enter the number of employees : \n”);


scanf(“%d”, &n);
for ( i = 0 ; i < n ; i++)
{
printf(“ Enter the employee %d details : \n”,i+1);
printf(“\nEmployee Code : ”);
scanf(“%d”, &E[i].emp_code);
printf(“\n Employee Name : ”);
scanf(“%s”, E[i].emp_name);
printf(“\n Give Basic Pay , HRA & DA : ”);
scanf(“%f %f %f”, &E[i].basic_pay, &E[i].hra, &E[i].da);
printf(“\n Give Tax : “);
scanf(“%f”, &E[i].tax);
E[i].gross_pay = E[i].basic_pay + E[i].hra + E[i].da;
E[i].net_pay = E[i].gross_pay - E[i].tax;
}
Printf(“-----------------------------------------------------------------------------\n”);
printf(“\t\t Employee Salary List \n”);
printf(“\n Emp_No \t Employee_Name \t Basic_pay \t HRA”);
printf(“\t DA \t Gross_Pay Net_Pay”);
printf(“-----------------------------------------------------------------------------\n”);
for ( i = 0 ; i < n ; i++)
{
printf(“\n %d \t %s \t”, E[i].emp_code, E[i].emp_name);
printf(“%f %f %f “, E [i].basic_pay, E[i].da, E[i].hra);
printf(“%f %f %f”, E[i].gross_pay, E[i].tax, E[i].net_pay);
}
printf(“------------------------------------------------------------------------------\n”);
getch();

Department of CSE Page 173


CS3251 PROGRAMMING IN C 2023

}
Output:
Enter the number of employee:2
Enter the employee 1 details:
Employee Code : 100
Employee Name : Venthan
Give Basic_pay, HRA & DA :
8000
600
6000
Give Tax : 400
Enter the employee 2 details:
Employee Code : 101
Employee Name : Venkat
Give Basic_pay, HRA & DA :
7000
300
5000
Give Tax : 300
Employee Salary List
------------------------------------------------------------------------------------------------------
Emp_No Employee_Name Basic_pay HRA DA Gross_Pay Tax Net_Pay
------------------------------------------------------------------------------------------------------
100 Venthan 8000 600 6000 14600 400 14200
101 Venkat 7000 300 5000 12300 300 12000
------------------------------------------------------------------------------------------------------
3. Book Details Using Structure
#include <stdio.h>
#include<conio.h>
Department of CSE Page 174
CS3251 PROGRAMMING IN C 2023

struct Book
{
char bname[20];
int pages;
int price;
}book[3];
void main()
{
int i;
for(i=0;i<3;i++)
{
printf("\nEnter the Name of Book : ");
scanf(&book[i].bname);
printf("\nEnter the Number of Pages : ");
scanf("%d",&book[i].pages);
printf("\nEnter the Price of Book : ");
scanf("%f",&book[i].price);
}
printf("\n--------- Book Details ------------ ");
for(i=0;i<3;i++)
{
printf("\nName of Book : %s",book[i].bname);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\nPrice of Book : %f",book[i].price);
}
getch();
}
Output
Enter the Name of Book : ABC
Enter the Number of Pages : 100
Enter the Price of Book : 200
Enter the Name of Book : EFG

Department of CSE Page 175


CS3251 PROGRAMMING IN C 2023

Enter the Number of Pages : 200


Enter the Price of Book : 300
Enter the Name of Book : HIJ
Enter the Number of Pages : 300
Enter the Price of Book : 500
--------- Book Details ------------
Name of Book : ABC
Number of Pages : 100
Price of Book : 200
Name of Book : EFG
Number of Pages : 200
Price of Book : 300
Name of Book : HIJ
Number of Pages : 300
Price of Book : 500
4. Write a C program to store the employee information using structure and search a
particular employee using employee number.
include <stdio.h>
#include <conio.h>
struct emp
{
int emp_code;
char name[30], design[20];
};
void main()
{

int i, n, No;
struct emp E[50];
clrscr();

Department of CSE Page 176


CS3251 PROGRAMMING IN C 2023

printf(“ Enter the number of employees : \n”);


scanf(“%d”, &n);
for ( i = 1 ; i <= n ; i++)
{
printf(“ Enter the employee %d details : \n”,i);
printf(“\n Give Employee Code : ”);
scanf(“%d”, &E[i].emp_code);
printf(“\n Give Employee Name & Designation :\n ”);
scanf(“%s %s”, E[i].name, E[i].desig);
}
printf(“ Give Employee Number to be searched : ”);
scanf(“d”, &No);
for ( i = 1 ; i <= n ; i++)
{
if ( E[i].emp_code == No )
Break;
}
if ( E[i].emp_code == No )
printf(“ Employee Found “);
else
printf(“Employee not found”);
getch();
}
Output:
Enter the number of employees: 2
Give Employee Code : 100
Give Employee Name & Designation: ARTHI MANAGER
Give Employee Code : 101
Give Employee Name & Designation: KAVITHA MANAGER

Department of CSE Page 177


CS3251 PROGRAMMING IN C 2023

Give Employee Number to be searched : 100


Employee Found
5. Define a structure called book with book name, author name and price. Write a C
program to read the details of book name, author name and price of 200 books in a library
and display the total cost of the books and the book details whose price is above Rs. 500.

include <stdio.h>
#include <conio.h>
struct
{
char name[20], author[20];
int price;
} book[200] ;
void main()
{
int i, Total = 0;
clrscr();
for ( i = 0 ; i < 200 ; i++)
{
printf(“Enter book detail %d \n”, i);
printf(“ Enter the book name & author : “);
scanf(“%s %s”, book[i].name, book[i].author);
printf(“\n Enter book price : ”);
scanf(“%d”, &book[i].price);
}
printf(“\t\t\t Book list whose price above 500 \n”);
printf(“Book Name Author Price \n”);
for ( i = 0 ; i < 200 ; i++)
{
Total = Total + book[i].price;

Department of CSE Page 178


CS3251 PROGRAMMING IN C 2023

if ( book[i].price > 500)


{
printf(“%s %s”, book[i].name, book[i].author);
printf(“%d \n”, book[i].price);
}
}
printf(“\n Total Book Cost = %d “, Total);
getch();
}
Output
Enter book detail
Enter the book name & author : Cprogramming kavitha
Enter book price : 400
Enter the book name & author : Cprogramming balaguruswamy
Enter book price : 400
Book list whose price above 500:
Cprogramming kavitha 400
total cost=400
6. Program to Find Largest Element Using Dynamic Memory Allocation - calloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, num;
float *data;
printf("Enter total number of elements(1 to 100): ");
scanf("%d", &num);
data = (float*) calloc(num, sizeof(float));
if(data == NULL)
{

Department of CSE Page 179


CS3251 PROGRAMMING IN C 2023

printf("Error!!! memory not allocated.");


exit(0);
}
printf("\n");
for(i = 0; i < num; ++i)
{
printf("Enter Number %d: ", i + 1);
scanf("%f", data + i);
}
for(i = 1; i < num; ++i)
{
if(*data < *(data + i))
*data = *(data + i);
}
printf("Largest element = %.2f", *data);
return 0;
}
Output:
Enter total number of elements(1 to 100): 10
Enter Number 1: 2.34
Enter Number 2: 3.43
Enter Number 3: 6.78
Enter Number 4: 2.45
Enter Number 5: 7.64
Enter Number 6: 9.05
Enter Number 7: -3.45
Enter Number 8: -9.99
Enter Number 9: 5.67
Enter Number 10: 34.95
Largest element: 34.95
7. Program to Display Student Information Using Nested Structure
Department of CSE Page 180
CS3251 PROGRAMMING IN C 2023

#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
int main()
{
struct student_detail stu_data = {1, " Roja", 90.5, 71145,"Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);
printf(" College Id is: %d \n", stu_data.clg_data.college_id);
printf(" College Name is: %s \n",stu_data.clg_data.college_name);
return 0;
}
Output:
Id is: 1
Name is: Roja
Percentage is: 90.500000
College Id is: 71145
College Name is: Anna University
Department of CSE Page 181
CS3251 PROGRAMMING IN C 2023

8. Program to find Sum of All Array Elements using Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
int limit,i;
int sum=0;
printf("Enter total number of elements: ");
scanf("%d",&limit);
/*allocate memory for limit elements dynamically*/
arr=(int*)malloc(limit*sizeof(int));
if(arr==NULL)
{
printf("Insufficient Memory, Exiting... \n");
return 0;
}
printf("Enter %d elements:\n",limit);
for(i=0; i<limit; i++)
{
printf("Enter element %3d: ",i+1);
scanf("%d",(arr+i));
/*calculate sum*/
sum=sum + *(arr+i);
}
printf("Array elements are:");
for(i=0; i<limit; i++)
printf("%3d ",*(arr+i));
printf("\nSum of all elements: %d\n",sum);
return 0; }
Output:
Department of CSE Page 182
CS3251 PROGRAMMING IN C 2023

Enter total number of elements: 5


Enter 5 elements:
Enter element 1: 11
Enter element 2: 22
Enter element 3: 33
Enter element 4: 44
Enter element 5: 55
Array elements are: 11 22 33 44 55
Sum of all elements: 165

Department of CSE Page 183


CS3251 PROGRAMMING IN C 2023

UNIT V
FILE PROCESSING

Files – Types of file processing: Sequential access, Random access – Sequential access file -
Random access file - Command line arguments.

5.1 FILES

A file is a semi-permanent, named collection of data. A File is usually stored on


magnetic media, such as a hard disk or magnetic tape. Semi-permanent means that data
saved in files stays safe until it is deleted or modified.

A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a readymade structure.
5.1.1 Streams in C
Stream is a logical interface to a file. In C, there are three standard streams. They are:
a) Standard input (stdin)
b) Standard output (stdout)
c) Standard error (stderr)

Display

stderr stdout

Program

stdin

Keyboard

Fig 5.1: Standard Streams


a) Standard input (stdin)
It is the stream from which the program receives its data. Data transfer is done using
read operation.
b) Standard output (stdout)
It is the stream where a program writes its output data. Data transfer is done using
write operation.
c) Standard error (stderr)
It is the output stream used by the program to report error messages.

Department of CSE Page 185


CS3251 PROGRAMMING IN C 2023

5.1.2 Buffers Associated with File Streams


A Stream is linked to a file using an open operation and disconnected from a file
using a close operation. When a stream is linked to a file, an associated buffer is created
automatically. A Buffer is a temporary storage area from which data are read from or written
to a file.
When writing output data to a file by the program, the data is first stored in the buffer
until it becomes full. Then the entire data in the buffer is written into the disk file.
When reading input data from a disk file, the data is read as a block from the file and
stored into the buffer. The program reads data from the buffer. The data resides in the buffer
until the buffer is flushed or written to a file.

Program writes Data from the buffer is


data to buffer written to the disk file

PROGRAM BUFFER DISK

Fig 5.2: Buffers Associated With Stream


5.1.3 Types of File

Files are categorized into two. They are:


a) ASCII Text Files
b) Binary Files
a) ASCII Text Files
A text file is a sequence of characters which are processed sequentially. The
operations done on text files are reading, writing and appending. Each line in a text file can
have maximum of 255 characters. Each line ends with a newline character and each file ends
with a EOF (end-of-file) marker.
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.

b) Binary Files
A binary file may contain any type of data that is encoded in binary form. It can be
processed either sequentially or randomly. Binary files require less space than the text files to
store the same piece of data. Binary file also ends with a EOF marker.

Binary files are mostly the .bin files in your computer. Instead of storing data in

Department of CSE Page 186


CS3251 PROGRAMMING IN C 2023

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.
5.1.4 FILE OPERATIONS
The various operations involved in using files in C are
1. Declaring the file pointer variable
2. Opening the file
3. Reading data from file
4. Writing data to the file
5. Closing the file
1. Declaring the file pointer variable
A file pointer variable has to be declared in order to access a particular file.
Syntax:
FILE *file_pointer_name;
Example:
FILE *fp;
Here, fp is the file pointer variable.
2. Opening the file
A file must be opened before read/write operation. The function fopen() is used to
open a file and associate it with a stream. It returns a pointer to FILE structure if the file is
opened successfully, otherwise a NULL is returned.
Syntax:
FILE *fopen(const char *file_name, const char *mode);
Here, file_name - Every file has a file name. In fopen(), the file name is specified
along with the path of the file in the disk.
Example:
E:\\CSE\\Student.DAT (To represent a backslash in C, another backslash is
used.)
mode - Mode represents the type of processing that can be done with the file. The
following table shows the different modes of processing the file.
Mode Description
r Open a text file for reading
w Open a text file for writing
a Append to a text file.

Department of CSE Page 187


CS3251 PROGRAMMING IN C 2023

rb Open a binary file for reading


wb Open a binary file for writing
ab Append to a binary file.
r+ Open an existing text file for read/write
w+ Create a new text file for read/write
a+ Append a text file for read/write
r+b/rb+ Open an existing binary file for read/write
w+b/wb+ Create a new binary file for read/write
a+b/ab+ Append a binary file for read/write
Table: 5.1 File Accessing Modes
3. Reading Data From File
Data can be read from files using the following functions.
a) fscanf()
b) fgets()
c) fgetc()
d) fread()
Function Description
fscanf Used to read formatted data from the stream.
Syntax: int fscanf(FILE *stream, const char *format, ...);
fgets() Used to read a line from the stream.
Syntax:
char *fgets(char *str, int n, FILE *stream);
fgetc() Used to read the next character from the stream.
Syntax:
int fgetc(FILE *stream);
fread() Used to read number of elements specified by num of size specified by size
from the stream.
Syntax:
int fread(void *str, size_t size, size_t num, FILE *stream);
Table: 5.2 Functions to Read Data from File
4. Writing Data to File
The functions used to write data to files are,
• fprintf()

Department of CSE Page 188


CS3251 PROGRAMMING IN C 2023

• fputs()
• fputc()
• fwrite()
Function Description
fprintf() Used to write formatted data to the stream.
Syntax:
int fprintf(FILE *stream, const char *format, ...);
fputs() Used to write a line to the stream.
Syntax:
int fputs(const char *str, FILE *stream);
fputc() Used to write a character to the stream.
Syntax:
int fputc(int char, FILE *stream);
fwrite() Used to write number of elements specified by num of size specified by
size to the stream.
Syntax:
fwrite(const void *str, size_t size, size_t num, FILE *stream);
Table: 5.3 Functions to Write Data to File
5. Closing a File
The file (both text and binary) should be closed after reading/writing. The function
fclose() is used to close an already opened file. It disconnects the file pointer and flushes out
all the buffers associated with the file.
Syntax:
int fclose(FILE *fp);
Here fp is the file pointer of the file that has to be closed. The function returns zero
for successful completion and a non-zero value otherwise.
The function fcloseall() closes all the streams except the standard streams(stdin,
stdout, stderr) and flushes out the stream buffers.
Syntax:
int fcloseall(void);
6.Detecting the End-Of-File(EOF)
EOF is a symbolic constant defined in the library function stdio.h with a value -1.
There are two ways to detect an EOF.

Department of CSE Page 189


CS3251 PROGRAMMING IN C 2023

• Compare the characters that has been read with the value of EOF (ie.,-1).
• Use the standard library function feof() defined in stdio.h. It returns one if EOF
has been reached and zero otherwise.
Syntax:
int feof(FILE *fp);
Program: Program To Open, Write And Close A File
# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[50];
printf( "Opening the file sample.c in write mode" ) ;
fp = fopen("sample.c", "w") ; // opening an existing
file
if ( fp == NULL )
{
printf( "Could not open file sample.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard” ); // getting input from user
while ( strlen ( gets( data ) ) > 0 )
{ // writing in the file
fputs(data, fp) ;
fputs("\n", fp) ;
}
printf("Closing the file sample.c") ;
fclose(fp) ; // closing the file
return 0; }
Output:
Opening the file sample.c in write mode
Enter some text from keyboard
Hai, How are you?
Closing the file sample.c

Department of CSE Page 190


CS3251 PROGRAMMING IN C 2023

5.2 TYPES OF FILE PROCESSING


There are two types of processing based on how a file is accessed. They are,
• Sequential Access
• Random Access
Sequential Access
In Sequential Access, the program processes the data in a sequential manner. ie, one
by one. In order to read the last record, all the records before that record need to be read.

… …

1 2 3 4 5 6 7 8

Fig 5.3: Sequential Access


Random Access
In Random Access, the program accesses the file at the point at which the data should
be read or written. The last record in the file can be read directly.

1 3 7 2 8 6 4 5

Fig 5.4: Random Access


5.3 SEQUENTIAL ACCESS FILE
The data items in a sequential access file are arranged one after another in a sequence.
Each data item can be accessed in the same order in which they have been stored. It is only
possible to read a sequential file from the beginning. To access a particular data within the
sequential access file, data has to be read one data at a time, until the required data is reached.
Reading data from a sequential file can be done using the various C functions like
fscanf(), fgets(), fgetc(), fread(). Writing data to a sequential file can be done using the
various C functions like fprintf(), fputs(), fputc(), fwrite().

Department of CSE Page 191


CS3251 PROGRAMMING IN C 2023

EXAMPLE PROGRAM:
Finding average of numbers stored in sequential access file
#include <stdio.h>
#include <math.h>
// Read the numbers and return average
float average(FILE *input)
{
float term,sum;
int n;
sum = 0.0;
n = 0;
while(!feof(input))
{
fscanf(input,"%f",&term);
sum = sum + term;
n = n + 1;
}
return sum/n;
}
int main ()
{
FILE *input;
float avg;
input = fopen("data.txt","r");
avg = average(input);
fclose(input);
printf("The average of the numbers is %f.\n",avg);
return 0;
}
Output:
/* Data in data.txt
10 11 12 13 14 15. */
The average of the numbers is 12.5

Department of CSE Page 192


CS3251 PROGRAMMING IN C 2023

5.4 RANDOM ACCESS FILE


A random-access data file enables you to read or write information anywhere in the
file. Random access allows you to access any record directly at any position in the file.
Individual records of a random-access file are normally fixed in length and may be accessed
directly without searching through other records. This makes random-access files appropriate
for airline reservation systems, banking systems, point-of-sale systems, and other kinds of
transaction-processing systems.
Random access is sometimes called direct access. C supports the following functions
for random access file processing of a binary file:
1. fseek()
2. ftell()
3. rewind()
4. fgetpos()
5. fsetpos()
5.4.1 fseek()
This function is used for setting the file pointer at the specified byte. On successful
operation, fseek() returns zero. Otherwise it returns a non-zero value.
Syntax:
int fseek(FILE *fp, long displacement, int origin);
Here,
fp – file pointer
displacement – denotes the number of bytes which are moved backward or
forward in the file. It can be positive or negative.
origin – denotes the position relative to which the displacement takes place. It takes
one of the following three values.
Constant Value Position
SEEK_SET 0 Beginning of file
SEEK_CURRENT 1 Current position
SEEK_END 2 End of file
Table: 5.4 Origin field in fseek() function
5.4.2 ftell()
This function returns the current position of the file position pointer. The value is
counted from the beginning of the file. If successful, ftell() returns the current file position. In
case of error, it returns -1.

Department of CSE Page 193


CS3251 PROGRAMMING IN C 2023

Syntax:
long ftell(FILE *fp);
Here, fp – file pointer.
5.4.3 rewind()
This function is used to move the file pointer to the beginning of the file. This
function is useful when we open file for update.
Syntax:
void rewind(FILE *fp);
Here, fp – file pointer.
It is impossible to determine if rewind() was successful or not.
5.4.4 fgetpos()
The fgetpos() is used to determine the current position of the stream. The fgetpos
function stores the current position of stream into the object pointed to by pos. The fgetpos
function returns zero if successful. If an error occurs, it will return a nonzero value.
Syntax:
int fgetpos(FILE *stream, fpos_t *pos);
Here,
stream - The stream whose current position is to be determined.
pos - The current position of stream to be stored.
5.4.5 fsetpos()
The fsetpos() function moves the file position indicator to the location specified by
the 'pos' returned by the fgetpos() function. If fsetpos() function successful, it return zero
otherwise returns nonzero value.
Syntax:
int fsetpos(FILE *stream, const fpos_t *pos);
Here,
stream − This is the pointer to a FILE object that identifies the stream.
pos − This is the pointer to a fpos_t object containing a position previously
obtained with fgetpos.
5.4.6 Difference Between Sequential Access Files And Random Access Files
Sequential Access Files Random Access Files

Sequential Access to a data file means that Random Access to a file means that the

Department of CSE Page 194


CS3251 PROGRAMMING IN C 2023

the computer system reads or writes computer system can read or write
information to the file sequentially, starting information anywhere in the data file.
from the beginning of the file and proceeding
step by step.
When you access information in the same In a random access file, you can search
order all the time, sequential access is faster through it and find the data you need more
than random access. easily.
To read the last record of the file, we have to To read the last record of the file, we can
read all the records from the beginning. read the last record directly.
Example: Tape drives Example: Hard drives
EXAMPLE PROGRAM: Transaction Processing Using Random Access Files
struct clientData
{
unsigned int acctNum;
char lastName[ 15 ];
char firstName[ 10 ];
double balance;
};
unsigned int enterChoice( void );
void textFile( FILE *readPtr );
void updateRecord( FILE *fPtr );
void newRecord( FILE *fPtr );
void deleteRecord( FILE *fPtr );
int main( void )
{
FILE *cfPtr;
unsigned int choice;
if ( ( cfPtr = fopen( "credit.dat", "rb+" ) ) == NULL )
{
puts( "File could not be opened." );
}
else
{
while ( ( choice = enterChoice() ) != 5 )
{
switch ( choice )
{
// create text file from record file
case 1:
textFile( cfPtr );

Department of CSE Page 195


CS3251 PROGRAMMING IN C 2023

break;
// update record
case 2:
updateRecord( cfPtr );
break;
// create record
case 3:
newRecord( cfPtr );
break;
// delete existing record
case 4:
deleteRecord( cfPtr );
break;
default:
puts( "Incorrect choice" );
break;
}
}
fclose( cfPtr );
}
}
void textFile( FILE *readPtr )
{
FILE *writePtr;
int result;
struct clientData client = { 0, "", "", 0.0 };
if ( ( writePtr = fopen( "accounts.txt", "w" ) ) == NULL )
{
puts( "File could not be opened." );
}
else
{
rewind( readPtr ); // sets pointer to beginning of file
fprintf( writePtr, "%-6s%-16s%-11s%10s\n", "Acct", "Last Name",
"First
Name","Balance" );
while ( !feof( readPtr ) )
{
result = fread(&client, sizeof( struct clientData ), 1, readPtr);
// write single record to text file
if ( result != 0 && client.acctNum != 0 )
{
fprintf( writePtr, "%-6d%-16s%-11s%10.2f\n",

Department of CSE Page 196


CS3251 PROGRAMMING IN C 2023

client.acctNum,client.lastName,client.firstName,
client.balance);
}
}
fclose( writePtr );
}
}
void updateRecord( FILE *fPtr )
{
unsigned int account;
double transaction;
struct clientData client = { 0, "", "", 0.0 };
printf( "%s", "Enter account to update ( 1 - 100 ): " );
scanf( "%d", &account );
fseek( fPtr, ( account - 1 ) * sizeof( struct clientData ),SEEK_SET );
fread( &client, sizeof( struct clientData ), 1, fPtr );
if ( client.acctNum == 0 )
{
printf( "Account #%d has no information.\n", account );
}
else
{
printf( "%-6d%-16s%-11s%10.2f\n\n",client.acctNum,
client.lastName, client.firstName, client.balance );
printf( "%s", "Enter charge ( + ) or payment ( - ): " );
scanf( "%lf", &transaction );
client.balance += transaction;
printf( "%-6d%-16s%-11s%10.2f\n",client.acctNum, client.lastName,
client.firstName, client.balance );
fseek( fPtr, ( account - 1 ) * sizeof( struct clientData ),SEEK_SET );
// write updated record over old record in file
fwrite( &client, sizeof( struct clientData ), 1, fPtr );
}
}
void deleteRecord( FILE *fPtr )
{
struct clientData client;
struct clientData blankClient = { 0, "", "", 0 };
unsigned int accountNum;
printf( "%s", "Enter account number to delete ( 1 - 100 ): " );
scanf( "%d", &accountNum );
fseek( fPtr, ( accountNum - 1 ) * sizeof( struct clientData ),SEEK_SET );
fread( &client, sizeof( struct clientData ), 1, fPtr );

Department of CSE Page 197


CS3251 PROGRAMMING IN C 2023

if ( client.acctNum == 0 )
{
printf( "Account %d does not exist.\n", accountNum );
}
else
{
fseek( fPtr, ( accountNum - 1 ) * sizeof( struct
clientData ),SEEK_SET );
// replace existing record with blank record
fwrite( &blankClient,sizeof( struct clientData ), 1, fPtr );
}
}
void newRecord( FILE *fPtr )
{
struct clientData client = { 0, "", "", 0.0 };
unsigned int accountNum;
printf( "%s", "Enter new account number ( 1 - 100 ): " );
scanf( "%d", &accountNum );
fseek( fPtr, ( accountNum - 1 ) * sizeof( struct clientData ),SEEK_SET );
fread( &client, sizeof( struct clientData ), 1, fPtr );
if ( client.acctNum != 0 )
{
printf( "Account #%d already contains
information.\n",client.acctNum );
}
else
{
printf( "%s", "Enter lastname, firstname, balance\n? " );
scanf( "%14s%9s%lf", &client.lastName, &client.firstName,
&client.balance );
client.acctNum = accountNum;
fseek( fPtr, ( client.acctNum - 1 ) *sizeof( struct clientData ),
SEEK_SET );
fwrite( &client,sizeof( struct clientData ), 1, fPtr );
}
}
unsigned int enterChoice( void )
{
unsigned int menuChoice;
printf( "%s", "\nEnter your choice\n"
"1 - Display a formatted text file of accounts\n"
"2 - update an account\n"
"3 - add a new account\n"

Department of CSE Page 198


CS3251 PROGRAMMING IN C 2023

"4 - delete an account\n"


"5 - end program\n? " );
scanf( "%u", &menuChoice );
return menuChoice;
}
Output:
Enter your choice
1 - Display a formatted text file of accounts
2 - update an account
3 - add a new account
4 - delete an account
5 - end program
?1
Acct Last Name First Name Balance

29 Brown Nancy -24.54

33 Dunn Stacey 314.33

37 Barker Doug 0.00

88 Smith Dave 258.34

96 Stone Sam 34.98

Enter your choice


1 - Display a formatted text file of accounts
2 - update an account
3 - add a new account
4 - delete an account
5 - end program
?2
Enter account to update ( 1 - 100 ): 37
37 Barker Doug 0.00
Enter charge ( + ) or payment (-): +87.99
37 Barker Doug 87.99
Enter your choice
1 - Display a formatted text file of accounts
2 - update an account
3 - add a new account
4 - delete an account
5 - end program
?3
Enter new account number ( 1 - 100 ): 22
Enter lastname, firstname, balance ?

Department of CSE Page 199


CS3251 PROGRAMMING IN C 2023

Johnston Sarah 247.45


Enter your choice
1 - Display a formatted text file of accounts
2 - update an account
3 - add a new account
4 - delete an account
5 - end program
?4
Enter account number to delete ( 1 - 100 ): 29
Enter your choice
1 - Display a formatted text file of accounts
2 - update an account
3 - add a new account
4 - delete an account
5 - end program
?5

5.5 COMMAND LINE ARGUMENTS


Any input value passed through command prompt at the time of running of program is
known as command line argument. It is used when you want to control your C program from
outside. Command line arguments are passed as parameters to the main() function.
Syntax:
int main(int argc, char *argv[])
Here,
argv and argc are the two arguments to the main() function.
The argc parameter holds the number of arguments on the command-line and is an
integer. It will always be at least 1 because the name of the program qualifies as the first
argument.
The argv parameter is an array of string pointers. The most common method for
declaring argv is char *argv[]; The empty brackets indicate that it is an array of undetermined
length. argv[0] always contains the name of the program.
Example of command line arguments:
Program : Determine Number of Command Line Arguments and Display Them
#include<stdio.h>
#include<conio.h>
void main(int argc, char* argv[])
{

Department of CSE Page 200


CS3251 PROGRAMMING IN C 2023

int i;
clrscr();
printf("Total number of arguments: %d",argc);
for(i=0;i< argc;i++)
{
printf("\n %d argument: %s",i,argv[i]);
getch();
}
}
Output:
C:/TC/BIN>TCC mycmd.c
C:/TC/BIN>mycmd 10 20
Number of Arguments: 3
0 arguments c:/tc/bin/mycmd.exe
1 arguments: 10
2 arguments: 20

PART A (2 Marks with Answers)


1. What does argv and argc indicate in command line arguments? (APRIL/MAY 2018)
The argv and argc are the two arguments to the main() function. The argc parameter
holds the number of arguments on the command-line and is an integer. It will always be at
least 1 because the name of the program qualifies as the first argument. The argv parameter is
an array of string pointers. The most common method for declaring argv is char *argv[]; The
empty brackets indicate that it is an array of undetermined length.
2. How can you restore a redirected standard stream? (APRIL/MAY 2018)
By using the standard C library functions named dup() and fdopen(), you can restore a
standard stream such as stdout to itsoriginal state.
The dup() function duplicates a file handle. You can use the dup() function to save the
file handlecorresponding to the stdout standard stream. The fdopen() function opens a stream
that has been duplicated with the dup() function.
3. What is the difference between text files and binary files?
Text files contain data that can easily be understood by humans. It includes letters,
numbers and other characters. Binary files contain 1s and 0s that only computers can

Department of CSE Page 201


CS3251 PROGRAMMING IN C 2023

interpret. Text files can be processed sequentially, while binary files can be processed either
sequentially or randomly.
4. What is the advantage of a random access file?
When the data stored in a file is very large, random access can be used to search
through it quickly. A random access file let's you to jump directly to the location where the
required data is present.
5. What is a sequential access file?
The data items in a sequential access file are arranged one after another in a sequence.
Each data item can be accessed in the same order in which they have been stored. It is only
possible to read a sequential file from the beginning. To access a particular data within the
sequential access file, data has to be read one data at a time, until the required data is reached.
6. What is a file?
File is a collection of data stored on secondary storage device such as Hard Disk. It is
used to store the data permanently. A file is used when the real life application involves large
amount of data.
7. What are the basic operations of a file?
The basic operations in files are,
• Creation of a new file
• Opening an existing file
• Reading data from a file
• Writing data to a file
• Closing a file
8. Give the syntax to open a file.
The function fopen() is used to open a file.
Syntax:
FILE *fopen(const char *file_name, const char *mode);
Where file_name represents the name of the file to be opened along with it's
path,
mode represents the type of processing that can be done with the file.
9. What is meant by command line arguments?
Any input value passed through command prompt at the time of running of program is
known as command line argument. It is used when you want to control your C program from
outside.

Department of CSE Page 202


CS3251 PROGRAMMING IN C 2023

Syntax:
int main(int argc, char *argv[])
Here, argc holds the number of arguments on the command-line and argv is an array
of string pointers.
10. What is the use of ftell() function?
ftell () function gives current position of file pointer. It is at the position at which the
next input or output operation will be performed.
Syntax:
long ftell(FILE *stream);
Here, stream points to the file whose file position has to be determined.
11. What is the use of rewind() function?
The rewind function is used to move file pointer position to the beginning of the file.
Syntax:
void rewind (FILE *fp);
Here, fp is the file pointer.
12. How to close an open file?
The fclose() function is used to close an open file. It disconnects the file pointer from
the file and flushes all the buffers associated with it.
Syntax:
int fclose(FILE *fp);
Here fp is the file pointer of the file that has to be closed.
13. Define the term stream.
Stream is a logical interface to a file. In C, there are three standard streams. They are:
1. Standard input (stdin)
2. Standard output (stdout)
3. Standard error (stderr)
14. What are different modes in which a file can be opened?
Mode Description
r Open a text file for reading
w Open a text file for writing
a Append to a text file.
rb Open a binary file for reading
wb Open a binary file for writing

Department of CSE Page 203


CS3251 PROGRAMMING IN C 2023

ab Append to a binary file.


r+ Open an existing text file for read/write
w+ Create a new text file for read/write
a+ Append a text file for read/write
r+b/rb+ Open an existing binary file for read/write
w+b/wb+ Create a new binary file for read/write
a+b/ab+ Append a binary file for read/write
15. What do you understand by EOF?
EOF means End Of File. Each text file ends with the EOF marker. EOF is a symbolic
constant defined in the library function stdio.h with a value -1. It is normally returned by
functions that perform read operations to denote either an error or end of input.
16. What is a buffer?
A Buffer is a temporary storage area from which data are read from or written to a
file. When writing output data to a file by the program, the data is first stored in the buffer
until it becomes full. Then the entire data in the buffer is written into the disk file.
17. What is the difference between gets() and fgets()?
gets() is used to read string from the standard input device until newline character not
found. fgets() is used to read string from file stream till newline character or maximum limit
of the character array.
18. What is the difference between a buffered output stream and an unbuffered output
stream?
When an output stream is unbuffered, information appears on the file as soon as it is
written. When the output stream is buffered, characters are saved in a buffer and then written
out once the buffer is full.
19. Write a C program using the fscanf() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{

Department of CSE Page 204


CS3251 PROGRAMMING IN C 2023

printf("Error! opening file");


exit(1);
}
// reads text until newline
fscanf(fptr,"%[^\n]", c);
printf("Data from the file: %s", c);
fclose(fptr);
return 0;
}
Output:
//Data in the file program.txt
Awesome day.
Let's have fun.
//Output of the program
Data from the file: Awesome day.
20. Why do we need fflush()?
The fflush() function is typically used for output stream only. Its purpose is to clear
(or flush) the output buffer and move the buffered data to file.
Syntax:
int fflush(FILE *fp);
Here, fp points to the output stream.
It returns 0 if buffer is successfully deleted otherwise returns EOF incase of an error.
PART B (Possible Questions)
1. Explain the types of file processing with necessary examples.(13) (APRIL/MAY 2018)
2. Write the C coding for finding the average of numbers stored in sequential access file. (13)
(APRIL/MAY 2018)
3. Explain the read and write operations on a file with a suitable program.
4. Compare Sequential access and Random access file.
5. Describe the various functions used in a file with example.
6. Explain about command line argument with suitable example.
7. Write a C Program Transaction processing using random access files.
8. What are the functions used for accessing files randomly? Explain with examples.
9. Explain the following file operations:

Department of CSE Page 205


CS3251 PROGRAMMING IN C 2023

i.fscanf()
ii.fprintf()
iii.fseek()
iv.ftell()
PART C (Possible Questions)
1. Write a C Program to write all the members of an array of structures to a file using
fwrite(). Read the array from the file and display on the screen.(5) (APRIL/MAY 2018)
2. Write the case study of "How sequential access file is different from random access file".
(10) (APRIL/MAY 2018)
3. Write a C Program to calculate the factorial of a number by using the command line
argument.
4. Write a C Program to read content of a File and display it.
5. Write a C Program to print the contents of a File in reverse.
6. Write a C program to insert, update, delete and append telephone details into a telephone
directory using random access file.
7. Write a C program to count the number of account holders whose balance is less than the
minimum balance using sequential access file.

Department of CSE Page 206


CS3251 PROGRAMMING IN C 2023

ADDITIONAL PROGRAMS
1. Program To Read A File And Store Into An Array
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LSIZ 128
#define RSIZ 10
int main(void)
{
char line[RSIZ][LSIZ];
char fname[20];
FILE *fptr = NULL;
int i = 0;
int tot = 0;
printf("\n\n Read the file and store the lines into an array :\n");
printf("------------------------------------------------------\n");
printf(" Input the filename to be opened : ");
scanf("%s",fname);
fptr = fopen(fname, "r");
while(fgets(line[i], LSIZ, fptr))
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
tot = i;
printf("\n The content of the file %s are : \n",fname);
for(i = 0; i < tot; ++i)
{
printf(" %s\n", line[i]);
}
printf("\n");
return 0;
}

Department of CSE Page 207


CS3251 PROGRAMMING IN C 2023

Output:
Read the file and store the lines into an array :
------------------------------------------------------
Input the filename to be opened : test.txt
The content of the file test.txt are :
Dalton
Stigi
Johan
Jayden
2. Program to copy a file into another
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
printf("\n\n Copy a file in another name :\n");
printf("----------------------------------\n");
printf(" Input the source file name : ");
scanf("%s",fname1);
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);

Department of CSE Page 208


CS3251 PROGRAMMING IN C 2023

exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
break;
else
fputc(ch, fptr2);
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar(); }
Output:
Copy a file in another name :
----------------------------------
Input the source file name : test.txt
Input the new file name : test1.txt
The file test.txt copied successfully in the file test1.txt.
3. Program to Count No. of Words and Characters in a File
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
char ch;
int wrd=1,charctr=1;
char fname[20];
printf("\n\n Count the number of words and characters in a file :\n");
printf("---------------------------------------------------------\n");
printf(" Input the filename to be opened : ");
scanf("%s",fname);

Department of CSE Page 209


CS3251 PROGRAMMING IN C 2023

fptr=fopen(fname,"r");
if(fptr==NULL)
printf(" File does not exist or can not be opened.");
else
{
ch=fgetc(fptr);
printf(" The content of the file %s are : ",fname);
while(ch!=EOF)
{
printf("%c",ch);
if(ch==' '||ch=='\n')
wrd++;
else
charctr++;
ch=fgetc(fptr);
}
printf("\n The number of words in the file %s are : %d\n",fname,wrd-
2);
printf(" The number of characters in the file %s are : %d\n\n", fname,
charctr-1);
}
fclose(fptr);
}
Output:
Count the number of words and characters in a file :
---------------------------------------------------------
Input the filename to be opened : test.txt
The content of the file test.txt are :
Dalton
Stigi
Johan
Jayden
The number of words in the file test.txt are : 4

Department of CSE Page 210


CS3251 PROGRAMMING IN C 2023

The number of characters in the file test.txt are : 22


4. Program to Find Sum of Numbers Given In Command Line Argument
#include <stdio.h>
int main(int argc, char *argv[])
{
int i, sum=0;
if(argc<2)
{
printf("please use \"prg_name value1 value2 ... \"\n");
return -1;
}
for(i=1; i<argc; i++)
{
printf("arg[%2d]: %d\n",i,atoi(argv[i]));
sum += atoi(argv[i]);
}
printf("Sum of all values: %d\n",sum);
return 0;
}
Output:
cc arg4.c
$ a.out 1 2 3 4
Sum of all values: 10
5. Program to Create Employee Record and Update it
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 200
struct emp
{
int id;
char *name;
}*emp1, *emp3;
void display();
void create();
void update();
FILE *fp, *fp1;
int count = 0;
void main(int argc, char **argv)

Department of CSE Page 211


CS3251 PROGRAMMING IN C 2023

{
int i, n, ch;
printf("1] Create a Record\n");
printf("2] Display Records\n");
printf("3] Update Records\n");
printf("4] Exit");
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
fp = fopen(argv[1], "a");
create();
break;
case 2:
fp1 = fopen(argv[1],"rb");
display();
break;
case 3:
fp1 = fopen(argv[1], "r+");
update();
break;
case 4:
exit(0);
}
}
}
void create()
{
int i;
char *p;

Department of CSE Page 212


CS3251 PROGRAMMING IN C 2023

emp1 = (struct emp *)malloc(sizeof(struct emp));


emp1->name = (char *)malloc((size)*(sizeof(char)));
printf("Enter name of employee : ");
scanf(" %[^\n]s", emp1->name);
printf("Enter emp id : ");
scanf(" %d", &emp1->id);
fwrite(&emp1->id, sizeof(emp1->id), 1, fp);
fwrite(emp1->name, size, 1, fp);
count++; // count to number of entries of records
fclose(fp);
}
void display()
{
emp3=(struct emp *)malloc(1*sizeof(struct emp));
emp3->name=(char *)malloc(size*sizeof(char));
int i = 1;
if (fp1 == NULL)
printf("\nFile not opened for reading");
while (i <= count)
{
fread(&emp3->id, sizeof(emp3->id), 1, fp1);
fread(emp3->name, size, 1, fp1);
printf("\n%d %s",emp3->id,emp3->name);
i++;
}
fclose(fp1);
free(emp3->name);
free(emp3);
}
void update()
{
int id, flag = 0, i = 1;
char s[size];

Department of CSE Page 213


CS3251 PROGRAMMING IN C 2023

if (fp1 == NULL)
{
printf("File cant be opened");
return;
}
printf("Enter employee id to update : ");
scanf("%d", &id);
emp3 = (struct emp *)malloc(1*sizeof(struct emp));
emp3->name=(char *)malloc(size*sizeof(char));
while(i<=count)
{
fread(&emp3->id, sizeof(emp3->id), 1, fp1);
fread(emp3->name,size,1,fp1);
if (id == emp3->id)
{
printf("Enter new name of emplyee to update : ");
scanf(" %[^\n]s", s);
fseek(fp1, -204L, SEEK_CUR);
fwrite(&emp3->id, sizeof(emp3->id), 1, fp1);
fwrite(s, size, 1, fp1);
flag = 1;
break;
}
i++;
}
if (flag != 1)
{
printf("No employee record found");
flag = 0;
}
fclose(fp1);
free(emp3->name);
free(emp3); }

Department of CSE Page 214


CS3251 PROGRAMMING IN C 2023

Output:
$ a.out emprec1
1] Create a Record
2] Display Records
3] Update Records
4] Exit
Enter your choice : 1
Enter name of employee : Johan
Enter emp id : 100
Enter your choice : 1
Enter name of employee : Jayden
Enter emp id : 200
Enter your choice : 1
Enter name of employee : Dalton
Enter emp id : 300
Enter your choice : 1
Enter name of employee : Stigi
Enter emp id : 400
Enter your choice : 1
Enter name of employee : Rose
Enter emp id : 500
Enter your choice : 2
100 Johan
200 Jayden
300 Dalton
400 Stigi
500 Rose
Enter your choice : 3
Enter employee id to update : 400
Enter new name of emplyee to update : Sophia
Enter your choice : 2
100 Johan
200 Jayden

Department of CSE Page 215


CS3251 PROGRAMMING IN C 2023

300 Dalton
400 Sophia
500 Rose
Enter your choice : 4
6. Program to Illustrate How a File Stored On the Disk Is Read
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
char filename[15];
char ch;
printf("Enter the filename to be opened \n");
scanf("%s", filename);
/* open the file for reading */
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
ch = fgetc(fptr);
while (ch != EOF)
{
printf ("%c", ch);
ch = fgetc(fptr);
}
fclose(fptr);
}
Output:
$ cc pgm96.c
$ a.out
Enter the filename to be opened

Department of CSE Page 216


CS3251 PROGRAMMING IN C 2023

Hello.txt
Welcome
Be Happy always
Good luck
7. Program to Convert the Content of File to UpperCase
#include <stdio.h>
int to_upper_file(FILE *);
int main(int argc,char *argv[])
{
FILE *fp;
int status;
if (argc == 1)
{
printf("Insufficient Arguments:");
printf("No File name is provided at command line");
return;
}
if (argc > 1)
{
fp = fopen(argv[1],"r+");
status = to_upper_file(fp);
if (status == 0)
{
printf("\n The content of \"%s\" file was successfully converted
to upper case\n",argv[1]);
return;
}
if (status == -1)
{
printf("\n Failed to convert");
return;
}
}

Department of CSE Page 217


CS3251 PROGRAMMING IN C 2023

}
int to_upper_file(FILE *fp)
{
char ch;
if (fp == NULL)
{
perror("Unable to open file");
return -1;
}
else
{
while (ch != EOF)
{
ch = fgetc(fp);
if ((ch >= 'a') && (ch <= 'z'))
{
ch = ch - 32;
fseek(fp,-1,SEEK_CUR);
fputc(ch,fp);
}
}
return 0;
}
}
Output
/*Input file : mydata
$ cat mydata
This is Johan
I like ice cream */

$ gcc file3.c
$ a.out mydata
The content of "mydata" file was successfully converted to upper case

Department of CSE Page 218


CS3251 PROGRAMMING IN C 2023

/*"mydata" after conversion


$ cat mydata
THIS IS JOHAN
I LIKE ICE CREAM */
8. Program to Reverse the Contents of a File and Print it
#include <stdio.h>
#include <errno.h>
long count_characters(FILE *);
void main(int argc, char * argv[])
{
int i;
long cnt;
char ch, ch1;
FILE *fp1, *fp2;
if (fp1 = fopen(argv[1], "r"))
{
printf("The FILE has been opened...\n");
fp2 = fopen(argv[2], "w");
cnt = count_characters(fp1);
fseek(fp1, -1L, 2);
printf("Number of characters to be copied %d\n", ftell(fp1));
while (cnt)
{
ch = fgetc(fp1);
fputc(ch, fp2);
fseek(fp1, -2L, 1);
cnt--;
}
printf("\n**File copied successfully in reverse order**\n");
}
else
{
perror("Error occured\n");

Department of CSE Page 219


CS3251 PROGRAMMING IN C 2023

}
fclose(fp1);
fclose(fp2);
}
long count_characters(FILE *f)
{
fseek(f, -1L, 2);
long last_pos = ftell(f); // returns the position of the last element of the file
last_pos++;
return last_pos;
}
Output
/* Data in the Input File test2
$ cat test2
Jayden is at his grandmas house. */

$ gcc file12.c
$ a.out test2 test_new
The FILE has been opened..
Number of characters to be copied 32
**File copied successfully in reverse order**
/* Data in the File test_new
$ cat test_new
.esuoh samdnarg sih ta si nedyaJ */
9. Program to Delete a File
#include<stdio.h>
main()
{
int status;
char file_name[25];
printf("Enter the name of file you wish to delete\n");
gets(file_name);
status = remove(file_name);
if( status == 0 )

Department of CSE Page 220


CS3251 PROGRAMMING IN C 2023

{
printf("%s file deleted successfully.\n",file_name);
}
else
{
printf("Unable to delete the file\n");
perror("Error");
}
return 0;
}
Output
Enter the name of the file you wish to delete
Hello.txt
Hello.txt file deleted successfully
10. Program to write all the members of an array of structures to a file using fwrite().
Also read the array from the file and display on the screen. (APRIL/MAY 2018)
#include <stdio.h>
struct student
{
char name[50];
int mark;
};
int main()
{
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);

Department of CSE Page 221


CS3251 PROGRAMMING IN C 2023

printf("Enter mark: ");


scanf("%d", &stud1[i].mark);
}
fwrite(stud1, sizeof(stud1), 1, fptr);
fclose(fptr);
fptr = fopen("file.txt", "rb");
fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %s\nmark: %d", stud2[i].name, stud2[i].mark);
}
fclose(fptr);
}
Output:
Enter name: Johan
Enter mark: 98
Enter name: Jayden
Enter mark: 99
Enter name: Dhas
Enter mark: 90
Enter name: Dalton
Enter mark: 85
Enter name: Sophia
Enter mark: 90
Name: Johan
mark: 98
Name: Jayden
mark: 99
Name: Dhas
mark: 90
Name: Dalton
mark: 85
Name: Sophia

Department of CSE Page 222


CS3251 PROGRAMMING IN C 2023

mark: 90
11. Find factorial of a number using command line arguments
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
int n=atoi(argv[1]);
int i,fact=1;
for(i=1;i<=n;i++)
fact*=i;
printf("Factorial of %d is %d", n, fact);
return 0;
}
Output
Factorial of 5 is 120
12. Insert, Update, Delete and Append Teleph
Random Access File
#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","a");
printf("*****Add Record****\n");
printf("Enter Name : ");

Department of CSE Page 223


CS3251 PROGRAMMING IN C 2023

scanf("%s",obj.name);
printf("Enter Telephone No. : ");
scanf("%ld",&obj.telno);
fprintf(fp,"%20s %7ld",obj.name,obj.telno);
fclose(fp);
}
void showAllData()
{
FILE *fp;
struct person obj;
fp=fopen("data.txt","r");
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))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
printf("%20s %30ld\n",obj.name,obj.telno);
}
fclose(fp);
getch();
}
void findData()
{
FILE *fp;
struct person obj;
char name[20];
int totrec=0;
fp=fopen("data.txt","r");
printf("*****Display SpecificRecords*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))

Department of CSE Page 224


CS3251 PROGRAMMING IN C 2023

{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
if(strcmpi(obj.name,name)==0)
{
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
totrec++;
}
}
if(totrec==0)
printf("\n\n\nNo Data Found");
else
printf("\n\n===Total %d Record found===",totrec);
fclose(fp);
getch();
}
void main()
{
char choice;
while(1)
{
printf("*****TELEPHONE DIRECTORY*****\n\n");
printf("1) Append Record\n");
printf("2) Find Record\n");
printf("3) Read all record\n");
printf("4) exit\n");
printf("Enter your choice : ");
fflush(stdin);
choice = getche();
switch(choice)
{
case'1' : //call append record
appendData();

Department of CSE Page 225


CS3251 PROGRAMMING IN C 2023

break;
case'2' : //call find record
findData();
break;
case'3' : //Read all record
showAllData();
break;
case'4' :
exit(1);
}
}
}
Output
*****TELEPHONE DIRECTORY*****
1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice :1
*****Add Record****
Enter Name : johan
Enter Telephone No. : 9867453423
*****TELEPHONE DIRECTORY*****
1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice :1
*****Add Record****
Enter Name : jayden
Enter Telephone No. : 8867453423
*****TELEPHONE DIRECTORY*****
1) Append Record

Department of CSE Page 226


CS3251 PROGRAMMING IN C 2023

2) Find Record
3) Read all record
4) exit
Enter your choice :2
*****Display SpecificRecords*****
Enter Name : johan
Name : johan
Telephone No : 9867453423
===Total 1 Record found===
*****TELEPHONE DIRECTORY*****
1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice :3
*****Display All Records*****
Name Telephone No.
===== ==========
johan 9867453423
jayden 8867453423

Department of CSE Page 227


CS3251 PROGRAMMING IN C 2023

REFERENCES

1. ReemaThareja, “Programming in C”, Oxford University Press, Second Edition, 2016.


2. Kernighan B.W and Ritchie,D.M, “The C Programming language”, Second Edition,
Pearson Education, 2015.
3. Paul Deitel and Harvey Deitel, “C How to Program with an Introduction to C++”,
Eighth edition, Pearson Education, 2018.
4. Yashwant Kanetkar, Let us C, 17th Edition, BPB Publications, 2020.
5. Byron S. Gottfried, “Schaum’s Outline of Theory and Problems of Programming with
C”, McGraw-Hill Education, 1996.
6. Pradip Dey, Manas Ghosh, “Computer Fundamentals and Programming in C”,
Second Edition, Oxford University Press, 2013.
7. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”, 1st
Edition, Pearson Education, 2013

Department of CSE Page 228


CS3251 PROGRAMMING IN C 2023

ANNA UNIVERSITY
MODEL
QUESTION PAPERS

MODEL QUESTION PAPER – I


Second Semester

Department of CSE Page 229


CS3251 PROGRAMMING IN C 2023

Computer Science and Engineering

CS8251 – PROGRAMMING IN C

(Common to: Computer and Communication Engineering/ B.Tech. Information Technology)


(Regulation 2017)

Time: Three Hours Maximum: 100 Marks

Answer ALL questions

PART – A (10x2=20 Marks)

1. List the different data types available in C.


2. Give an example for Ternary operator.
3. Name any two library functions used for string handling.
4. Differentiate between Linear search and Binary search.
5. What is a function?
6. What are the uses of pointers?
7. What are Self Referential structures?
8. Define singly linked list.
9. What is the difference between text files and binary files?
10. What is meant by command line arguments?

PART – B (5x13=65 Marks)

11. (a) Explain the different types of operators available in C. (13)


(OR)
(b) Explain the concept of storage classes with suitable example.(13)
12. (a) (i) Write a C program to add two matrices. (8)
(ii) Write a C program to search an element in an array. (5)
(OR)
(b) (i) Write a C program to sort an array of elements in ascending order using selection
sort.(8)
(ii) Write a C program to reverse a string.(5)
13. (a) (i) Explain the concept of pass by reference with suitable example. (8)
(ii) Write a C program to find factorial of a number using recursion. (5)
(OR)
(b) Demonstrate about function declaration, function definition and function call. (13)

Department of CSE Page 230


CS3251 PROGRAMMING IN C 2023

14. (a) Explain in detail about how to declare a structure and access members of a structure
with example.(13)

(OR)
(b) Explain about Nested structure with example.(13)

15. (a) Explain about command line argument with suitable example. (13)
(OR)
(b) Explain the following file operations: fscanf(), fprintf(), fseek(),ftell() with suitable
example. (13)
PART – C (1x15=15 Marks)
16. Write a C program to insert, update, delete and append telephone details into a telephone
directory using random access file. (15)

MODEL QUESTION PAPER – II


Second Semester

Department of CSE Page 231


CS3251 PROGRAMMING IN C 2023

Computer Science and Engineering

CS8251 – PROGRAMMING IN C

(Common to: Computer and Communication Engineering/ B.Tech. Information Technology)


(Regulation 2017)

Time: Three Hours Maximum: 100 Marks

Answer ALL questions

PART – A (10x2=20 Marks)

1. List the various input and output statements in C.


2. What are keywords? Give an example.
3. Define array. Give example.
4. List the string functions available in C.
5. Define recursion.
6. What is the difference between pass by value and pass by reference?
7. What do you mean by structure?
8. What is meant by Dynamic memory allocation?
9. What do you understand by EOF?
10. What are different modes in which a file can be opened?
PART – B (5x13=65 Marks)

11. (a) (i) What are constants? Explain the various types of constants.(7)
(ii) Write short notes on Switch statements in C with example.(6)
(OR)
(b) Describe the various looping statements in C language and discuss with example.(13)
12. (a) What are the different types of string function? Write a C program to find whether the
given string is palindrome or not without using string functions. (13)
(OR)
(b) (i) Write a C program to find the determinant of the matrix. (8)
(ii) Write a C program to calculate mean for an array of elements.(5)
13. (a) (i) Write a C program to find the sum of digits using recursive function. (8)

(ii) Write a C program using pointers to read in an array of integers and print its
elements in reverse order.(5)
(OR)

Department of CSE Page 232


CS3251 PROGRAMMING IN C 2023

(b) Write a C program for designing Scientific calculator using built-in functions. (13)
14. (a) Write a C program to create mark sheet for students using structure. (13)
(OR)
(b) Explain about the Self Referential structures with example.(13)
15. (a) Explain the read and write operations on a file with a suitable program.(13)
(OR)
(b) Write a C Program for Transaction processing using random access files.(13)

PART – C (1x15=15 Marks)


16. Explain about sequential access file. Write a C program to count the number of account
holders whose balance is less than the minimum balance using sequential access file. (15)

Question Paper Code: 40027

B.E./B.Tech. DEGREE EXAMINATION, APRIL/MAY 2018

Department of CSE Page 233


CS3251 PROGRAMMING IN C 2023

Second Semester
Computer Science and Engineering

CS8251 – PROGRAMMING IN C

(Common to: Computer and Communication Engineering/ B.Tech. Information Technology)


(Regulation 2017)

Time: Three Hours Maximum: 100 Marks

Answer ALL questions

PART – A (10x2=20 Marks)

1. What is external storage class?


2. How does the preprocessor work?
3. What is array? Write the syntax for multi dimensional array.
4. Design C Program to compare any two strings.
5. List advantages of recursion.
6. When null pointer is used?
7. State the meaning of root word struct.
8. Specify the use of typedef.
9. How can you restore a redirected standard stream?
10. What does argv and argc indicate in command line arguments?

PART – B (5x13=65 Marks)

11. (a) (i) Explain the different types of operators used in C with necessary program (8)
(ii) Write the C program to check the integer is palindrome or not. (5)

(OR)
(b) Describe the decision making statements and looping statements in C. (13)
12. (a) Write the C program to multiply two matrices (two-dimensional array) which will be
entered by user. The user will enter the order of a matrix and then its elements and similarly
input the second matrix. If the entered orders of 2 matrices are such that they can’t be
multiplied by each other, then an error message is displayed on the screen. (13)

(OR)
(b) (i) What are the different types of string function? Describe with their purpose. (5)

Department of CSE Page 234


CS3251 PROGRAMMING IN C 2023

(ii) Write the C program to find the number of vowels, consonants, digits and white
space in a string. (8)
13. (a) (i) Explain the purpose of a function prototype. And specify the difference between
user defined function and built-in-function (8)
(ii) Write the program to find the value of sin(x) using series up to the given
accuracy and also print the sin(x) using library function (5)
(OR)
(b) What is the difference between pass by value and pass by reference? Write the C
coding for swapping two numbers using pass by reference (13)
14. (a) Define structure in C. Also specify the pointer and structure with example. (13)
(OR)
(b) (i) Write a C program for accessing structure member through pointer using dynamic
memory allocation. (6)
(ii) Write a short note on singly linked list and specify how the node are created in
singly linked list. (7)
15. (a) Explain the types of file processing with necessary examples.(13)
(OR)
(b) Write the C coding for finding average of numbers stored in sequential access
file.(13)
PART – C (1x15=15 Marks)
16. (i) Write the case study of "How Sequential Access File is different from Random Access
File". (10)
(ii) Write a C Program to write all the members of an array of structures to a file using
fwrite(). Read the array from the file and display on the screen.(5)

Question Paper Code: 80093

Department of CSE Page 235


CS3251 PROGRAMMING IN C 2023

B.E./B.Tech. DEGREE EXAMINATION, APRIL/MAY 2019


Second Semester
Computer Science and Engineering

CS8251 – PROGRAMMING IN C

(Common to: Computer and Communication Engineering/ B.Tech. Information Technology)


(Regulation 2017)

Time: Three Hours Maximum: 100 Marks

Answer ALL questions

PART – A (10x2=20 Marks)

1. Differentiate between formatted and unformatted input statements. Give one example
for each.
2. What is the use of preprocessor directive?
3. Define an array.
4. Write a C function to compare two strings.
5. What is the need for functions?
6. What is the output of the following code fragment?
int x= 456, *p1, **p2;
pl=&x; p2=&p1;
printf (“Value of x is : %d\n”, x);
printf(“Value of *p1 is : %d\n”, p1);
printf (“Value of *p2 is : %d\n”, p2);
7. Compare and contrast a structure with an array.
8. What is the output of the following code fragment?
struct point
{
int x;
int y;
};
struct point origin, “PP;
main ()
{
pp = & origin;
Printf (" origin is (%d% d)\n", (*pp).x,pp-> y);
}
9. Why files are needed?
Department of CSE Page 236
CS3251 PROGRAMMING IN C 2023

10. What is the use of command line argument?

PART – B (5x13=65 Marks)

11. (a) (i) What is the purpose of looping statements? Explain in detail the
operation of various looping statements in C with suitable examples. (12)
(ii) Write a C program to find the sum of 10 non-negative numbers entered by
the user. (4)
(OR)
(b) (i) What is a storage class? Explain the various storage classes jp C along
with suitable example. (12)
(ii) Write a C program to find the largest among 3 numbers entered by the
user. (4)
12. (a) Explain binary search procedure. Write a C program to perform binary
search and explain.
(16)
(OR)
(b) Discuss how you can evaluate the mean, median, mode for an array of
numbers. Write the C program to evaluate the mean, median and mode for an array
of numbers and explain. (16)
13. (a) What is recursion? Explain the procedure to compute sin(x) using recursive
functions. Write the C code for the same.(16)
(OR)
(b) What is pass by reference? Explain swapping of 2 values using pass by
reference in ‘C’.(16)
14. (a) What is dynamic memory allocation? Explain various C functions that are
used for the same with examples. (16)
(OR)
(b) What is a self-referential structures? Explain with suitable examples. (16)
15. (a) Explain in detail various operations that can be done on file giving suitable
examples.(16)
(OR)
(b) Explain in detail random access in files along with the functions used for the
same in C. Give suitable examples. (16)

Department of CSE Page 237


www.EnggTree.com

Downloaded from EnggTree.com


www.EnggTree.com

Downloaded from EnggTree.com

You might also like