0% found this document useful (0 votes)
48 views110 pages

B.Sc. Computer Study Material Guide

The document is a syllabus for a B.Sc. II Semester Computer Studies course, covering topics such as algorithms, programming languages, and the C programming language. It includes detailed units on decision control, functions, arrays, strings, pointers, structures, and file handling in C. Additionally, it provides an index and model papers for students' reference.

Uploaded by

hydiith6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views110 pages

B.Sc. Computer Study Material Guide

The document is a syllabus for a B.Sc. II Semester Computer Studies course, covering topics such as algorithms, programming languages, and the C programming language. It includes detailed units on decision control, functions, arrays, strings, pointers, structures, and file handling in C. Additionally, it provides an index and model papers for students' reference.

Uploaded by

hydiith6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Triveni 1

I [Link].
II SEMESTER
PAPER – 2

COMPUTER STUDY MATERIAL


Triveni 2

SYLLABUS - 2*03CSC15
UNIT I
Introduction to Algorithms and Programming Languages: Algorithm – Key features of
Algorithms – Some more Algorithms – Flow Charts – Pseudo code – Programming

Languages – Generation of Programming Languages – Structured Programming Language-


Design and Implementation of Correct, Efficient and Maintainable Programs.
Introduction to C: Introduction – Structure of C Program – Writing the first C Program –
File used in C Program – Compiling and Executing C Programs – Using Comments –
Keywords – Identifiers – Basic Data Types in C – Variables – Constants – I/O Statements in
C- Operators in C- Programming Examples – Type Conversion and Type Casting

UNIT II
Decision Control and Looping Statements: Introduction to Decision Control Statements –
Conditional Branching Statements – Iterative Statements – Nested Loops – Break and
Continue Statement – Goto Statement
Functions: Introduction – using functions – Function declaration/ prototype – Function
definition – function call – return statement – Passing parameters – Scope of variables –
Storage Classes – Recursive functions – Type of recursion – Towers of Hanoi – Recursion vs
Iteration

UNIT III
Arrays: Introduction – Declaration of Arrays – Accessing elements of the Array – Storing
Values in Array – Calculating the length of the Array – Operations on Array – one
dimensional array for inter-function communication – Two dimensional Arrays –Operations
on Two Dimensional Arrays - Two Dimensional Arrays for inter-function communication –
Multidimensional Arrays – Sparse Matrices
Strings: Introduction –Suppressive Input – String Taxonomy – String Operations –
Miscellaneous String and Character functions

UNIT IV
Pointers: Understanding Computer Memory – Introduction to Pointers – declaring Pointer
Variables – Pointer Expressions and Pointer Arithmetic – Null Pointers – Generic Pointers -
Passing Arguments to Functions using Pointer – Pointer and Arrays – Passing Array to
Function – Difference between Array Name and Pointer – Pointers and Strings – Array of
pointers – Pointer and 2D Arrays – Pointer and 3D Arrays – Function Pointers – Array 0f
Function Pointer – Pointers to Pointers – Memory Allocation in C Programs – Memory
Usage – Dynamic Memory Allocation – Drawbacks of Pointers
Structure, Union, and Enumerated Data Types: Introduction – Nested Structures – Arrays
of Structures – Structures and Functions – Self referential Structures – Union – Arrays of
Unions Variables – Unions inside Structures – Enumerated Data Types
Triveni 3

UNIT V
Files: Introduction to Files – Using Files in C – Reading Data from Files – Writing Data from

INDEX

Unit
Heading PageNo
No

1 Introduction to Algorithms and Programming Languages 4

2 Introduction to C 11

3 Decision Control and Looping Statements 26

4 Functions 34

5 Arrays 42

6 Strings 47

7 Pointers 52

8 Structure, Union, and Enumerated Data Types 60

9 Files 67

Lab manual 72

Model Papers 105

Files – Detecting the End-of-file – Error Handling during File Operations – Accepting
Command Line Arguments – Functions for Selecting a Record Randomly - Remove() –
Renaming a File – Creating a Temporary File
Triveni 4
Triveni 5

UNIT - I
[Link] to Algorithms and Programming Languages

1. What is an Algorithm? Explain about Control Structures. (Or) Features of


algorithms.
Definition: An algorithm is a set of steps for solving a particular problem or program. In
algorithm the set of rules must be unambiguous and have a clear stopping point. It can
expressed in any language, from natural languages like English or French to programming
languages like FORTRAN, C, C++, java etc.
Algorithms that are simple and require the fewest steps possible, is one of the
principle challenges in programming.
Example: the following is an algorithm to find the sum of two numbers.
Step 1: START [start here]
Step 2: INPUT A, B [read two numbers]
Step 3: CALCULATE C=A+B [Do the addition]
Step 4: PRINT C [output the result]
Step 6: END [stop here]

Control Structures used in Algorithms


An algorithm exhibits three key features
1. Sequence
2. Decision and
3. Repetition
1. Sequence: Each step of the algorithm is executed in the specified order.
Ex 1: Algorithm to add two numbers

Step 1 : Input the first number as A


Step 2 : Input the second number as B
Step 3 : Set Sum=A+B
Step 4 : Print Sum
Step 5 : End
2. Decision: Decision statements are used when the outcome of the process depends on some
[Link] general form of the if construct is
if condition then process
A decision statement can also be stated as
if condition
then process1
else process2
Ex: Write an Algorithm to find biggest of any three numbers
step 1 : input the first number as a
step 2 : input the second number as b
step 3 : if a > b and a>c
then print “a is big”
else if b>c
then print “b is big”
else print “c is big”
step 4 : end
[Link]: Repetition involves executing one or more steps for a number of times until
some condition is true. These are also called as looping statements. It can be implemented
using constructs such as the
Triveni 6

 While
 do-while and
 for loops
 Example: Algorithm to print the DENNIS WORD 10 TIMES.
Step 1 : [Initialize] Set I=1, N=10
Step 2 : Repeat Step 3&4 while I<=N
Step 3 : Print “DENNIS”
Step 4 : I=I+1
Step 5 : End
Some More Algorithms
1. Algorithm for swapping two values
Step 1: Input first number as A
Step 2: Input second number as B
Step 3: Set temp=A
Step 4: Set A=B
Step 5: Set B=temp
Step 6: Print A, B
Step 7: End
2. Algorithm to find whether a number is even or off
Step 1: Input the first number as A
Step 2: if A%2=0
then print “EVEN”
else
print “ODD”
Step 3: End
2. What is a Flowchart and explain its significance with an example.
A Flow Charts: A diagrammatic representation of the algorithm is called as flow charts.
They are constructed using some special geometric symbols. After developing the
algorithm a flowchart is drawn. Flowchart is useful to understand the computer program.
Symbols:
No Flow Chart Symbol Symbol Name Symbol Meaning
Beginning or end of a program
1 Oval
Input or output instructions
2 Parallelogram
Used for a calculation process other
3 Rectangle than a decision.

4
Diamond Decision-making and branching

5 Flow lines Indicates the direction of program flow.

Circle This is a connection symbol and is


6
used to join various parts of a flow chart.
Annotation used for added comments
7 Annotation connected to flow chart where helpful
to provide additional information.
Triveni 7

Steps for drawing flow charts: The steps involved in the drawing or flow charts:
a) START: Every Flow Chart should begin with start instruction.
b) INITIALISATION: All the counters or variables should be assigned some initial
value.
c) INPUT: Some variables are assigned to the input variables in this step through READ
or ACCEPT statements.
d) PROCESSING: The processing step may consist of following operations:
a) Mathematical computations.
b) Movement of data value from one variable to another.
c) Conditions testing or decision-making.
d) Iteration of operations (a) through (c)
e) OUTPUT: The final results after processing of the input data are to be printed
displayed.
f) TERMINATION: The processing required at the end is to be done in this stage.
g) STOP: Every flow chart its module is to be closed with one or more stop instruction.
Example flowcharts
1. Addition of two numbers

2. Find the largest of three numbers


Triveni 8

3. What is a Pseudocode? Explain its parts with an example?


 Pseudocode is a form of structured English that describes algorithms.
 Pseudocode describes the entire logic of the algorithm so that it can be translated into
a programming language.
 Pseudocode uses the structural conventions of a programming language.
 It is basically meant for human reading so it omits the details such as variable
declarations, system-specific code and subroutines.
 Pseudocodes are an outline of a program that can easily be converted into
programming statements
 Pseudocode is not an executable program
Keywords used while writing pseudocodes
For looping and selection, the keywords are
Do While …… EndDo; Do Until …. EndDO; Case …. EndCase; If…. EndIf; Call ….With;
etc
Parts of pseudocodes
 For selection statements, the general form is
IF condition THEN
Sequence 1
ELSE
Sequence 2
ENDIF
If the condition is true, sequence 1 is performed, otherwise sequence 2 is performed
Example: IF age>=18 THEN
Display eligible to vote
ELSE
Display not eligible
ENDIF
 For WHILE statement, the general form is
WHILE condition
Sequence
ENDWHILE
The loop is entered only if the condition is true. After each iteration, the condition
will be tested and the loop will continue as long as the condition is true. The
beginning and ending of the loop are indicated by keywords WHILE and
ENDWHILE
Ex: WHILE I<10
Print i
Increment i
ENDWHILE
 REPEAT, the general form is
REPEAT
Sequence
UNTIL condition
Sequence will be performed at least once as the test is performed after it is executed.
After each iteration the condition is evaluated and the loop repeats if the condition is
false.
 FOR loop , the general form is
FOR iteration bounds
Sequence
ENDFOR
Triveni 9

The for loop is used for iterating a sequence for a specific number of times. The
keywords are FOR and ENDFOR.
EX: FOR each student in the class
Add 10 as bonus marks
ENDFOR
Examples of pseudocodes
1. Write a pseducode for calculating the price of a product after adding the sales tax to its
original price.

4. What is meant by Programming Language? Explain different generations of


Programming languages?
Programming Language: Software is the set of Programs. Program is a set of
instructions. Instructions are those that tell the computer what to do and how to do.
Programming language is not a natural language. It is an artificial language that tells the
computer what to do. Programming language consists of a vocabulary and a set of rules
called syntax.

Types of Programming Languages: There are two main types of computer programming
languages.
• low-level languages
• high-level languages.
1. Low Level Programming Languages: These languages are near to computer hardware
and far from human languages. Computer can understand these languages easily.
Following are two low-level languages:
• Machine Language
• Assembly Language
a. Machine Language
Triveni 10

A computer language in which instructions are written in binary form (0 and 1) is


called machine language. It is the only language that is directly understood by the computer.
A computer language in which instructions are written in binary form (0 and 1) is called
machine language. It is the only language that is directly understood by the computer.
Advantages of Machine Languages:
a) Very fast program execution: Because the machine language is the native language of
computer that computers directly understand and execute.
Disadvantages of Machine Languages:
a) Machine Language is difficult to understand
b) Machine Language is difficult to learn
c) Programs of Machine Language are difficult to modify
d) Machine Language requires deep knowledge of hardware
e) Programs of Machine Language are difficult to remove errors
f) Programs of Machine Language are Machine dependent
Machine language is also known as first generation language.
b. Assembly Language

Assembly language is a low-level language. In assembly language, symbols are used instead
of binary code. These symbols are easy to remember. For example Add instruction is used to
add two numbers.
Assembly language is also known as second generation language
Advantages:
a) Assembly language programs are executed with fast speed
b) Assembly language programming is easier to learn, understand and modify than machine
language
Disadvantages:
a) Assembly language programs are machine dependent
b) Assembly language programming requires deep knowledge of hardware

2. High Level Programming Languages: A type of language that is close to human


languages is called high level language. High-level languages are easy to understand.
Instructions of these languages are written in English-like words e.g. Print, Display, Write
etc. Examples of High Level Programming Languages
a. COBOL b. BASIC c. PASCAL
d. C e. C++ f. JAVA
g. Visual Basic
Triveni 11

Advantages of High Level Programming Languages:


a) High Level Programming Languages are Easy to learn and understand
b) Programs written in High Level Programming Languages are Easy to modify
c) It is Easy to remove errors in the Programs written in High Level Programming Languages
d) Programs written in High Level Programming Languages are Machine independent
e) High Level Programming Languages have Better documentation
Disadvantages of High Level Programming Languages:
a) A disadvantage of High Level Programming Languages is slower program execution.
b) High Level Programming Languages provide programming facilities for performing
Certain operations.

5. Explain generations of programming languages.


A. A generation language may refer to any of the following:
1. The first generation languages, or 1GL, are low-level languages that are machine
language.
2. The second-generation languages, or 2GL, are also low-level assembly languages. They
are sometimes used in kernels and hardware drives, but more commonly used for video
editing and video games.
3. The third-generation languages, or 3GL, are high-level languages, such as C, C+
+, Java, JavaScript, and Visual Basic.
4. The fourth-generation languages, or 4GL, are languages that consist of statements
similar to statements in a human language. Fourth generation languages are commonly
used in database programming and scripts examples include Perl, PHP, Python, Ruby,
and SQL.
5. The fifth-generation languages, or 5GL, are programming languages that contain visual
tools to help develop a program. Examples of fifth generation languages include
Mercury, OPS5, and Prolog.

6. Explain Types of High Level Languages.


A. Programming Languages:
1. FORTRAN:FORTRAN stands for FORmula TRANslation. It is mainly used for writing
applications related to science and engineering fields.
2. BASIC: BASIC stands for Beginners All-purpose Symbolic Instruction Code. It was
invented in late 1960's to teach programming skills to students.
3. COBOL: COBOL stands for Common Business Oriented Language. It was especially
designed for business applications.
4. C Language: C Language is one of the most popular programming language among
students and beginners in the field of computer programming. C Language was designed by
Dennis Ritchie at AT&T Bell Labs in 1972. Sometimes C Language is called a middle level
language because it provides facilities to develop application software as well as system
software. So C Language combines some important qualities of a high level language and a low
level programming language.
Triveni 12

INTRODUCTION TO C

1. What is ‘C’? Write about history of C language.


C language is a general purpose and structured programming language developed by
'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972s in USA. It is also called as
'Procedure oriented programming language.'
C is not specially designed for specific applications areas like COBOL (Common
Business-Oriented Language) or FORTRAN (Formula Translation). It is well suited for
business and scietific applications. It has some various features like control structures,
looping statements, arrays, macros required for these applications.
History of C:
Year of
Establishmen Language Name Developed By
t
1960 ALGOL-60 Cambridge University
CPL
1963 Cambridge University
(Combined Programming Language)
BCPL
Martin Richard
1967 (Basic Combined Programming
at Cambridge University
Language)
Ken Thompson
1970 B at AT & T's Bell
Laboratory.
Dennis Ritchie
1972 C at AT & T' Bell
Laboratory.
The development of C was a cause of evolution of programming languages like Algol 60,
CPL (Combined Programming Language), BCPL (Basic Combined Programming Language)
and B.
 Algol-60 : (1963) : ALGOL is an acronym for Algorithmic Language. It was the first
structured procedural programming language, developed in the late 1950s and once
widely used in Europe. But it was too abstract and too general structured language.
 CPL : (1963) : CPL is an acronym for Combined Programming Language. It was
developed at Cambridge University.
 BCPL : (1967) : BCPL is an acronym for Basic Combined Programming Language.
It was developed by Martin Richards at Cambridge University in 1967. BCPL was not
so powerful. So, it was failed.
 B : (1970) : B language was developed by Ken Thompson at AT & T Bell
Laboratories in 1970. It was machine dependent. So, it leads to specific problems.
 C : (1972) : 'C' Programming Language was developed by Dennis Ritchie at AT & T
Bell Laboratories in 1972. This is general purpose, compiled, structured programming
language. Dennis Ritchie studied the BCPL, then improved and named it as 'C' which
is the second letter of BCPL.

2. Explain advantages, disadvantages and uses of C language.


Advantages of C:-
 Machine independence:- Being a high level language it is machine independent.
 Economy of expression:- C is a compact and coherent programming language.
The code is quite cryptic and so small length of code can perform complex tasks.
Triveni 13

 Data Structures:- There are variety of ways to store data in C which allows easy
access to data.
 Operator richness:- C supports a wide range of operators to handle arithmetic and
logical calculations.
Disadvantages of C:-
 Difficult to debug:- C gives a lot of freedom to the developer but it appears bit
complex for a new comer to find what is wrong with a program.
 Loosely syntaxes: - C allows a lot of freedom in coding. You can put end of
statement symbols (;), blank lines, white spaces anywhere you want in the
program. There is no fixed place to start or end a line. This can give rise to code
that is difficult to understand by reading.
Uses:
 C language is primarily used for system programming. The portability, efficiency, the
ability to access specific hardware addresses and low runtime demand on system
resources makes it a good choice for implementing operating systems.
 Compilers, libraries, and interpreters of other programming languages are often
implemented in C.
 For portability and convenience reasons, C is sometimes used as an intermediate
language by implementations of other languages.
 C is widely used to implement end-user applications.

3. What is ‘C’? Explain features (or) characteristics of a ‘C’ Language.


C language is a general purpose and structured programming language developed by
'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972s in USA. It is also called as
'Procedure oriented programming language.' The Characteristics of ‘C’ language are:
1. Modularity.
2. Portability.
3. Extend ability.
4. Speed.
5. Flexibility.
1. Modularity: Ability to breakdown a large module into manageable sub modules called as
modularity that is an important feature of structured programming languages.
Advantages:
1. Projects can be completed in time.
2. Debugging will be easier and faster.
2. Portability: The ability to port i.e. to install the software in different platform is called
portability. Highest degree of portability: ‘C’ language offers highest degree of portability
i.e., percentage of changes to be made to the sources code is at minimum when the software
is to be loaded in another platform. Percentage of changes to the source code is minimum.
The software that is 100% portable is also called as platform independent software or
architecture neutral software. Eg: Java.
3. Extend ability: Ability to extend the existing software by adding new a feature is called as
extend ability.
4. Speed: ‘C’ is also called as middle level language because programs written in ‘c’
language run at the speeds matching to that of the same programs written in assembly
language so ‘c’ language has both the merits of high level and middle level language and
because if this feature it is mainly used in developing system software.
Triveni 14

5. Flexibility: (Key words or reserve words) ANSIC has 32 reserve words. ‘C’ language has
right number of reverse words which allows the programmers to have complete control on the
language. ‘C’ is also called as programmer’s language since it allows programmers to induce
creativeness into the programmers.

4. Discuss the structure of a ‘C’ program? How to Execute ‘C’ program?


A C program contains one or more functions. The statements in a C program are written in a
logical sequence to perform a specific task. Execution of a C program begins at the main ()
function. We can choose any name for the functions. Every program must contain one
function that has its name as main().
The basic structure of C program is as follow:
Document Section: It consists of set of comment lines which include name of a program,
author name, creation date and other information.
// Single line Comment
/* Multi line Comment */ Document Section
Links Section (File)
Links Section (File): It is used to link the required Definition Section
system libraries (or) header files to execute a Global variable declaration
program. Section
void main()
Definition Section: It is used to define or set values {
to variables. Variable declaration
section
Global variable declaration Section: It is used to Function declaration
declare global or public variable or external variable section
or extern variable executable statements;
}
void main(): Used to start of actual C program. It Function definition 1
includes two parts as declaration part and executable ---------------------
part. ---------------------
Function definition n
Variable declaration section: Used to declare
private variable or private varialbes because these
variables can be used with in the block we cant used out side block.

Function declaration section: Used to declare functions of program from which we get
required output.

Then, executable statements are placed for execution.

Function definition section: Used to define functions which are to be called from main().
#include<stdio.h>
void main( )
{
clrscr( );
printf(“Welcome to b sc students”);
getch( );
}
Triveni 15

Execution of C Program: C program executes in following 4 (four steps).

1. Creating a program :
An editor like notepad or WordPad is used to create a C program. This file contains a
source code which consists of executable code. The file should be saved as '*.c'
extension only.
2. Compiling the program :
The next step is to compile the program. The code is compiled by using compiler.
Compiler converts executable code to binary code i.e. object code.
3. Linking a program to library :
The object code of a program is linked with libraries that are needed for execution of
a program. The linker is used to link the program with libraries. It creates a file with
'*.exe' extension.
4. Execution of program :
The final executable file is then run by dos command prompt or by any other
software.

5. Explain Keywords and Identifiers in ‘C’.


Keywords: They are the system defined identifiers. All keywords have fixed meanings that
do not change. White spaces are not allowed in keywords. Keyword may not be used as an
identifier.
It is strongly recommended that keywords should be in lower case letters.
There are totally 32(Thirty Two) keywords used in a C programming.
int float double long
signe
short unsigned const
d
if else switch break
default do while for
register extern static struct
typedef enum return sizeof
goto union auto case
void char continue volatile
Identifiers:- Identifiers are names given to program elements such as variables, arrays and
functions.
Rules for forming identifier name
 it cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc)
except the underscore"_".
 There cannot be two successive underscores
 Keywords cannot be used as identifiers
 The names are case sensitive. So, example, “FIRST” is different from “first” and
“First”.
 It must begin with an alphabet or an underscore.
 It can be of any reasonable length. Though it should not contain more than 31
characters.
Example: roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code
Triveni 16

6. Explain various types of data types that are available in C Language.


Data Type: A data type defines a set of values and the operations that can be performed
on them. Every data type item (constant, variable …etc) in a C – program has a data type
associated with it. C supports several types of data, each of which may be represented
differently within the computer’s memory.
There are mainly 5 types of data types used in the Turbo – C Compiler. They are:
1. Primary (or) Scalar (or) Standard (or) Simple data types.
2. Secondary (or) Derived (or) Structured data type.
3. User defined (or) Enumerated (or) Typedef data type.
4. Empty (or) Void data type.
5. Pointer data type.
1. Scalar (or) Standard data type: A scalar data type is used for representing a single
value only. It is also called as Simple or Fundamental data type. These are used at
primary level so these are also called as Primary data type. These are sub divided
into 4 categories:
 Integer data type:
 It must have at least one digit.
 It should not contain decimal point.
 -ve or +ve values are allowed.
 Its range is – 32768 to 32767.
 It ranges for unsigned int be 0 to 65535.
 It occupies 2bytes of memory.
 Default sign is positive.
 The format string specifier is %d or %i.

 Float (or) Single precision real (or) Real data type:


 It is of very small real type.
 Default sign is positive.
 It should contain at least one digit with a decimal point.
 -ve or +ve values are allowed.
 Its range is 3.4E – 38 to 3.4E +38.
Before ‘E’ is called mantissa after ‘E’ part is called Exponential part.
 It occupies 4bytes of memory.
 The format string specifier is %f.

 Double Precision real (or) Double (or) Long float data type:
 It is a very large floating value.
 Its range is 1.7E – 308 to 1.7E +308.
 There are long double and long float are also available.
 It occupies 8bytes of memory.
 The format string specifier is %lf.

 Character data type:


 This is a single character or a group of characters (called String).
 It may be signed or unsigned.
 It ranges for signed int be – 128 to + 127.
 It ranges for unsigned int be 0 to 255.
 It occupies 1bytes of memory.
 The format string specifier is %c.
Triveni 17

Type Size Range


(Bytes
)
char (or) signed char 1 -128 to 127
unsigned char 1 0 to 255
int (or) signed int 2 -32768 to 32767
unsigned int 2 0 to 65535
short int (or) signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int (or) signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
float 4 3.4E – 38 to 3.4E +38
Double 8 1.7E – 308 to 1.7E +308
long double 10 3.4E – 4932 to 3.4E +4932

2. Structured (or) Derived data type: Derived data types are derived from the primary
data types by adding additional relationship with the elements of the primary data
types. These are used to represent a single or multiple values. These are also called as
structured or secondary data types. These are divided into 3 categories:
o Arrays and Strings
o Structures
o Unions

3. Enumerated (or) User Defined data type : This is also used for type definition i.e. it
allows the users to define a variable or an identifier, which is used to represent
existing data types. In other way it allows us to define new data types. These are
defined as below:
Syntax: enum identifier {v1, v2, v3,….., vn};
(or)
enum identifier {v1, v2, v3,…., vn} variable;
Example: enum month {Jan, Feb, Mar,…, Dec};
(or)
enum year {1999, 2000, 2001,…., 2005}y;
There is another user defined data type typedef. It is also used to represent the
existing data type and it can be used in place of the old data type anywhere in a C
program. It is defined as:
Syntax: typedef data type identifier;
Example: typedef int pay;
typedef float salary;
Here pay tells us the link with int and salary with the float and these can be
used for the declaration of the variable as:
pay p1, p2;
salary s1, s2, s3;

4. Void (or) Empty Data type: It is used in the user defined function or sub programs.
It is used when a function has not any argument and the function does not return a
value.
Syntax: void function name ( int, int ); void function name ( void );
Triveni 18

Example: void add (10, 20); void mul (void);

7. What is Constant? Explain various types of constants.


Constants:- A constant is a value that does not change or vary during the execution of
the program i.e., the value is fixed. In other words we can define constant as an object
whose value can’t be changed. Generally, in every programming language, constants are
same.

1. Numeric constant:- These constants have the numeric value of the combination of
sequence of digits i.e., from 0 – 9 as alone digit or combination of 0 – 9 with or with out
decimal point/ precision value having positive or negative sign. The numeric constant is
of two types:
1. Integer numeric constant: these constants have no decimal or precision point.
These constants range between 0 – 9 and have either + ve, or – ve sign. These are
again divided into three types:
 Decimal integer numeric constant: These constants have no decimal or precision
point. These constants range between 0 – 9, and have either + ve or – ve sign.
Ex: 123, -239, 0, 8, -9, + 4, etc
 Octal integer numeric constant: These constants consists of combination of digits
from 0 – 7 with positive or negative sign. It has leading with O or o (upper or
lower case). It will lead with either ‘O’ or ‘o’ means Octal or octal.
Ex: O37, O5, - o455, etc
 Hexa decimal integer numeric constant: These have Hexa decimal data. These
constants will be preceded by ox, ox, ox, x, x. The combination of values are 0 – 9
and a – f ( a – f ) or alone. The alphabets a – f/ a – f represents the numeric values
10 – 15.
Ex: ox32, ox92, oxdef, etc

2. Real or float numeric constant: These constants have a decimal point or a


precession value within it having any positive or negative sign is called real number
constant. For example, some real numeric constants are :
24.32, 5.32e4, 4.64e3, etc
Mantissa E Exponent
The real constant is divided into two types:
 With exponent: values, which consist of exponent value, are known as float or
real numerical constants with exponents. Ex: 3.1e2, 4.1e-5, etc
 With out exponent: values, which are declared with out exponent value, are
known as float or real numerical constants without exponents.
Ex: 25.3, -55.2, etc

3. Character constant (Non Numeric Constant ):- These constants have a either a single
character or a group of characters or a character with a backslash. They are used for
special purpose. These constants are again divided into three types:
 Single character constant: these constants have a single character within a single
quote (‘). Ex: ‘a’, ‘m’, ‘3’, ‘+’ , etc
 String character constant: These constants have a string value enclosed in double
quotes (“). A string is the collection or combination of characters.
Ex: “hello”, “computers”, “2001 – 2002 “, “2003”, etc
Triveni 19

 Backslash character constant: These constants are used for special purpose in the
programming languages. They are used to arrange the output in an order. They are
also used in the statements like printf, scanf, etc. The backslash characters are also
known as “Escape Sequence” characters. The following are the various escape
sequences used in c + +.
Constants Purpose
‘ \ a ‘ or “ \a “ Produces a beep sound when executed
‘ \ b ‘ or “ \b “ Backspace
‘ \ n ‘ or “ \n “ New line
‘ \ t ‘ or “ \t “ Horizontal tab
‘ \ v ‘ or “ \v ” Vertical tab
‘ \ r ‘ or “ \r “ Carriage return
‘ \ ? ‘ or “ \? “ Displays question tag
‘ \ \ ‘ or “ \\ “ Displays backslash
‘ \ “ ‘ or “ \ “ “ Displays double quotes and etc.

8. What is a variable? What are the rules that are to be followed during variable
declaration?
It is a data name which is used to store data and may change during program
execution. It is opposite to constant. Variable name is a name given to memory cells location
of a computer where data is stored.
The following is the syntax for the declaration of variable:
Syntax: data type variable name;
Example: int a; (or) float b;
Variables of different data type must be declared in different statements. But variables of
same data type can be declared in a single statement, separated by comma.
Syntax: data type variable name1, variable name 2,………, variable name n;
Example: int a, b, c;
Assigning values to variables: values to variables can be assigned in two ways:
 Assigning values at the time of declaration
 Assigning values after declaration
Assigning values at the time of declaration:
We can assign value to the variable at the time of declaring variables. These values
act like default values of the variables, when the variable is accessed.
Syntax: data type variable name = assigning value;
Example: int a = 5;
Assigning values after the declaration:
We can assign value to the variable after the declaration of the variable. Accepting values
from the user using input statements or assigning a value to the variable after the
declaration statement are known as assigning values after declaration.
Syntax: data type variable name;
Variable name = assigning value;
Example: int a;
int a = 5;
or
int a;
printf( “Enter a value into a “);
scanf(“%d”,&a);
Triveni 20

Rules for declaring variables:


 Each variable must be preceded by a data type.
 Variables of different data types can be declared in single statement, but they must be
separated by semi colon.
 Variables of same data type can be declared in a single statement separated by
comma.
 Variables must be declared before their first use.
 Re declaring of variables is not allowed.
 Variable names are case sensitive.
 First character should be letter or alphabet.
 Keywords are not allowed to use as a variable name.
 White space is not allowed.
 C is case sensitive i.e. UPPER and lower case are significant.
 Only underscore, special symbol is allowed between two characters.
 The length of indentifier may be upto 31 characters but only only the first 8 characters
are significant by compiler.

9. What is an operator? Explain various types of operators in C.


Operator: An operator is a symbol that tells the computer to perform certain
mathematical (or) logical manipulations. Operators are used in programs to manipulated
data and variables. The data items that operators act upon are called operands.
"Operator is a symbol that is used to perform mathematical operations."
‘C’ language includes a large number of operators. These operators can be divided
into several different categories. The categories are as follows.
(1) Arithmetic Operators (+,-,*,/,%)
(2) Unary Operators (-,++,--)
(3) Relational Operators (<,>, <=,>=, ==, =)
(4) Logical Operators (&&, ||,)
(5) Assignment Operators(+=,-=,*=,/=,%=,=)
(6) Conditional Operators (? :)
(7) Bitwise Operators(&,|,>>,<<,^,~)
(8) Special Operators(( ),sizeof)
(1) Arithmetic Operators: There are five arithmetic operators in ‘C’ language they are
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Reminder after integer division
Example: Suppose x & y are two integer variables whose values are 6 & 2 respectively.
x+y = 8, x-y=4 , x*y = 12, x/y = 3, x%y = 0.

(2) Unary Operators:


The operators that act on a single operant and produce a new value are known as
unary operators. ‘C’ language includes several unary operators they are as follows:
Unary minus (-), increment (++), decrement (--, size of ( ), Cast operator, logical not
(!), One’s Compliment (~), address operator (&), indirection (*).
Unary Minus (-):
A minus using precedes numerical constants, variable or an expression. Ex: -10, -i, -
(a+b).
Triveni 21

Increment and Decrement Operators:


The Increment operator causes the operand to be incremented by one.
The decrement operator causes the operand to be decremented by one.
The decrement and increment operators can each be utilized in two different ways, depending
on whether the operator is written before the operand or after the operand.
i.e., ++a and --a
a++ and a--
Consider the following:
a= 10;
b= ++a;
In this case the value of a and b would be 11.
Suppose if we rewrite the above statement as
a= 10;
b = a++;
The the value of a & b is 11 and 10 respectively.
A prefix operator first adds one to the operand and then results are assigning to the variable to
L.H.S. then increment its operands.

(3) Relational Operators:


The relational operators are as follows:
Operato Meaning
r
< Less Than
> Greater Than
<= Less Than or Equal to
>= Greater Than or equal to
== Equal to
!= Not Equal
Ex: Suppose that a & b is two integer variables whose values are:
int a=6, b=2;
a>b → T(1) a< b → F (0) a<=b →F(0)
a >= b → F(0) a= = b → F (0) a!=b → T(1).

(4) Logical Operators:


Logical Operators are as follows:
Operator Meaning
&& Logical And
|| Logical Or
! Logical Not
Logical operators act upon operands that are themselves logical expressions.
The result of a logical and operation will be true only both operands are true. The result of
logical or operation will be true if either operand is true, both the operands are true.
Op Op2 Op1&& Op2 Op1 || Op2 !Op1 !Op2
1
0 0 0 0 1 1
1 0 0 1 0 1
0 1 0 1 1 0
1 1 1 1 0 0
Triveni 22

(5) Assignment Operator:


It is used to assign the value of an expression to an integer. The most commonly used
assignment operator is equal to. Assignment operator they may use of this operator is return
in the form.
Syntax: identifier = expression
If the two operands in an assignment expression are of different data types than the
value of expression on the R.H.S. will automatically be converted to the type of identifier on
the Left hand side. The C language also contain the addition 5 assignment operators
+ =, - =, * =, / =, %=
Ex: Suppose that x & y is two integer values and whose values are 6 & 2 respectively.
x+=y  x = x +y  x= 8
x-=y  x = x -y  x= 4
x*=y  x = x *y  x= 12
x/=y  x = x /y  x= 3
x%=y  x = x %y  x= 0

(6) Conditional Operators:


These are used to check the condition with respect to operands or its values.
Conditional operators are ‘?’ and ‘:’. ? returns T if the condition is true otherwise ‘:’ returns
F if the condition is false.
Ex: Suppose a=10 & b = 20
(a>b)? printf (“ as is big): printf(“ b is big”);  b is big.
(7) Bitwise Operators
These are used to manipulate data bit levels. Bitwise operators may not applied, to
float or double data type variables. These operators are as follows.
Operato Meaning
r
& Logical Bitwise And
| Logical Bitwise Or
^ Logical Bitwise Exclusive
>> Left Shift
<< Right Shift
~ One’s compliment
(8) Special Operators:
‘C’ Language includes special operators are as follows:

Operato Meaning
r
, Comma
&, * Pointer Operators
. Member selection
#, ## Pre processor
size of( ) :
The size of( ) operator returns the size of operand in bytes. The size of operator
always preceeds its operand in bytes. The operand may be a variable or a data type.
Ex: size of (int);
double d;
size of (d);
Triveni 23

The size of( ) operator is normally used to determine the length of arrays and structures, when
their sizes are not known to the programmer. These also used to allocate the memory space
dynamically to variables during the execution of program.

10. What is Operator Precedence and Explain with an examples (or) Hierarchy of
operations?
The individual constant, variables array elements and functions can be joined by
operation to form expression. These operators in ‘C’ language as precedence associated with
in. This precedence is used to determine, how an expression, involving more than one
operator is evaluated. The operators having higher level of precedence are evaluated first.
The operator of the same precedence are evaluated either from left to right (or) right to left,
depending on the associative property of an operator. The following table provides a
complete list of operators their precedence levels and their rules of association.

Sl. No Operator Operators Associatively Precedence


Category
1. Unary Operator -, ++, --, size RL 1
of( ), cast()
field, &
2. Arithmetic *, /, % LR 2
+, - LR 3
3. Bitwise <<, >> LR 4
4. Relational <, >, <=, >= LR 5
5. Equality ==, != LR 6
6. Logical bitwise & LR 7
and
7. Logical bitwise | LR 8
or
8. Logical bitwise ^ LR 9
exclusive or
9. Logical And && LR 10
10. Logical Or || LR 11
11. Conditional ?, : RL 12
12. Assignment =, +=, -=, *=, RL 13
%=
13. Comma , LR 14
Note: If the expression consists of parenthesis then the expression in the innermost
parenthesis is evaluated first.

11. What are commonly used Input / Output functions in ‘C’?


C has input – output functions, these are collectively called as Standard I/O library.
Input functions: The input functions are used to read data from the standard input
device (keyboard). There are several input functions.
1. getchar()
2. getch()
3. getche() Unformatted input function
4. gets()
5. scanf() Formatted input function
Triveni 24

1. getchar(): The simplest of all input operations is reading a single character from
input unit (keyboard)
Syntax: char variable name;
Variable name=getchar();
Example: char ch;
ch=getchar();

Program: void main()


{
char answer;
printf(“Enter any character”);
answer=getchar();
printf(“Answer is %c”,answer);
}
2. getch(): This function is similar to getchar() but the difference is this function reads a
single character when it is typed without waiting for the enter key to be pressed. The
function will not display the character on the screen which the user has typed.
Syntax: variable name=getch();
Program: void main()
{
char answer;
printf(“Would you like to know my name?\n”);
printf(“Type Y for yes and N for no:”);
answer=getchar();
if(answer==’y’)
printf(“My name is xxx \n”);
else
printf(“Exit”);
}
3. getche():This function is similar to getch() but the difference is the typed character is
echod (or) displayed on the screen and doesn’t wait for enter key.
Syntax: variable name= getche();
Program: void main()
{
char answer;
printf(“Would you like to know my name?\n”);
printf(“Type Y for yes and N for no:”);
answer=getche();
if(answer==’y’)
printf(“My name is xxx \n”);
else
printf(“Exit”);
}
4. gets(): The purpose of gets() statement is to read a string. It will read a string until you
press enter key from the keyboard. It will mark null character (‘\0’) in the memory at the
end of the string when we press enter key.
Syntax: gets(v);
Example: char mn(80);
gets(mn);
Now, you type “TRIVENI” then mn string will store the value “TRIVENI”
Triveni 25

5. scanf(): This is formatted input function. The scanf input statement is used for reading
mixed data type. It allows to read integer, float, character, hexadecimal, octal, decimal
data by using its format specifier.
Syntax: scanf (“control string”, arg1,arg2,………,argn);
(or)
scanf (“control string”,&v1,&v2,…….&vn);
Here arg1,arg2,………,argn are the arguments for reading and v1,v2,…….vn are all
variables.
Program:void main()
{
int a,b;
printf(“\n Enter a,b”);
scanf(“%d%d”,&a,&b);
printf(“\n addition = %d”, a+b);
}
Output functions:
These functions are used to output (or) print data from the computer onto he
standard output device (monitor or printer)
There are several output functions:
1. putchar()
2. putch() unformatted output functions
3. puts()
4. printf() Formatted output function
1. putchar(): This function displays a single character on the screen.
Syntax: putchar(v);
Where v is the variable of character type in which a single character data is
stored.
Program: void main()
{
char a;
printf(“Enter any character”);
a=getchar();
putchar(a);
}
2. putch(): This function is similar to putchar() which displays a single character, the
instant it is typed without waiting the enter key to be pressed. It displays the character on
the screen, which the user has typed.
Syntax: putch(variable);
Program: void main()
{
char a;
printf(“Enter any character”);
a=getch();
putchar(a);
}
3. puts(): This function is used to display a string at a time, in the standard output device
followed by a new character.
Syntax: puts(argument);
Program: void main()
{
Triveni 26

char triveni[20];
gets(triveni);
puts(triveni);
}
Output: Triveni
4. printf(): The printf() statement is used to display a text message or a value stored in
the variable.
Syntax: printf(“control string”,v1,v2,…….vn);
(or)
printf(“Message line or Text line”);

Format code Meaning


%c To print a single character
%s To print a string
%d To print a signed decimal integer
%ld To print a signed long decimal integer
%f To print a signed float decimal integer
%lf To print a signed double precision value
The print function is a prewritten function and is available to use just by calling it
property. Whenever we use printf() in our program, we have a header file called stdio.h
provides the interface for printf. In addition to displaying message, the printf evaluates
arithmetic expressions and displays the result.
Program: #include<stdio.h>
void main()
{
printf(“Hello! Welcome to C class”);
}
Triveni 27

UNIT – II
[Link] CONTROL AND LOOPING STATEMENTS

1. What is Control Statement?


Control Flow Statement: In most of C programs, the instructions that were executed in
the same order in which they appeared in the program. In some situations the statement(s)
should be executed either in conditional way or in iterative way. To handle such types of
statement(s), some flow controls are required. These are called as Control Statements.
The control statements are 5 types:
1. Sequential Control Statements
2. Decision / Branching Control Statements
3. Loop / repetitive / Iterative Control Statements
4. Case Control Statements
5. Jump Control Statements.
1. Sequential Control Statements: These statements are evaluated by the system in the
order of their appearance in program.
2. Branching Statements (or) Decision Control Statements (or) If Statements (or)
Conditional Control Statemtns: These statements allow the system to execute a block of
statements by having its own decision.
 Simple if
 If else
 Nested if else
 Ladder if / else if
a. Simple if Statement: When only one condition occurs in a statement, then
simple if statement is used having one block. Flow Chart

Syntax:
if (condition)
{
True statement block;
}
Statement – x;

b. If – else Statement: This statement also has a single condition with two different
blocks. One is true block and another one is false block.
Syntax: Flow – Chart:
if (condition)
{
True statement block;
}
else
{
False statement block;
}
Statement – x;
Triveni 28

c. Nested if – else Statements: When an if statement occurs within another if statement,


then it is called nested if statement. It is some complex than the simple if or if – else
statements, but very useful to solve real problems.

Flow – Chart:

d. Ladder if (Or) else if Statement: When in a complex problem number of conditions


arise in a sequence, then we can use Ladder- if or else if statement to solve the problem in
a simple manner.
In this the condition will be checked, if it is true then action will be taken, otherwise
further next condition will be checked and this process will continue till the end of the
condition.
Syntax:
if(condition 1)
statement 1
Triveni 29

else if (condition 2)
statement 2;
else if(condition 3)
statement 3;
else if(condition n)
statement n;
else
statement -x; "
Flow – Chart:

Example: Write a ‘c’ program to print biggest of 3 numbers.


#include<stdio.h>
main()
{
int a, b, c;
clrscr();
printf("Enter 3 numbers:");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
printf("\nA is biggest:%d",a);
else
Triveni 30

if(b>c)
printf("\nB is biggest:%d",b);
else
printf("\nC is biggest:%d",c);
getch();
}
3. Loop / repetitive / Iterative Control Statements: The repetition is done until condition
becomes true. A loop declaration and execution can be done in following ways.
 Check condition to start a loop
 Initialize loop with declaring a variable.
 Executing statements inside loop.
 Increment or decrement of value of a variable.
Types of looping statements:
Basically, the type of looping statements depends on the condition checking mode. Condition
checking can be made in two ways as: Before loop and after loop. So, there are 2(two) types
of looping statements.
 Entry controlled loop
 Exit controlled loop
1. Entry controlled loop:
In such type of loop, the test condition is checked first before the loop is executed. Some
common examples of these looping statements are:
 while loop
 for loop
2. Exit controlled loop:
In such type of loop, the loop is executed first. Then condition is checked after block of
statements are executed. The loop executed atleast one time compulsorily.
Some common example of this looping statement is:
 do-while loop
i) while Loop: This is an entry controlled looping statement. It is used to repeat a block of
statements until condition becomes true.
Syntax: Initialization
initialization
while(condition)
{
statements;
increment/decrement; Condition F
}
Demo of While loop Program:
#include<stdio.h>
void main()
{ Body of theT Loop
int i=1;
clrscr();
while(i<=3) Increment/Decrement
{
printf("\nRama");
i++;
}
getch(); Next statement
}
Triveni 31

Output:
Rama
Rama
Rama
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the loop and executes the block of statements associated with it. At the end of
loop increment or decrement is done to change in variable value. This process continues until
test condition satisfies.

ii) do- while: This is an exit controlled looping statement. Sometimes, there is need to
execute a block of statements first then to check condition. At that time such type of a loop is
used. In this, block of statements are executed first and then condition is checked.
Syntax:
do Initialization
{
statements;
(increment/decrement); Body of the Loop
}while(condition);
Example: Demo of Do-While loop.
#include<stdio.h> Increment/Decrement
void main()
{
int i=1;
clrscr();
do
{ Condition F
printf("\nRama");
i++;
}while(i<3);
getch(); T
}
Output:
Rama Next statement
Rama
Rama
In above syntax, the first the block of statements are executed. At the end of loop, while
statement is executed. If the resultant condition is true then program control goes to evaluate
the body of a loop once again. This process continues till condition becomes true. When it
becomes false, then the loop terminates.

iii) for loop: This is an entry controlled looping [Link] this loop structure, more than
one variable can be initilized. One of the most important feature of this loop is that the three
actions can be taken at a time like variable initilisation, condition checking and
increment/decrement. The for loop can be more concise and flexible than that of while and
do-while loops.
Syntax:
for(initialisation; test-condition; incre/decre)
{
statements;
}
Triveni 32

In above syntax, the given three expressions are Initialization


seperated by ';' (Semicolon)

Demo of for loop.


Program:
#include<stdio.h> F
Condition
void main()
{
int i;
clrscr();
for(i=1;i<=3;i++) Body of the
T Loop
printf("\nRama");
getch();
} Increment/Decrement
Output:
Rama
Rama
Rama
Next statement
4. Multiple branching Statement / Case Control Statements / Switch Statement: These
are similar to decision control statements but each decision depends upon a separate case
other than condition.
Syntax: Flow – Chart:
switch (Expression or variable)
{
case value1:
block – 1;
break;
case value2:
block – 2;
break;
case value3:
block – 3;
break;
…….
…….
case value n:
block – n;
break;
default:
block n+1;
}
Statement – X;

 The case labels are not necessary to write in ascending order.


 The case labels must be unique.
 The block may contain zero (or) one (or) more statements.
 The block contains more than one statement there is no necessary of using braces.
 This expression or case labels are only of integer or character data type
 It is similar to if…..else statement (or) else …. If ladder.
Triveni 33

 The default statement is not used and there is no match is found the control
transfer to the next statement of the program and there is no output.
Example: Demo of Switch control Statement.
#include<stdio.h>
void main()
{
int day_no;
clrscr();
printf("\t\tEnter Day Number:\t");
scanf("%d", &day_no);
switch(day_no)
{
case 1: printf("\n\t\tSunday");
break;
case 2: printf("\n\t\tMonday");
break;
case 3: printf("\n\t\tTuesday");
break;
case 4: printf("\n\t\tWednesday");
break;
case 5: printf("\n\t\tThursday");
break;
case 6: printf("\n\t\tFriday");
break;
case 7: printf("\n\t\tSaturday");
break;
default: printf("\n\t\tInvalid Day_Number");
}
getch();
}
Output:
Enter Day Number: 6
Friday

5. Jump Control Statements: These statements are used to transfer the control from one
position to desired position that’s why these are also known as conditional transfer control
statements.
a) Break Statement: Sometimes, it is necessary to exit immediately from a loop as soon as
the condition is satisfied. When break statement is used inside a loop, then it can cause
to terminate from a loop. The statements after break statement are skipped.
Syntax : Figure :
break;

Example:
#include<stdio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
Triveni 34

{
if(i==5)
break;
printf(“ %d”,i);
}
getch();
}
OUTPUT – 1:
1234

b) Continue: Sometimes, it is required to skip a part of a body of loop under specific


conditions. So, C supports 'continue' statement to overcome this anomaly. The working
structure of 'continue' is similar as that of that break statement but difference is that it cannot
terminate the loop. It causes the loop to be continued with next iteration after skipping
statements in between. Continue statement simply skips statements and continues next
iteration.
Syntax : Figure :
continue;

Example:
#include<stdio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
continue;
printf(" %d”, i);
}
getch();
}
Output:
1 2 3 4 6 7 8 9 10

c) goto: It is a well known as 'jumping statement.' It is primarily used to transfer the control
of execution to any place in a program. It is useful to provide branching within a loop. When
the loops are deeply nested at that if an error occurs then it is difficult to get exited from such
loops. Simple break statement cannot work here properly. In this
situations, goto statement is used.
Syntax :
goto label;
label creation
labelname:
Ex: err:

Figure :
Triveni 35

[Link]

1. What is a Function? Write about advantages and types of functions? Explain


Various Categories of functions.
A. Function: It may be defined as a self contained block of the program to perform specific
task. There are different types of functions to perform different tasks. Functions are classified
into the following categories:
1. System defined functions 2. User defined functions
[Link] in Functions (or) System defined functions : These functions are also called as
'library functions'. These functions are provided by system. These functions are stored in
library files. e.g.
 scanf( ) <stdio.h>
 printf( )
 strcpy( ) <string.h>
 strlwr( )
 strcmp( )
 strlen( )
 strcat( )
 sqrt( ) <math.h>
 abs( )
2. User defined functions: These functions can be defined by the user to perform specific
tasks. There are different types of functions namely:
1. Functions without arguments and without return values
2. Functions without arguments and with return values
3. Functions with arguments and without return values
4. Functions with arguments and with return values
Calling function & Called function: A function which invokes the other function is called
calling functions. A function which is invoked by other function is known as called function
void main( )
{
display( ); calling function
}

void display( )
{
printf(“Rama”); called function
}
Argument: In order to perform specific tasks we have to send some information to the called
function in the form of an argument. There are different types of arguments known as
1. Actual Argument 2. Formal Argument
1. Actual Argument: Argument which is at calling function level it may be either
constant, variable, or expression.
2. Formal Argument: It is an argument which is at called function level. It must be a
variable.
void main( )
{
int x=5, y=6;
add(x,y); Actual Arguments
}
Triveni 36

void add(int a,int b) Formal Arguments


{
Printf(“%d”,a+b);
}

Return Statement: It is used to return a value from called function to the calling
function. It is enable to return more than single value.
Eg: return(5);
return(x);
return(x+5);
Prototype of a function: It tells the compiler the characteristics of function. i.e., return
type, [Link] arguments and their types.
Eg: void add(int,int);
void display( );
long fact(int);
Rules for constructing user defined functions:
1. A function must be followed by a pair of parenthesis.
2. Arguments of a function must be enclosed with in a pair of parenthesis.
3. If a function name followed by a block of code i.e called function definition.
4. If a function name followed by a semicolon than it is invoked from other function
5. Prototype of called function should be declared from it gets called.
6. A Function can be called from any other function any [Link] times.
7. Even main function can be called from any other function
8. Main function may be defined any where of the program but execution is started with
main only.
9. [Link] actual arguments must be equal to [Link] formal arguments, in same order with
same data type.
10. A function can be called from itself. such a function is called recursive function and
such a process is known as recursion.
11. A function should not be defined with in the another function definition,
12. Keywords and system defined function names must not be used for user defined
functions.
13. A function can be called from any part of C program i.e from decision control
statement, loop control statements.
14. A function name can be used as argument to the another function calling
15. A function can be called from the other function by using the following methods.
 call by value  call by reference
16. The value can be returned from called function to the calling function by using return
statements.
17. A function can be ported into [Link] program by including the function name to other
program.
Uses of Functions:
1. reusability
2. reducing the return dent code
3. modularity
4. portability
5. Debugging time.
Advantages :
 It is easy to use.
 Debugging is more suitable for programs.
Triveni 37

 It reduces the size of a program.


 It is easy to understand the actual logic of a program.
 Highly suited in case of large programs.
 By using functions in a program, it is possible to construct modular and structured
programs

2. What are different parameters passing techniques available in ‘C’? Explain?


(Or) Explain passing arguments to functions using pointers.
Parameter passing techniques: The parameter passing mechanism refers to the actions
taken regarding the parameters when a function is invoked. There are two parameter
passing techniques are available in C. They are:
1. Call by Value
2. Call by Reference
1. Call by Value: In this mechanism the values of actual arguments are copied to formal
arguments of the function. If any modification done to the formal arguments, that values
doesn’t effect to the actual arguments. There is only one way communication between the
calling function and called function.
Example: A program to swap the contents of two variables using call by value.
#include<stdio.h>
void swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
printf("\nAfter Swapping %d and %d",a,b);
}
void main()
{
int x,y;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&x,&y);
printf("\nBefore Swapping %d and %d",x,y);
swap(x,y);
getch();
}
Output:
Enter Two Values:12 23
Before Swapping 12 and 23
After Swapping 23 and 12

2. Call by Reference: In this mechanism the address of the actual arguments are copied
on to the formal arguments, though they may be referred by different variable names. The
content of the variables that are altered within the function block are returned to the calling
portion of a program in the altered form it self, as the formal and the actual arguments are
referencing the dame memory location (or) address. This is technically known as call by
reference (or) call by address.
Example: A program to swap the contents of two variables using call by address.
#include<stdio.h>
Triveni 38

void swap(int *a,int *b)


{
int t;
printf("\nBefore Swapping %d and %d",*a,*b);
t=*a;
*a=*b;
*b=t;
printf("\nAfter Swapping %d and %d",*a,*b);
}
void main()
{
int x,y;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&x,&y);
swap(&x,&y);
getch();
}
Output:
Enter Two Values:12 23
Before Swapping 12 and 23
After Swapping 23 and 12

3. What is meant by the scope of variables? Explain storage classes in ‘C’?


A. Storage Classes in C: The storage class of a variable dictates how, when and where
storage will be allocated for the variable. There are different storage classes available.
1. Automatic Variables
2. Register Variables
3. Extern Variables
4. Static Variables
1. Automatic Variables:
 Keyword : auto
 Storage Location : Main memory
 Initial Value : Garbage Value
 Life : Control remains in a block where it is defined.
 Scope : Local to the block in which variable is declared.
Syntax :
auto [data_type] [variable_name];
Example :
auto int a;
Program :
#include <stdio.h>
void main()
{
auto int i=10;
clrscr();
{
auto int i=20;
printf("\n\t %d",i);
}
Triveni 39

printf("\n\n\t %d",i);
getch();
}
Output :
20
10
2. Register variables:
 Keyword : register
 Storage Location : CPU Register
 Initial Value : Garbage
 Life : Local to the block in which variable is declared.
 Scope : Local to the block.
Syntax :
register [data_type] [variable_name];
Example :
register int a;
Program :
#include <stdio.h>
#include <conio.h>
void main()
{
register int i=10;
clrscr();
{
register int i=20;
printf("\n\t %d",i);
} Output :
printf("\n\n\t %d",i); 20
getch(); 10
}
3. External Storage Class :
 Keyword : extern
 Storage Location : Main memory
 Initial Value : Zero
 Life : Until the program ends.
 Scope : Global to the program.
Syntax :
extern [data_type] [variable_name];
Example :
extern int a;
The variable access time is very fast as compared to other storage classes. But few registers
are available for user programs.
The variables of this class can be referred to as 'global or external variables.' They are
declared outside the functions and can be invoked at anywhere in a program.
Program :
#include <stdio.h>
#include <conio.h>
extern int i=10;
void main()
{
Triveni 40

int i=20;
void show(void);
clrscr();
printf("\n\t %d",i);
show();
getch();
}
void show(void) Output :
{ 20
printf("\n\n\t %d",i); 10
}
4. Static Storage Class :
 Keyword : static
 Storage Location : Main memory
 Initial Value : Zero and can be initialize once only.
 Life : depends on function calls and the whole application or program.
 Scope : Local to the block.
Syntax :
static [data_type] [variable_name];
Example :
static int a;
There are two types of static variables as :
a) Local Static Variable b) Global Static Variable
Static storage class can be used only if we want the value of a variable to persist between
different function calls.
Program :
// Program to demonstrate static storage class.
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
void incre(void);
clrscr();
for (i=0; i<3; i++)
incre();
getch();
}
void incre(void)
{
int avar=1;
static int svar=1;
avar++;
svar++;
printf("\n\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}
Output :
Automatic variable value : 2 Static variable value : 2
Automatic variable value : 2 Static variable value : 3
Triveni 41

Automatic variable value : 2 Static variable value : 4

4. Explain Recursive Functions.


A. Recursive Function: If a function called from itself such a process is known as recursion
such a function is called recursive function. Every recursive function should be terminated
after finite [Link] steps and a recursive function must not have any loop control statements.
Using this facility the [Link] instructions may be reduced to perform specific tasks but for each
and every call separate bytes of memory is allocated. That’s why recursive functions are said
to be memory wasted functions.
Features :
 There should be at least one if statement used to terminate recursion.
 It does not contain any looping statements.
Advantages :
 It is easy to use.
 It represents compact programming strctures.
Disadvantages :
 It is slower than that of looping statements because each time function is called.
Program 1: Finding factorial of a number:
PROBLEM SOLUTION
5! 5 X 4 X 3 X 2 X 1!
= 5 X 4! = 5X4X3X2X1
= 5 X 4 X 3! = 5X4X3X2
= 5 X 4 X 3 X 2! =5 X 4 X 6
= 5 X 4 X 3 X 2 X 1! = 5 X 24
= 120
#include <stdio.h>
long fact(int n)
{
if(n==0)
return 1;
else
return (n*fact(n-1));
}
void main()
{
int n;
printf(“Enter an Integer”);
scanf(“%d”,&n);
printf(“Factorial of N:%ld”,fact(n));
}
Output:
Enter an interger:5
Factorial of N:120

5. Explain types of Recursion.


A. Any recursive function can be characterized based on:
a. Whether the function calls itself directly or indirectly (direct or indirect recursion).
b. Whether any operation is pending at each recursive call (tail-recursive or not).
c. The structure of the calling pattern (linear or tree-recursive).
Triveni 42

1. Direct Recursion: A function is said to be directly recursive if it explicitly calls itself. For
example, consider the function given below.
int Func( int n)
{
if(n==0)
retrun n;
return (Func(n-1));
}
2. Indirect Recursion: A function is said to be indirectly recursive if it contains a call to
another function which ultimately calls it. Look at the functions given below. These two
functions are indirectly recursive as they both call each other.
int Func1(int n) int Func2(int x)
{ {
if(n==0) return Func1(x-1);
return n; }
return Func2(n);
}
3. Tail Recursion:
•A recursive function is said to be tail recursive if no operations are pending to be
performed when the recursive function returns to its caller.
•That is, when the called function returns, the returned value is immediately returned from
the calling function.
•Tail recursive functions are highly desirable because they are much more efficient to use as
in their case, the amount of information that has to be stored on the system stack is
independent of the number of recursive calls.
int Fact(n) int Fact1(int n, int res)
{ {
return Fact1(n, 1); if (n==1)
} return res;
return Fact1(n-1, n*res);
}
4. Linear and Tree Recursion:
•A recursive function is said to be linearly recursive when no pending operation involves
another recursive call to the function. For example, the factorial function is linearly
recursive as the pending operation involves only multiplication to be performed and does
not involve another call to Fact.
•A recursive function is said to be tree recursive (or non-linearly recursive) if the pending
operation makes another recursive call to the function. For example, the Fibonacci
function Fib in which the pending operations recursively calls the Fib function.
Triveni 43

UNIT - III
[Link]

1. What is meant by an array? Explain uses and types of an array?


A. ARRAY: An array is a collection of identical data objects are stored in consecutive
memory locations under a common heading.
1. Single dimensional array or One dimensional array
2. Two dimensional array or Double dimensional array
3. Multi – Dimensional Array
1. Single dimensional array
Definition: It is a secondary data type allowed in c which can be store collection of similar
data elements in adjacent memory allocations.
Declaration:
datatype variablename[size];
eg: int a[10]; a[0]……..a[9]
eg float a[100]; a[0]………a[99]

Initialization: An array can be initialized by placing the elements with in a pair of brasses
and separated by camma(,) operated.
int a[5]={12,13,14,15,16};

Here each element occupies 2 bytes of memory.


12 13 14 15 16 Array size 5 * 2=10 bytes of memory

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


Accessing: It means reading and writing. Elements of an array can be accessed with the help
of a subscripted variable whose value is varying from 0 to maximum size minus one.
Reading:
int i,n;a[100];
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]); //Here a[i] is a subscripted variable
}
Writing:
for(i=0;i<n;i++)
{
printf(“ %d”,a[i]);
}
2. Two dimensional array or double dimensional array
Definition: It may be defined as a set of single dimensional arrays i.e a collection of
rows and columns stored in adjacent memory allocations.
Declaration:
int a;
int a[10];
datatype arrayname[rowsize][colsize];
int a[10][10]; ------------> a[0][0]------a[9][9]
10*10=100 elements are entered here
Initialization: D.D.A elements can be initialized by placing with in a pair of braces and
separated by cama(,) operator
int a[3]={23,45,67};
Triveni 44

int a[3][3]={{12,13,14},{23,34,45},{67,78,89}};
or
{12,13,14,23,24,25,67,78,89};

a[0] a[1] a[2]


a[0] 12 13 14
a[1] 23 24 25
a[2] 67 78 89

Accessing : T.D.A elements can be accessed by using two subscript variables. The value of
first one is valid from 0 to [Link] rows minus one and the value second one should be valid
from 0 to [Link] columns minus one.
Reading:
int i,j,r,c,a[100];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]); //Here a[i][j] are two subscripted variables
}
Writing:
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“ %d”,a[i][j]);
}
printf(“\n”);
}
3. Multi – Dimensional Array
Arrays can have more than one dimension is called multi dimensional array.
Syntax: storage class data type array name [expression1] [expression2] . . . .
[Expression n];
1. Where the storage class refers to the scope of the array variable such as external,
static, automatic (or) register.
2. Where the data type refers to the nature of the data elements in the array such as
character type, integer type (or) floating point etc.
3. Where the array name is the name of the multidimensional array. Expression 1,
expression 2, expression n refers to the maximum of the each array locations.
Examples:
int value [50][10][5];
char line [10] [80];
The First one is a three dimensional integer array whose maximum size is 2500
elements.
=================================================================
2. What are the operations that can be performed on Arrays?
A. There are number of operations that can be performed on arrays. These operations include:
1. Traversal: Traversing means accessing each and every element of the array.
Triveni 45

Step 1: [Initialization] Set I = lower_bound


Step 2: Repeat steps 3 to 4 while I<=upper_bound
Step 3: Apply Process to A[I]
Step 4: Set I=I+1
[End of Loop]
Step 5: Exit
2. Insertion: Inserting an element in the array means adding a new data element in an array.
We can insert the element at the end of the array or in the middle of the array.
Inserting element at the end of the array:
Step 1: Set upper_bound = upper_bound + 1
Step 2: Set A[upper_bound] = VAL
Step 3; EXIT
Inserting element in the middle of the array:

Step 1: [INITIALIZATION] SET I = N


Step 2: Repeat Steps 3 and 4 while I >= POS
Step 3: SET A[I + 1] = A[I]
Step 4: SET I = I – 1
[End of Loop]
Step 5: SET N = N + 1
Step 6: SET A[POS] = VAL
Step 7: EXIT
3. Deletion: Deleting an element in the array means removing a data element from an array.
We can delete the element at the end of the array or from the middle of the array.
Deleting element at the end of the array:
Step 1: Set upper_bound = upper_bound - 1
Step 2: EXIT
Deleting element from the middle of the array:

Step 1: [INITIALIZATION] SET I = POS


Step 2: Repeat Steps 3 and 4 while I <= N - 1
Step 3: SET A[I] = A[I + 1]
Step 4: SET I = I + 1
[End of Loop]
Step 5: SET N = N - 1
Step 6: EXIT
4. Search: Searching means to find whether a particular value is present in the array or not.
There are 2 popular searching methods: Linear search, Binary Search.
Triveni 46

Linear search:

LINEAR_SEARCH(A, N, VAL, POS)


Step 1: [INITIALIZE] SET POS = -1
Step 2: [INITIALIZE] SET I = 0
Step 3: Repeat Step 4 while I<N
Step 4: IF A[I] = VAL, then
SET POS = I
PRINT POS
Go to Step 6
[END OF IF]
[END OF LOOP]
Step 5: PRINT “Value Not Present In The Array”
Step 6: EXIT
Binary Search:
BINARY_SEARCH(A, lower_bound, upper_bound, VAL,
POS)
Step 1: [INITIALIZE] SET BEG = lower_bound, END =
upper_bound, POS = -1
Step 2: Repeat Step 3 and Step 4 while BEG <= END
Step 3: SET MID = (BEG + END)/2
Step 4: IF A[MID] = VAL, then
POS = MID
PRINT POS
Go to Step 6
IF A[MID] > VAL then;
SET END = MID - 1
ELSE
SET BEG = MID + 1
[END OF IF]
[END OF LOOP]
Step 5: IF POS = -1, then
PRINTF “VAL IS NOT PRESENT IN THE
ARRAY”
[END OF IF]
Step 6: EXIT

5. Merging: Merging means copying the content of one array to another array or copying the
contents of first array to third array, and then copy the contents of second array to third array.
6. Sorting: Sorting means arranging the elements of the array in some relevant order which
may either be ascending or descending. There are two types of sorting: Internal, Sorting.
3. Explain Sparse Matrices.
 Sparse matrix is a matrix that has many elements with a value zero.
 In order to efficiently utilize the memory, specialized algorithms and data structures
that take advantage of the sparse structure of the matrix should be used. Otherwise,
execution will slow down and the matrix will consume large amounts of memory.
Triveni 47

 There are two types of sparse matrices. In the first type of sparse matrix, all elements
above the main diagonal have a value zero. This type of sparse matrix is also called a
(lower) triagonal matrix. In a lower triangular matrix, Ai,j = 0 where i<j.
 An nXn lower triangular matrix A has one non zero element in the first row, two non
zero element in the second row and likewise, n non zero elements in the nth row.

 In an upper triangular matrix Ai,j = 0 where i>j.


 An nXn upper triangular matrix A has n non zero element in the first row, n-1 non
zero element in the second row and likewise, 1 non zero elements in the nth row.

 In the second variant of a sparse matrix, elements with a non-zero value can appear
only on the diagonal or immediately above or below the diagonal. This type of matrix
is also called a tridiagonal matrix.
 In a tridiagonal matrix, Ai,j = 0 where | i – j| > 1. Therefore, if elements are present on
 the main diagonal the, it contains non-zero elements for i=j. In all there will be n
elements
 diagonal below the main diagonal, it contains non zero elements for i=j+1. In all there
will be n-1 elements
 diagonal above the main diagonal, it contains non zero elements for i=j-1. In all there
will be n-1 elements
1
1 2
9 3 1

4 2
2
5
1 9

6 7
Triveni 48

[Link]

1. What is character array (String)? Explain how to create and initialise the character
array.
• A string is a null-terminated character array. This means that after the last character, a
null character (‘\0’) is stored to signify the end of the character array.
• The general form of declaring a string is
char str[size];
• For example if we write,
char str[] = “HELLO”;
We are declaring a character array with 5 characters namely, H, E, L, L and O.
Besides, a null character (‘\0’) is stored at the end of the string. So, the internal
representation of the string becomes- HELLO’\0’. Note that to store a string of length 5,
we need 5 + 1 locations (1 extra for the null character).
The name of the character array (or the string) is a pointer to the beginning of the
string.

Reading of a string:-
If we declare a string by writing
char str[100];
Then str can be read from the user by using three ways
use scanf function
using gets() function
using getchar()function repeatedly
• The string can be read using scanf() by writing
scanf(“%s”, str);
• The string can be read by writing
gets(str);
gets() takes the starting address of the string which will hold the input. The string
inputted using gets() is automatically terminated with a null character.
Triveni 49

Writting of a string:-
The string can be displayed on screen using three ways
• use printf() function
• using puts() function
• using putchar()function repeatedly
The string can be displayed using printf() by writing
printf(“%s”, str);
The string can be displayed by writing
puts(str);
2. Explain suppressing input.
• scanf() can be used to read a field without assigning it to any variable. This is done
by preceding that field's format code with a *. For example, given:
scanf("%d*c%d", &hr, &min);
• The time can be read as 9:05 as a pair. Here the colon would be read but not assigned
to anything.
Using a Scanset
• The ANSI standard added the new scanset feature to the C language. A scanset is used
to define a set of characters which may be read and assigned to the corresponding
string. A scanset is defined by placing the characters inside square brackets prefixed
with a %
int main()
{
char str[10];
printf("\n Enter string: " );
scanf("%[aeiou]", str );
printf( "The string is : %s", str);
return 0;
}
• The code will stop accepting character as soon as the user will enter a character that is
not a vowel.
• However, if the first character in the set is a ^ (caret symbol), then scanf() will accept
any character that is not defined by the scanset. For example, if you write
scanf("%[^aeiou]", str );
The sscanf() function: This function reads data from str and stores them according to the
parameter format into the specific location. Consider the following:
sscanf(str, “%d”, &num);
a) First parameter str contains the data to be converted.
b) Second parameter %d determines how the string is converted.
c) Third parameter specifies memory location to place the result of the conversion.

3. Explain string taxonomy.


We can store a string either in fixed length format or in variable length format.
Triveni 50

Fixed length String: When storing a string in fixed length format, we need to specify an
approximate size for the string variable.
Variable Length String: In variable length format, the string expanded or condensed to
accommodate the elements in it. This can be done in two ways:
1. Length controlled string: In this format, we have to specify the count, this count is
then used by the string manipulation functions.
2. Delimited string: In this the string is ended with some delimiter. The NULL character
is most commonly used delimiter in the C language.
4. Explain string operations.
There are different string operations that are performed on character arrays.
1. Length: The number of characters in the string constitutes the length of the string. For
example, LENGTH(“C PROGRAMMING IS FUN”) will return 20. Note that even blank
spaces are counted as characters in the string. LENGTH(‘0’) = 0 and LENGTH(‘’) = 0
because both the strings does not contain any character.
Step 1: [INITIALIZE] SET I = 0
Step 2: Repeat Step 3 while STR[I] != '\0'
Step 3: SET I = I + 1
[END OF LOOP]
Step 4: SET LENGTH = I
Step 5: END
2. Converting to upper case: In memory the ASCII code of a character is stored instead of
its real value. The ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z
ranges from 97 to 123. So if we have to convert a lower case character into upper case, then
we just need to subtract 32 from the ASCII value of the character.

Step1: [Initialize] SET I=0


Step 2: Repeat Step 3 while STR[I] != ‘\0’
Step 3: IF STR[1] > ‘a’ AND STR[I] < ‘z’
SET Upperstr[I] = STR[I] - 32
ELSE
SET Upperstr[I] = STR[I]
[END OF IF]
[END OF LOOP]
Step 4: SET Upperstr[I] = ‘\0’
Step 5: EXIT

3. Converting to upper case: In memory the ASCII code of a character is stored instead of
its real value. The ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z
ranges from 97 to 123. So if we have to convert a lower case character into upper case, then
we just need to add 32 from the ASCII value of the character.
Triveni 51

Step1: [Initialize] SET I=0


Step 2: Repeat Step 3 while STR[I] != ‘\0’
Step 3: IF STR[1] > ‘A’ AND STR[I] < ‘Z’
SET Lowerstr[I] = STR[I] + 32
ELSE
SET Lowerstr [I] = STR[I]
[END OF IF]
[END OF LOOP]
Step 4: SET Lowerstr [I] = ‘\0’
Step 5: EXIT
TRIVENI 52

4. Concatenating two strings: If S1 and S2 are two strings, then concatenation operation produces a
string which contains characters of S1 followed by the characters of S2.

1. Initialize I =0 and J=0


2. Repeat step 3 to 4 while I <= LENGTH(str1)
3. SET new_str[J] = str1[I]
4. Set I =I+1 and J=J+1
[END of step2]
5. SET I=0
6. Repeat step 6 to 7 while I <= LENGTH(str2)
7. SET new_str[J] = str1[I]
8. Set I =I+1 and J=J+1
[END of step5]
9. SET new_str[J] = ‘\0’
10. EXIT

5. Reversing a String: If S1= “HELLO”, then reverse of S1 = “OLLEH”. To reverse a string we just
need to swap the first character with the last, second character with the second last character, so on
and so forth.
Step1: [Initialize] SET I=0, J= Length(STR)
Step 2: Repeat Step 3 and 4 while I< Length(STR)
Step 3: SWAP( STR(I), STR(J))
Step 4: SET I = I + 1, J = J – 1
[END OF LOOP]
Step 5: EXIT

5. Explain Character and String functions.


Character Functions:
1. islower( ) returns TRUE if the argument is a lowercase letter.
2. isupper( ) returns TRUE if the argument is an uppercase leter.
3. isascii( ) returns TRUE if the integer argument is in the ASCII range 0-127. Treats 128-
255 as non-ASCII.
4. toascii( ) converts the argument (an arbitrary integer) to a valid
ASCII character number 0-127.
c = toascii(500); //c gets number 116
// (modulus 500%128)
c = toascii('d'); //c gets number 100
5. tolower( ) converts the argument (an uppercase ASCII character) to
lowercase.
c = tolower('Q'); // c becomes 'q'
6. toupper( ) converts the argument (a lowercase ASCII character) to
uppercase.
c = toupper('q'); //c becomes 'Q'
String Functions:
1. strcat (): The purpose of this function is to concatenate or combine two different strings
together.
TRIVENI 53

Syntax: strcat(string1, string2); Example: strcat(“HELLO”, “FRIEND”);

2. strcmp():The purpose of this function is to compare two strings. If two strings are equal then it
returns 0, if string1 is larger than string2 then it returns –ve value, if string2 is larger than
string2 then it returns +ve value.
Syntax: strcmp(string1, string2); Example: strcmp(“HELLO”, “HAI”);
3. strcpy():The purpose of this function is to copy one string to another.
Syntax: strcpy(string1, string2); Example: char name[30]; strcpy(name, “Rama”);
4. strlen(): This function count the number of characters in a string i.e., to find the length of the
string.
Syntax: n = strlen(string1); Example: n = strlen(“Rama”);
5. strrev(): The purpose of this function is to reverse a string. Here the first character becomes the
last and the last character becomes the first character.
Syntax: strrev(string); Example: strrev(“Rama”);
6. strlwr(): This function converts the string into lowercase.
Syntax: strlwr(string); Example: strlwr(“Rama”);
7. strupr(): This function converts the string into lowercase.
Syntax: strupr(string); Example: strupr(“Rama”);
AIM: Write a c program to demonstrate the string functions
#include<stdio.h>
void main( )
{
char s1[10]={“triveni”};
char s2[10]={“college”};
char s3;

clrscr( );

printf(“\nstring length:%d”,strlen(“Triveni”));
printf(“\nstring upper:”%s”,strupr(“triveni”));
printf(“\nstring lower:%s”,strlwr(“TRIVENI”));
printf(“\nstring reverse:%s”,strrev(“triveni”);
printf(“\nstring concat:%s”,strcat(s1,s2));
strcpy(s3,”dennis”)
printf(“\nstring copy:%s”,s3);
printf(“\nstring compare:%d”,strcmp(s1,s2));
getch()
}
TRIVENI 54

UNIT - IV
[Link]

1. What is Pointer? How to declare pointers in C.


Definition: It may be defined as a variable which can store the address of another variable. Address
of variables are always numbers. so pointers can store the numbers only i.e garbage
values(unpredictable values.
x Name of the location
Value of the location
12
1000 Address of the Location
The pointer has the following advantages:
1. Accessing array elements.
2. Passing arguments to functions by reference (i.e. the arguments can be modified).
3. Passing arrays and strings to functions.
4. Creating data structures such as linked lists, trees, graphs, and so on.
5. Obtaining memory from the system dynamically.
Declaration: datatype *variable name;
int *p; here p in pointer to integer
char *p;here p is pointer to character
float *p; here p is pointer to float
Operators used in pointers:
1. Address operator(&)
2. value of address operator/Indirection operator(*)
1. Address operator (&): It returns the address of a specific variable.
Printf(“%d”,x); 12
Printf(“%d”,&x);1000
2. Value of address operator: It return the value stored at specific address
x12
*(&x)*(1000)12

Pointer to Pointer: It is a variable which can store the address of another pointer variable.
Declaration: datatype **variable name;
Example: Program to access array elements using pointers
#include<stdio.h>
main()
{
int a[]={10,20,30,40,50};
int i,*p;
clrscr();
p=&a[0];
printf("\nArray elements:");
for(i=0; i<5; i++)
{
printf("%d\t",*p);
p++;
}
getch();
}
OUTPUT: Array elements: 10 20 30 40 50
3. Write short notes on Pointer Arithmetic?
TRIVENI 55

Pointer Arithmetic: As a pointer holds the memory address of a variable; some arithmetic
operations can be performed with pointers. C supports four arithmetic operators that can be used
with pointer, such as
Addition +
Subtraction -
Incrementation ++
Decrementation - -
Pointers are variables. They are not integers, but they can be displayed as unsigned integers.
The conversion specifier for a pointer is added and subtracted.
Examples:
Increment operator on pointer variable:
if x is pointer variable
1. int *x;
x++;
The value x incremented by 2, since integer type requires 2 bytes long.
2. float *x;
x++;
The value of x incremented by 4, since floating type requires 4 bytes long.
3. char *x;
x++;
The value of x incremented by 1, since character requires 1 byte long.
Every time a pointer is incremented it points to the immediately next location of its base type.
Decrement operator on a pointer variable:
int *x;
x--;
Each time a pointer is decremented, it points to the location of the previous element.
A number can be added to pointer:
int i, *j;
i=5;
j=&i;
j=j+i;
A number can be subtracted from a pointer:
int i=5;
int *j;
j=&i;
j=j-2;
Subtraction of one pointer from another is possible:
This is possible when both variables point to elements of the same array. The resulting value
indicates the number of bytes separating the corresponding array elements.
main( )
{
int a[ ] = {10, 20, 30};
int *i, *j;
i=&a[0];
j=&a[2];
printf(“%d”,j-1);
}
j-1 would print a value 3 and not 6 i.e. the j & i are pointing to locations which are 3 integers
a part.

4. Explain: (i) Null Pointer (ii) Generic Pointer?


TRIVENI 56

(i) Null Pointer: A null pointer which is a special pointer value that is known not to point anywhere.
This means that a NULL pointer does not point to any valid memory address. To declare a null
pointer you may use the predefined constant NULL,
int *ptr = NULL;
We can always check whether a given pointer variable stores address of some variable or
contains a null by writing,
if ( ptr == NULL)
{ Statement block;
}
Null pointers are used in situations if one of the pointers in the program points somewhere
some of the time but not all of the time. In such situations it is always better to set it to a null pointer
when it doesn't point anywhere valid, and to test to see if it's a null pointer before using it.
(ii) Generic Pointer: A generic pointer is pointer variable that has void as its data type. The generic
pointer, can be pointed at variables of any data type. It is declared by writing:
void *ptr;
We need to cast a void pointer to another kind of pointer before using it. Generic pointers are used
when a pointer has to point to data of different types at different times. For ex,
#include<stdio.h>
void main()
{ int x=10;
char ch = ‘A’;
void *gp;
gp = &x; printf("\n Generic pointer points to the integer value = %d", *(int*)gp);
gp = &ch; printf("\n Generic pointer now points to the character %c", *(char*)gp);
}
OUTPUT:
Generic pointer points to the integer value = 10
Generic pointer now points to the character = A

5. Explain (i) Pointer and Arrays (ii) Passing arrays to functions (iii) Difference between Array
Name and Pointer.
A. i. Pointers and Arrays: The concept of arrays is very much related to the pointers. Array
occupies consecutive memory locations.

Array notation is a form of pointer notation. The address of the first element of the array is called
base address. The name of the array is actually a pointer that points to the first element of the array.
Let us use a pointer variable as:
int *ptr;
ptr=&arr[0];
Example:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = &arr[0];
ptr++;
printf(“\n The value of the second element of the array is %d”, *ptr);
(ii) Passing arrays to functions: An array can be passed to a function using pointers. The function
that expects an array can declare the formal parameters in the following two ways:
TRIVENI 57

Func(int arr[]);
OR
Func(int *arr);
When we pass the name of the array to function, the address of the 0 th element of the array copied to
the local pointer variable in the function. We can access all the elements of the array using array
name and index. The declaration should be as:
Func(int arr[, int n);
OR
Func(int *arr, int n);
(iii) Difference between Array Name and Pointer:
1. When memory is allocated for array, its base address cannot be changed during program
execution, means array name is an address constant. However pointer variable may change.
2. Array cannot be assigned to another array. However one pointer variable is assigned to another.
3. For pointer, the address operator returns the address of the operand. For arrays, array name (arr)
and address of the array (&arr) gives the same value.
4. For arrays, sizeof operator returns the number of bytes allocated. For pointers, the sizeof operator
returns the number of bytes used for the pointers.

6. Explain (i) Array of pointers (ii) Pointer and 2D Arrays (iii) Pointer and 3D Arrays.
(i) Array of pointers: An array of pointers can be declared as int *ptr[10]
The above statement declares an array of 10 pointers where each of the pointer points to an
integer variable. For example, look at the code given below.
int *ptr[10];
int p=1, q=2, r=3, s=4, t=5;
ptr[0]=&p;
ptr[1]=&q;
ptr[2]=&r;
ptr[3]=&s;
ptr[4]=&t
Can you tell what will be the output of the following statement?
printf(“\n %d”, *ptr[3]);
Yes, the output will be 4 because ptr[3] stores the address of integer variable s and *ptr[3]
will therefore print the value of s that is 4.
(ii) Pointer and 2D Arrays: Individual elements of the array mat can be accessed using either:
mat[i][j] or *(*(mat + i) + j) or*(mat[i]+j);
• Pointer to an one dimensional array can be declared as,
int arr[]={1,2,3,4,5};
int *parr;
parr=arr;
• Similarly, pointer to a two dimensional array can be declared as,
int arr[2][2]={{1,2},{3,4}};
int (*parr)[2];
parr=arr;
• Look at the code given below which illustrates the use of a pointer to a two dimensional
array.
#include<stdio.h>
main()
{ int arr[2][2]={{1,2}.{3,4}};
int i, (*parr)[2];
parr=arr;
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
TRIVENI 58

printf(" %d", (*(parr+i))[j]);


}
}
OUTPUT
1234
(iii) Pointer and 3D Arrays:
• Pointer to an one dimensional array can be declared as,
int arr[]={1,2,3,4,5};
int *parr;
parr=arr;
• Pointer to a two dimensional array can be declared as,
int arr[2][2]={{1,2},{3,4}};
int (*parr)[2];
parr=arr;
• Pointer to a 3 dimensional array can be declared as,
int arr[2][2][2]={1,2,3,4,5,6,7,8};
int (*parr)[2][2];
parr=arr;

7. Explain (i) Function Pointers (ii) Array of Function Pointer.


(i) Function Pointers:
• This is a useful technique for passing a function as an argument to another function.
• If we have declared a pointer to the function, then that pointer can be assigned to the address
of the right sort of function just by using its name.
• When a pointer to a function is declared, it can be called using one of two forms:
(*func)(1,2); OR func(1,2);
#include <stdio.h>
void print(int n);
main()
{
void (*fp)(int);
fp = print;
(*fp)(10);
fp(20);
return 0;
}
void print(int value)
{ printf("\n %d", value);
}
Comparing Function Pointers: Comparison operator == and != are used as usual.
if(fp >0) // check if initialized
{ if(fp == print)
printf("\n Pointer points to Print");
else
printf("\n Pointer not initialized!");
}
 A function pointer can be passed as a function's calling argument. This is done when you want to
pass a pointer to a callback function.
(ii) Array of Function Pointer: When an array of function is made, the appropriate function is
selected using an index. In the following way, we can define and use an array of function pointers in
C:
TRIVENI 59

1. Use typedef so that ‘fp’ can be used as


Typedef int (*fp) (int, int);
2. Define the array and initialize the elements to NULL. This can be done in two ways:
 fp funcarr[10]={NULL};
 int (*funcarr[10]) (int, int) = {NULL};
3. Assign the function address.
4. Call the function using an index to address the function pointer.

8. Explain (i) Pointer and Strings (ii) Pointer to pointers.


(i) Pointer and Strings: Consider the following program that prints a text.
#include<stdio.h>
main()
{ char str[] = “Oxford”;
char *pstr = str;
printf(“\n The string is : “);
while( *pstr != ‘\0’)
{ printf(“%c’, *pstr);
pstr++;
}
}
(ii) Pointer to pointers: We can use pointers that point to pointers. The pointers in turn, point to data
(or even to other pointers). To declare pointers to pointers just add an asterisk (*) for each level of
reference.
For example, if we have:
int x=10;
int *px, **ppx;
px=&x;
ppx=&px;
Now if we write,
printf(“\n %d”, **ppx);
Then it would print 10, the value of x.
9. Explain memory allocation and memory usage.
A. Memory Allocation: It can be divided into two types:
1. Static Memory Allocation: The process of allocating memory for a variable at declaration
level of a program is known as static memory allocation. In this case the allocated memory may be
wastage or shortage.
2. Dynamic Memory Allocation: The process of allocating memory for a variable at run
time of a program is known as DMA. In this case the user can be allocated only the required bytes of
memory for a variable. That’s why there is no chance to wastage or shortage of memory. We can
perform this task by using the following functions:
malloc( ) calloc( ) realloc( )
These functions are members of header file alloc.h
a) Malloc( ): It returns the base address of allocated memory by allocating required [Link] bytes for a
variable. The base address can be handled by using pointer variable. But the address returned by
malloc( ) may be points to any datatype known as generic pointer. In order to convert these pointers
to the required type we have to use the type allocated memory locations by initially filled up with
garbage values.
Syntax: pointer=(data type *)malloc(sizeof(data type)*[Link] elements);
Eg: a=(int *)malloc(sizeof(int)*10);
TRIVENI 60

b) Calloc( ): It is used to allocate a required bytes of memory for a variable and returns the base
address. In this case initially the locations are filled up with zero’s.
Syntax: pointer=(data type *)calloc(sizeof(data type),[Link] elements);
Eg: a=(int *)calloc(sizeof(int),10);

c) realloc( ): It is used to reallocate the allocated memory. But the contents of old memory locations
will be lost.
Syntax: pointer=(data type *)realloc(sizeof(data type)*[Link] elements);
Eg: a=(int *)realloc(sizeof(int)*10);

Example: Write a C program to demonstrate dynamic memory allocation.


#include<stdio.h>
void main( )
{
int *p,n,i,sum=0;
clrscr( );
printf("Enter [Link] Students:");
scanf("%d",&n);
p=(int *)malloc(n*sizeof (n));
printf("\nEnter marks:\n");
for(i=0;i<n;i++)
{
scanf("%d",(p+i));
sum+=*(p+i);
}
printf("\nThe No Of Students Are :%d",n);
printf("\nThe Grand Total Of All Student Marks Are:%d",sum);
getch( );
}
OUTPUT:
Enter [Link] Students:5
Enter marks:
90
80
70
60
50
The No Of Students Are:5
The Grand Total Of All Student Marks Are:350

10. Explain advantages and drawbacks of pointers.


A. Benefits (use) of pointers in c:
 Pointers provide direct access to memory
 Pointers provide a way to return more than one value to the functions
 Reduces the storage space and complexity of the program
 Reduces the execution time of the program
 Provides an alternate way to access array elements
 Pointers can be used to pass information back and forth between the calling function and
called function.
 Pointers allows us to perform dynamic memory allocation and deallocation.
 Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs
etc.
TRIVENI 61

 Pointers allows us to resize the dynamically allocated memory block.


 Addresses of objects can be extracted using pointers

Drawbacks of pointers in c:
 Un-initialized pointers might cause segmentation fault.
 Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
 Pointers are slower than normal variables.
 If pointers are updated with incorrect values, it might lead to memory corruption.
Basically, pointer bugs are difficult to debug. Its programmer’s responsibility to use pointers
effectively and correctly.
TRIVENI 62

[Link], UNION AND ENUMERATED DATA TYPES

1. What is a structure and explain the rules for declaration, initialization and accessing
structure?
Structures: It may be defined as a secondary data type which can store collection of dissimilar data
elements. In order to define structure we have to use the special keyword “struct”.
Syntax:
struct structurename
{
datatype varialbename;
datatype varialbename;
datatype varialbename;
datatype varialbename;
}structurevariable;

Definition:
struct employee
{
int eno;
char name[20]; 26 bytes elements/members of structure
float sal;
};
struct employee e1,e2;  each structure variables it occupies 26 bytes of memory.

Initialization of Structure: Structure can be initialized by placing the elements with in a pair of
braces and separated by cama operator.
struct employee e={101,”SriRama”,3500.00};
or
[Link],[Link],[Link];
Accessibility of structure elements: Structure elements can be accessed with the help of dot or
arrow operators. On the left side of dot operator there must be a structure variable but on the right
hand side structure element should be there. On the left hand side of arrow operator there should be
pointer to structure but on right hand side structure element must be there.
Eg: [Link],[Link],[Link];
Eg: eeno,ename,esal;

Example:
Using Structure
struct student
{
int rollnum;
char name[100];
int m1,m2,m3,sum;
float avg;
};
struct student s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Rollnum:");
scanf("%d",&[Link]);
TRIVENI 63

printf("\nEnter Student Name:");


scanf("%s",&[Link]);
printf("\nEnter 3 Subjects Marks:");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
[Link]=s.m1+s.m2+s.m3;
[Link]=[Link]/3;
printf(“\nStudent Details are:”);
printf("\n\tRollNum:%d,\n\tName:%s,\n\tM1:%d,\n\tM2:%d,\n\tM3:%d,\n\tTotal:%d,\n\tAverage:
%f",[Link],[Link],s.m1,s.m2,s.m3,[Link],[Link]);
getch();
}

2. Explain (i) Nested Structures (ii) Array of Structures (iii) Structures and Functions
(iv) Self referential Structures.
(i) Nested Structures: If the structure is defined within another structure such a concept is known as
nested structures. The elements of nested structures can be accessed with the help of two or more dot
or arrow operators.
Example:
struct student
{
int rno;
char name[30];
char course[10];
struct marks
{
int m1,m2,m3,sum;
float avg;
}g;
}s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Student Details:");
printf("\nEnter Student RollNum:");
scanf("%d",&[Link]);
printf("\nEnter Student Name:");
scanf("%s",&[Link]);
printf("\nEnter Student Course:");
scanf("%s",&[Link]);
printf("\nEnter Subject1:");
scanf("%d",&s.g.m1);
printf("\nEnter Subject2:");
scanf("%d",&s.g.m2);
printf("\nEnter Subject3:");
scanf("%d",&s.g.m3);
[Link]=s.g.m1+s.g.m2+s.g.m3;
[Link]=[Link]/3;
printf("\nStudent Rollnum:%d",[Link]);
printf("\nStudent Name:%s",[Link]);
printf("\nStudent Course:%s",[Link]);
printf("\nMarks1:%d",s.g.m1);
TRIVENI 64

printf("\nMarks2:%d",s.g.m2);
printf("\nMarks3:%d",s.g.m3);
printf("\nTotal Marks of Student:%d",[Link]);
printf("\nAverage Marks of Student:%f",[Link]);
getch();
}
(ii) Array of Structure: It may be defined as collection of similar structure stored in the adjacent
memory locations.
Example:
#include<stdio.h>
struct std
{
int rno;
char name[30];
};
void main()
{
struct std s[100];
int i,n;
clrscr();
printf("Enter [Link] Students:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter RollNum:");
scanf("%d",&s[i].rno);
fflush(stdin);
printf("\nEnter Name:");
gets(s[i].name);
fflush(stdin);
}
printf("\nThe Details are:\n");
for(i=1;i<=n;i++)
{
printf("\nRno:%d\nName:%s",s[i].rno,s[i].name);
}
getch();
}

(iii) Structure using functions: Struct variables can also be passed to a function. We may either
pass individual structure elements or the entire structure variables at one go.
#include<stdio.h>
struct book
{
int bno;
char bname[20];
};
void main()
{
struct book b={101,"JAVA"};
void disp();
clrscr();
TRIVENI 65

disp(b);
getch();
}
void disp(struct book b)
{
printf("\nBook no:%d",[Link]);
printf("\nBook name:%s",[Link]);
}

(iv) Passing Structures through Pointers: C allows to crerate a pointer to a structure. Like in other
cases, a pointer to a structure is never itself a structure, but merely a variable that holds the address
of a structure. The syntax to declare a pointer to a structure can be given as
struct struct_name
{
data_type member_name1;
data_type member_name2;
.....................................
}*ptr; OR
struct struct_name *ptr;
For our student structure we can declare a pointer variable by writing
struct student *ptr_stud, stud;
Example:
struct student
{
int rollnum;
char name[100];
int m1,m2,m3,sum;
float avg;
};
struct student s,*p;
#include<stdio.h>
void main()
{
p=&s;
clrscr();
printf("Enter Rollnum:");
scanf("%d",&p->rollnum);
printf("\nEnter Student Name:");
scanf("%s",&p->name);
printf("\nEnter 3 Subjects Marks:");
scanf("%d%d%d",&p->m1,&p->m2,&p->m3);
p->sum=p->m1+p->m2+p->m3;
p->avg=p->sum/3;
printf(“\nStudent Details are:”);
printf("\n\tRollNum:%d,\n\tName:%s,\n\tM1:%d,\n\tM2:%d,\n\tM3:%d,\n\tTotal:%d,\n\tAverage:
%f",p->rollnum,p->name,p->m1,p->m2,p->m3,p->sum,p->avg);
getch();
}
3. Write short notes on Unions?
A. Union is user defined data type used to stored data under unique variable name at single memory
[Link] is similar to that of structure. Syntax of union is similar to structure. But the major
difference between structure and union is 'storage.' In structures, each member has its own
TRIVENI 66

storage location, whereas all the members of union use the same location. Union contains many
members of different types, it can handle only one member at a time.
To declare union data type, 'union' keyword is used.
Union holds value for one data type which requires larger storage among their members.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
Example:
union techno
{
int comp_id;
char nm;
float sal;
}tch;
In above example, it declares tch variable of type union. The union contains three members as data
type of int, char, float. We can use only one of them at a time.
* Memory Allocation :

Fig : Memory allocation for union

Example:
Write a C program to demonstrate the unions.
#include<stdio.h>
union student
{
int rno;
char name[20];
float fees;
}s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Std Details:");
scanf("%d%s%f",&[Link],&[Link],&[Link]);
printf("\nThe Std Detials are:");
printf("\nRollNum:%d\nName:%s\nFees:%f",[Link],[Link],[Link]);
getch();
}
TRIVENI 67

4. Explain Enumerated data types.


The enumerated data type is a user defined type based on the standard integer type. To define
enumerated data types, enum keyword is used. The syntax of creating an enumerated data type
can be given as below.
enum enumerationname
{
identifier1,
----
};
Consider the example given below which creates a new type of variable called COLORS to store
colors constants.
enum COLORS
{
RED,
BLUE,
BLACK, GREEN, YELLOW, PURPLE, WHITE};
Enum variables: The syntax for declaring a variable of an enumerated data type can be given as,
enum enumerationname variable1,---;
So to create a variable of COLORS, we may write:
enum COLORS bg_color;
Another way to declare a variable can be as illustrated in the statement below.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE}
bg_color, fore_color;
Using the typedef keyword:
C permits to use typedef keyword for enumerated data types. For ex, if we write
typedef enum COLORS color;
Then, we can straight-away declare variables by writing
color forecolor = RED;
Assigning values to enumerated variables:
Once the enumerated variable has been declared, values can be stored in it. However, an
enumerated variable can hold only declared values for the type. For example, to assign the color
black to the back ground color, we will write,
bg_color = BLACK;
Once an enumerated variable has been assigned a value, we can store its value in another variable
of the same type as shown below.
enum COLORS bg_color, border_color;
bg_color = BLACK;
border_color = bg_color;

Example: Write a Program to demonstrate the enums.


#include<stdio.h>
enum rest
{
idly=10,
dosa=15,
voda=20
};
enum rest r1, r2;
main()
{
r1=idly;
r2=dosa;
TRIVENI 68

clrscr();
if(r1==r2)
printf("\nBoth are equal");
else
printf("\nBoth are not equal");
getch();
}
Output:
Both are not equal

[Link] differences b/w structures and unions

Structure Union
[Link] keyword struct is used to define a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a 2. When a variable is associated with a union,
structure, the compiler allocates the memory the compiler allocates the memory by
for each member. The size of structure is considering the size of the largest memory. So,
greater than or equal to the sum of sizes of its size of union is equal to the size of largest
members. The smaller members may end with member.
unused slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.
4. The address of each member will be in 4. The address is same for all the members of a
ascending order This indicates that memory for union. This indicates that every member begins
each member will start at different offset at the same offset value.
values.
5 Altering the value of a member will not 5. Altering the value of any of the member will
affect other members of the structure. alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.
7. Several members of a structure can initialize 7. Only the first member of a union can be
at once. initialized.
TRIVENI 69

UNIT - V
[Link]

1. What is a file? Explain.


A. A file is a collection of bytes stored on a secondary storage device, which is generally a disk of
some kind. The collection of bytes may be interpreted, for example, as characters, words, lines,
paragraphs and pages from a textual document; fields and records belonging to a database; or pixels
from a graphical image.
Disk I/O Functions: These functions are used to perform i/o operations on the secondary
storage devices. In order to perform these operations we have to use a particular location in the
memory known as a file i.e file is an entity which can be store collection of information.
Types of disk I/O functions:
1. Unformatted Disk I/O functions 2. Formatted Disk I/O functions

1. Unformatted Disk I/O functions: These functions are used to access either character or string
type of information on secondary storage devices.
fgetc( ): It gets a character from a specific file.
Syntax: variable=fgetc(file ponter);
fputc( ): It prints a character into a specific file.
Syntax: fputc(character, file pointer);
fgets( ): It gets a string from a specific file.
Syntax: fgets(string name, max size, file pointer);
fputs( ): It prints a string into a specific file.
Syntax: fputs(string, file pointer);
2. Formatted Disk I/O functions: These functions are used to access any type of information from
or to the secondary storage devices.
fscanf( ): It is used to read any type of information from a specific file.
Syntax: fscanf(file pointer, ”format string specifies”, list of variables);
fprintf( ): It is used to print any type of information in required format into a specific file.
Syntax: fprintf(file pointer, ”format string specifies”, list of operands);

II. Record I/O functions: These functions are used to access an entire record from or to
a specific file.
fwrite( ): It prints an entire record into a specific file.
Syntax: fwrite(address of record, sizeof(record), [Link] records, file pointer);
fread( ): It gets an entire record from specific file.
Syntax: fread(address of record, sizeof(record), [Link] records, file pointer);
III. Other functions in files:
fopen( ): to open a file in specific mode.
Syntax: file pointer=fopen(“Filename”,mode);
Here mode may be one of the following:
Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing, if it does not exist then a new file is created. Here your
program will start writing content from the beginning of the file.
a Opens a text file for writing in appending mode, if it does not exist then a new file is
created. Here your program will start appending content in the existing file content.
r+ Opens a text file for reading and writing both.
w+ Opens a text file for reading and writing both. It first truncate the file to zero length if it
exists otherwise create the file if it does not exist.
a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The
reading will start from the beginning but writing can only be appended.
TRIVENI 70

fclose( ): To close a file.


Syntax: fclose(file pointer);
fseek( ): It is used to move the file pointer from one record to another record.
Syntax: fseek(file pointer, [Link] bytes to move, mode);
In above case the mode may be SEEK_CUR, SEEK_END, SEEK_SET
rewind( ): It is used to place the file pointer at first record of the file.
Syntax: rewind(file pointer);
remove( ): To delete a file.
Syntax: remove(“File name”);
rename( ): It renames the fiel with another name.
Syntax: rename(old filename, new filename);

Macros: In files we have to use the following macros:


 NULL: It denotes a zero.
 EOF: It denotes an end of file character
Note: For dos based systems it is used ctrl+z.
Example:

Write a C program to count numbers of (i) Words (ii) Lines (iii) Special characters in a given
text.
#include<stdio.h>
void main( )
{
FILE *fp;
char ch;
int noc=0, now=1, nol=0, nos=0;
clrscr( );
fp=fopen("[Link]","r");
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
noc++;
if(ch==' ')
{
now++;
nos++;
}
if(ch=='\n')
nol++;
}
fclose(fp);
printf("\nNumber of characters:%d",noc);
printf("\nNumber of words:%d",now);
printf("\nNumber of lines:%d",nol);
printf("\nNumber of spaces:%d",nos);
getch( );
}

OUTPUT:
TRIVENI 71

Number of characters:232
Number of words:27
Number of lines:20
Number of spaces:26

2. Explain error handling during the file operations.


It is not uncommon that an error may occur while reading data from or writing data to a file. For
example, an error may arise
• When you try to read a file beyond EOF indicator
• When trying to read a file that does not exist
• When trying to use a file that has not been opened
• When trying to use a file in un-appropriate mode. That is, writing data to a file that has been
opened for reading
• When writing to a file that is write-protected
The function ferror() is used to check for errors in the stream. Its prototype can be given as:
int ferror ( FILE *stream);
1) clearerr():
• The function clearerr() is used to clears the end-of-file and error indicators for the stream. Its
protoype can be given as
void clearerr( FILE *stream);
• The clearerr() clears the error for the stream pointed to by stream. The function is used
because error indicators are not automatically cleared; once the error indicator for a specified
stream is set, operations on that stream continue to return an error value until clearerr, fseek,
fsetpos, or rewind is called.

2) perror():
• perror() stands for print error. The perror() function is used to handle errors in C programs.
When called, perror() displays a message on stderr describing the most recent error that
occurred during a library function call or system call. The prototype of perror() can be given
as
void perror(char *msg);
• The perror() takes one argument msg which points to an optional user-defined message. This
message is printed first, followed by a colon and the implementation-defined message that
describes the most recent error.
• If a call to perror() is made when no error has actually occurred, then a “No error” will be
displayed. The most important thing to remember is that a call to perror() does nothing to
deal with the error condition.

3. What are the functions available for selecting a record randomly?


1) fseek():
• fseek() is used to reposition a binary stream. The prototype of fseek() can be given as,
int fseek( FILE *stream, long offset, int origin);
• fseek() is used to set the file position pointer for the given stream. Offset is an integer value
that gives the number of bytes to move forward or backward in the file. Offset may be
positive or negative, provided it makes sense. For example, you cannot specify a negative
offset if you are starting at the beginning of the file. The origin value should have one of the
following values (defined in stdio.h):
1. SEEK_SET: to perform input or output on offset bytes from start of the file
2. SEEK_CUR: to perform input or output on offset bytes from the current position in the file
3. SEEK_END: to perform input or output on offset bytes from the end of the file
4. SEEK_SET, SEEK_CUR and SEEK_END are defined constants with value 0, 1 and 2
respectively.
TRIVENI 72

• On successful operation, fseek() returns zero and in case of failure, it returns a non-zero
value. For example, if you try to perform a seek operation on a file that is not opened in
binary mode then a non-zero value will be returned.
fseek() can be used to move the file pointer beyond a file, but not before the beginning.
2) rewind():
• rewind() is used to adjust the position of file pointer so that the next I/O operation will take
place at the beginning of the file. It’s prototype can be given as
void rewind( FILE *f );
• rewind() is equivalent to calling fseek() with following parameters: fseek(f,0L,SEEK_SET);
3) fgetpos():
• The fgetpos() is used to determine the current position of the stream. It’s prototype can be
given as
int fgetpos(FILE *stream, fpos_t *pos);
• Here, stream is the file whose current file pointer position has to be determined. pos is used to
point to the location where fgetpos() can store the position information. The pos variable is of
type fops_t which is defined in stdio.h and is basically an object that can hold every possible
position in a FILE.
• On success, fgetpos() returns zero and in case of error a non-zero value is returned. Note that
the value of pos obtained through fgetpos() can be used by the fsetpos() to return to this same
position.
4) fsetpos():
• The fsetpos() is used to move the file position indicator of a stream to the location indicated
by the information obtained in "pos" by making a call to the fgetpos(). Its prototype is
int fsetpos( FILE *stream, const fops_t pos);
• Here, stream points to the file whose file pointer indicator has to be re-positioned. pos points
to positioning information as returned by "fgetpos".
• On success, fsetpos() returns a zero and clears the end-of-file indicator. In case of failure it
returns a non-zero value
5) ftell():
• The ftell function is used to know the current position of file pointer. It is at this position at
which the next I/O will be performed. The syntax of the ftell() defined in stdio.h can be given
as: long ftell (FILE *stream);
• On successful, ftell() function returns the current file position (in bytes) for stream. However,
in case of error, ftell() returns -1.
• When using ftell(), error can occur either because of two reasons:
1. First, using ftell() with a device that cannot store data (for example, keyboard)
2. Second, when the position is larger than that can be represented in a long integer.
6) remove():
• The remove() as the name suggests is used to erase a file. The prototype of remove() as given
in stdio.h can be given as,
int remove(const char *filename);
• The remove() will erase the file specified by filename. On success, the function will return
zero and in case of error, it will return a non-zero value.

4. Explain: (i) Renaming a File (ii) Creating temporary File.


(i) Renaming a File:
• The rename(), as the name suggests is used to renames a file. The prototype is:
int rename(const char *oldname, const char *newname)
• Here, the oldname specifies the pathname of the file to be renamed and the newname gives
the new pathname of the file.
TRIVENI 73

• On success, rename() returns zero. In case of error, it will return a non-zero value will set the
errno to indicate the error.
(ii) Creating temporary File:
• The tmpfile() function is used to create a temporary file. The tmpfile() opens the
corresponding stream with access parameters set as “w+”. The file created with tmpfile() will
be automatically deleted when all references to the file are closed. That is, the file created
will be automatically closed and erased when the program has been completely executed.
• The prototype of tmpfile() as given is stdio.h header file is,
FILE* tmpfile(void);
• On success, tmpfile() will return a pointer to the stream of the file that is created. In case of
error, the function will return a null pointer [and set errno to indicate the error.
TRIVENI 74

LAB MANUAL

[Link] program

1. Swap two numbers


2. Quadratic equations
3. Reverse of a number
4. Palindrome or not
5. Prime or not
6. Pascal triangle
7. Perfect or not
8. Armstrong or not
9. Sum of digits
10. Bubble sort
11 Addition & subtraction of two matrices
12 Multiplication of two matrices
13 Transpose of a matrix
14 Demonstration of functions (with argument, with return value)
15 Call by value & call by reference
16 Factorial of a number
17 Strings (Concatenation)
18 String palindrome or not
19 Structures
20 Unions
21 Files
22 Fputs(), fgets() functions
23 Enums
24 Arrays using pointers
25 Dynamic memory allocation
TRIVENI 75

1. SWAP TWO NUMBERS


Aim: Write a program to read two variables then swap them without using third variable.

Program:

#include<stdio.h>
void main()
{
int a,b;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&a,&b);
printf("\nBefore Swapping %d and %d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter Swapping %d and %d",a,b);
getch();
}

Output:

Enter Two Values:


12
13
Before Swapping 12 and 13
After Swapping 13 and 12
TRIVENI 76

2. QUADRATIC EQUATION
Aim: Write a c program to print roots of a quadratic equation.

Program:

#include<stdio.h>
#include<math.h>
void main()
{
float a,b,c,desc,root1,root2;
clrscr();
printf("\n\t\tEnter values for a,b and c:\n");
scanf("%f%f%f",&a,&b,&c);
desc=(b*b)-(4*a*c);
if(desc<0)
printf("\n\n\t\tRoots are Imaginary");
else if(desc>0)
{
printf("\n\n\t\tRoots are Real");
root1=(-b+sqrt(desc))/(2.0*a);
root2=(-b-sqrt(desc))/(2.0*a);
printf("\n\n\t\t\tRoot-1=%5.2f\n\n\t\t\tRoot- =%5.2f",root1,root2);
}
else
{
printf("\n\n\t\tRoots are Equal");
root1=(-b+sqrt(desc))/(2.0*a);
root2=(-b-sqrt(desc))/(2.0*a);
printf("\n\n\t\t\tRoot-1=%5.2f\n\n\t\t\tRoot-2=%5.2f", root1,root2);
}
getch();
}

Output:

Enter values for a,b and c:1.0 2.0 1.0


Roots are Equal
Root – 1=-1.00
Root – 2=-1.00
TRIVENI 77

3. REVERSE OF A NUMBER
Aim: Write a program to calculate reverse of a given number.

Program:

#include<stdio.h>
void main()
{
int d;
long n,rev=0;
clrscr();
printf("Enter N Value:");
scanf("%ld",&n);
while(n>0)
{
d=n%10;
rev=(rev*10)+d;
n=n/10;
}
printf("\nReverse of a given Num:%ld",rev);
getch();
}

Output:

Enter N Value:123
Reverse of a given Num:321
TRIVENI 78

4. PALINDROME OR NOT
Aim: Write a program to check whether the given number is palindrome or not.

Program:

#include<stdio.h>
#include<stdio.h>
void main()
{
long n, rev=0,t;
int d;
clrscr();
printf("Enter a no:");
scanf("%ld",&n);
t=n;
while(n>0)
{
d=n%10;
rev=(rev*10)+d;
n=n/10;
}
if(t==rev)
printf("\nIt is palindrome");
else
printf("\nIt is not palindrome");
getch();
}

Output:

Enter a number:121
It is not palindrome:121
TRIVENI 79

5. PRIME OR NOT
Aim: Write a c program to check whether the given num is prime or not.

Program:

#include<stdio.h>
void main()
{
int n, i, check=1;
clrscr();
printf("Enter a Number:");
scanf("%d",&n);
for(i=2; i<n; i++)
if(n%i == 0)
{
check=0;
break;
}
if(check==1)
printf("\nThe given no is prime");
else
printf("\nThe given no is not prime");
getch();
}

Output – 1:

Enter a number: 5
The given no is prime

Output – 2:
Enter a number: 9
The given no is not prime
TRIVENI 80

6. PASCAL TRIANGLE
Aim: Write a program to calculate Pascal Triangle.
1
1 1
1 2 1
1 3 3 1
1 4 5 4 1
Program:

#include<stdio.h>
void main()
{
int i,j,k=1;
clrscr();
for(i=0;i<5;i++)
{
for(j=0;j<40-i;j++)
printf(" ");
for(j=0;j<=i;j++)
{
if(j==0)
{
k=1;
}
else
{
k=(i*k-j*k+k)/j;
}
printf(" %d",k);
}
printf("\n");
}
getch();
}

Output:
1
1 1
1 2 1
1 3 3 1
1 4 5 4 1
TRIVENI 81

7. PERFECT OR NOT
Aim: Write a program to check whether the given no is perfect or not.

Program:

#include<stdio.h>
void main()
{
int n, s=0, i;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
for(i=1; i<n; i++)
if(n%i == 0)
s+=i;
if(n==s)
printf("\nThe given no is perfect:%d",s);
else
printf("\nThe given no is not perfect:%d",s);
getch();
}

Output – 1:

Enter a number:6
The given no is perfect:6

Output – 2:

Enter a number:9
The given no is not perfect:4
TRIVENI 82

9. ARMSTRONG OR NOT
Aim: Write a c program to check whether the given no is Armstrong or not.

Program:

#include<stdio.h>
void main()
{
long n, sd=0, d, t;
clrscr();
printf("Enter a number:");
scanf("%ld",&n);
t=n;
while(n>0)
{
d=n%10;
sd=sd+(d*d*d);
n=n/10;
}
if(t==sd)
printf("\nThe given no is Armstrong:%ld",sd);
else
printf("\nThe given no is not Armstrong:%ld",sd);
getch();
}

Output – 1:

Enter a number:153
The given no is Armstrong:153

Output – 2:

Enter a number:125
The given no is not Armstrong:134
TRIVENI 83

9. SUM OF DIGITS
Aim: Write a program to print sum of digits of the given number.

Program:

#include<stdio.h>
void main()
{
long n;
int sd=0, d;
clrscr();
printf("Enter a number:");
scanf("%ld",&n);
while(n>0)
{
d=n%10;
sd+=d;
n=n/10;
}
printf("\nSum of digits:%d",sd);
getch();
}

Output – 1:

Enter a number:123
Sum of digits:6

Output – 2:
Enter a number:456
Sum of digits:15
TRIVENI 84

10. BUBBLE SORT


Aim: Write a program to sort given list of numbers by using Bubble Sort.

Program:
#include<stdio.h>
void main()
{
int a[100],i,j,n,t;
clrscr();
printf("Enter N Array Size:");
scanf("%d",&n);
printf("Enter Array Elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nBefore Sorting Array Elements:\n");
for(i=0;i<n;i++)
{
printf(" %d",a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf("\nAfter Sorting Array Elements:\n");
for(i=0;i<n;i++)
{
printf(" %d",a[i]);
}
getch();
}
Output:
Enter N Array Size:5
Enter Array Elements:89 12 34 21 85
Before Sorting Array Elements:
89 12 34 21 85
After Sorting Array Elements: 12 21 34 85 89
TRIVENI 85

11. ADDITION & SUBTRACTION OF TWO MATRICES


Aim: Write a program to print addition and subtraction of two matrices.

Program:

#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],d[10][10],i,j,r1,c1,r2,c2;
clrscr();
printf("Enter R1*C1 Matrix Size:");
scanf("%d%d",&r1,&c1);
printf("Enter R2*C2 Matrix Size:");
scanf("%d%d",&r2,&c2);
if(r1!=r2||c1!=c2)
{
printf("\nMatrix Add & Sub is not possible");
exit(0);
}
printf("\nEnter R1*C1 Matrix Elements:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter R2*C2 Matrix Elements:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
//Addition
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
//Subtraction
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
d[i][j]=a[i][j]-b[i][j];
}
}
TRIVENI 86

printf("\nAddition of Two Matrix:\n");


for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf(" %d",c[i][j]);
}
printf("\n");
}
printf("\nSubtraction of Two Matrix:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf(" %d",d[i][j]);
}
printf("\n");
}
getch();
}

Output:

Enter R1*C1 Matrix Size:2 2


Enter R2*C2 Matrix Size:2 2
Enter R1*C1 Matrix Elements:7 8
9 5

Enter R2*C2 Matrix Elements:5 4


3 2

Addition of Two Matrix:


12 12
12 7

Subtraction of Two Matrix:


24
63
TRIVENI 87

12. MULTIPLICATION OF TWO MATRICES


Aim: Write a program to print multiplication of two matrices.

Program:

#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2,k;
clrscr();
printf("Enter R1*C1 Matrix Size:");
scanf("%d%d",&r1,&c1);
printf("Enter R2*C2 Matrix Size:");
scanf("%d%d",&r2,&c2);
if(r1!=c2)
{
printf("\nMatrix Mul is not possible");
exit(0);
}
printf("\nEnter R1*C1 Matrix Elements:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter R2*C2 Matrix Elements:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
// Calculate Matrix Multiplication
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
printf("\nMultiplication of Two Matrix:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf(" %d",c[i][j]);
}
TRIVENI 88

printf("\n");
}
getch();
}

Output:

Enter R1*C1 Matrix Size:2 2


Enter R2*C2 Matrix Size:2 2
Enter R1*C1 Matrix Elements:4 3
2 1
Enter R2*C2 Matrix Elements:5 6
7 8
Multiplication of Two Matrix:
41 48
17 20
TRIVENI 89

13. TRANSPOSE OF MATRICES


Aim: Write a program to print Transpose of a given matrix.

Program:

#include<stdio.h>
void main()
{
int a[10][10],i,j,r1,c1;
clrscr();
printf("Enter R1*C1 Matrix Size:");
scanf("%d%d",&r1,&c1);
printf("\nEnter R1*C1 Matrix Elements:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nThe Matrix Elements:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
printf("\nTranspose of a Matrix:\n");
for(i=0;i<c1;i++)
{
for(j=0;j<r1;j++)
{
printf(" %d",a[j][i]);
}
printf("\n");
}
getch();
}
Output:

Enter R1*C1 Matrix Size:2 2


Enter R1*C1 Matrix Elements:1 2
3 4
The Matrix Elements:
12
34

Transpose of a Matrix:
13
24
TRIVENI 90

14. DEMONSTRATION OF FUNCTIONS


Aim: Write a program to print sum of any two numbers by using User defined functions
i. Function without argument without return value
ii. Function without argument with return value
iii. Function with argument without return value
iv. Function with argument with return value

Program:

i. Function without argument without return value


#include<stdio.h>
void sum()
{
int a, b;
printf("Enter Two Numbers:");
scanf("%d%d",&a,&b);
printf("\nAddition:%d",a+b);
}
void main()
{
clrscr();
sum();
getch();
}

Output:

Enter Two Values:12 13


Addition:25

ii. Function without argument with return value


#include<stdio.h>
int sum()
{
int a,b,s;
printf("Enter Two Values:");
scanf("%d%d",&a,&b);
s=a+b;
return(s);
}
void main()
{
int s;
clrscr();
printf("\nAddition:%d",sum());
getch();
}

Output:

Enter Two Values:12 13


TRIVENI 91

Addition:25
iii. Function with argument without return value
#include<stdio.h>
void sum(int a, int b)
{
printf("\nAddition:%d",a+b);
}
void main()
{
int a,b;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&a,&b);
sum(a,b);
getch();
}
Output:

Enter Two Values:12 13


Addition:25

iv. Function with argument with return value


#include<stdio.h>
int sum(int x, int y)
{
return x+y;
}
void main()
{
int a,b;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&a,&b);
printf("\nAddition:%d",sum(a,b));
getch();
}

Output:
Enter Two Values:12 13
Addition:25
TRIVENI 92

15. CALL BY VALUE & CALL BY REFERENCE


Aim: Write a Program by using
Program:
a. call by value
void swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
printf("\nAfter Swapping %d and %d",a,b);
}
void main()
{
int x,y;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&x,&y);
printf("\nBefore Swapping %d and %d",x,y);
swap(x,y);
getch();
}
Output:
Enter Two Values:12 23
Before Swapping 12 and 23
After Swapping 23 and 12

b. Call by reference
void swap(int *a,int *b)
{
int t;
printf("\nBefore Swapping %d and %d",*a,*b);
t=*a;
*a=*b;
*b=t;
printf("\nAfter Swapping %d and %d",*a,*b);
}
void main()
{
int x,y;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&x,&y);
swap(&x,&y);
getch();
}
Output:
Enter Two Values:12 23
Before Swapping 12 and 23
After Swapping 23 and 12
TRIVENI 93

16. FACTORIAL OF A NUMBER (RECURSIVE FUNCTION)


Aim: Write a recursive function to calculate factorial value of N

Program:

#include<stdio.h>
void main()
{
long fact(int);
int n;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
printf("\nFactorial of a given number:%ld",fact(n));
getch();
}
long fact(int n)
{
if(n<=1)
return(1);
else
return(n*fact(n-1));
}

Output – 1:

Enter a number:5
Factorial of a given number:120

Output – 2:

Enter a number:6
Factorial of a given number:720
TRIVENI 94

17. STRINGS
AIM
Write a c program to demonstrate the string functions

SOURCE CODE
#include<stdio.h>
void main( )
{
char s1[10]={“triveni”};
char s2[10]={“college”};
char s3;
clrscr( );
printf(“\nstring length:%d”,strlen(“Triveni”));
printf(“\nstring upper:”%s”,strupr(“triveni”));
printf(“\nstring lower:%s”,strlwr(“TRIVENI”));
printf(“\nstring reverse:%s”,strrev(“triveni”);
printf(“\nstring concat:%s”,strcat(s1,s2));
strcpy(s3,”dennis”)
printf(“\nstring copy:%s”,s3);
printf(“\nstring compare:%d”,strcmp(s1,s2));
getch()
}
TRIVENI 95

18. STRING PALINDROME OR NOT


Aim: Write a ‘C ‘ program to check whether the given string is palindrome or not.

Program:

#include<stdio.h>
void main()
{
char s[10];
int i,len=0,check=1,j;
clrscr();
puts("Enter a string:");
gets(s);
for(i=0; s[i]!='\0'; i++)
len++;
for(i=0, j=len-1; i<(len/2); i++, j--)
if(s[i]!=s[j])
{
check=0;
break;
}
if(check==1)
puts("It is a string palindrome");
else
puts("It is not a string palindrome");
getch();
}

Output – 1:

Enter a string: sathyaveni


It is not a string palindrome

Output – 2:

Enter a string: LIRIL


It is a string palindrome
TRIVENI 96

19. STRUCTURES
Aim: Write a program by using structures.
Program:
a. Using Structure
struct student
{
int rollnum;
char name[100];
int m1,m2,m3,sum;
float avg;
};
struct student s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Rollnum:");
scanf("%d",&[Link]);
printf("\nEnter Student Name:");
scanf("%s",&[Link]);
printf("\nEnter 3 Subjects Marks:");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
[Link]=s.m1+s.m2+s.m3;
[Link]=[Link]/3;
printf(“\nStudent Details are:”);
printf("\n\tRollNum:%d,\n\tName:%s,\n\tM1:%d,\n\tM2:%d,\n\tM3:%d,\n\tTotal:%d,\n\tAverage:
%f",[Link],[Link],s.m1,s.m2,s.m3,[Link],[Link]);
getch();
}
Output:
Enter Rollnum:1001
Enter Student Name:Rama
Enter 3 Subjects Marks:56 78 89
Student Details are:
RollNum:1001,
Name:Rama,
M1:56,
M2:78,
M3:89,
Total:223,
Average:74.000000

b. Using Nested Structure


struct student
{
int rno;
char name[30];
char course[10];
struct marks
{
int m1,m2,m3,sum;
float avg;
TRIVENI 97

}g;
}s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Student Details:");
printf("\nEnter Student RollNum:");
scanf("%d",&[Link]);
printf("\nEnter Student Name:");
scanf("%s",&[Link]);
printf("\nEnter Student Course:");
scanf("%s",&[Link]);
printf("\nEnter Subject1:");
scanf("%d",&s.g.m1);
printf("\nEnter Subject2:");
scanf("%d",&s.g.m2);
printf("\nEnter Subject3:");
scanf("%d",&s.g.m3);
[Link]=s.g.m1+s.g.m2+s.g.m3;
[Link]=[Link]/3;
printf("\nStudent Rollnum:%d",[Link]);
printf("\nStudent Name:%s",[Link]);
printf("\nStudent Course:%s",[Link]);
printf("\nMarks1:%d",s.g.m1);
printf("\nMarks2:%d",s.g.m2);
printf("\nMarks3:%d",s.g.m3);
printf("\nTotal Marks of Student:%d",[Link]);
printf("\nAverage Marks of Student:%f",[Link]);
getch();
}
Output:
Enter Student Details:
Enter Student RollNum:1001
Enter Student Name: Ramya
Enter Student Course: Bsc
Enter Subject1:78
Enter Subject2:89
Enter Subject3:91
Student Rollnum:1001
Student Name:Ramya
Student Course:Bsc
Marks1:78
Marks2:89
Marks3:91
Total Marks of Student:258
Average Marks of Student:86.000000

c. Pointers Using Structures


struct student
{
int rollnum;
TRIVENI 98

char name[100];
int m1,m2,m3,sum;
float avg;
};
struct student s,*p;
#include<stdio.h>
void main()
{
p=&s;
clrscr();
printf("Enter Rollnum:");
scanf("%d",&p->rollnum);
printf("\nEnter Student Name:");
scanf("%s",&p->name);
printf("\nEnter 3 Subjects Marks:");
scanf("%d%d%d",&p->m1,&p->m2,&p->m3);
p->sum=p->m1+p->m2+p->m3;
p->avg=p->sum/3;
printf(“\nStudent Details are:”);
printf("\n\tRollNum:%d,\n\tName:%s,\n\tM1:%d,\n\tM2:%d,\n\tM3:%d,\n\tTotal:%d,\n\tAverage:
%f",p->rollnum,p->name,p->m1,p->m2,p->m3,p->sum,p->avg);
getch();
}
Output:
Enter Rollnum:1001
Enter Student Name:Sathyaveni
Enter 3 Subjects Marks:89 78 91
Student Details are:
RollNum:1001,
Name:Sathyaveni,
M1:89,
M2:78,
M3:91,
Total:258,
Average:86.000000

d. Array Using Structures:


#include<stdio.h>
struct std
{
int rno;
char name[30];
};
void main()
{
struct std s[100];
int i,n;
clrscr();
printf("Enter [Link] Students:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
TRIVENI 99

printf("\nEnter RollNum:");
scanf("%d",&s[i].rno);
fflush(stdin);
printf("\nEnter Name:");
gets(s[i].name);
fflush(stdin);
}
printf("\nThe Details are:\n");
for(i=1;i<=n;i++)
{
printf("\nRno:%d\nName:%s",s[i].rno,s[i].name);
}
getch();
}
Output:
Enter [Link] Students:3
Enter RollNum:1001
Enter Name:Anupama
Enter RollNum:1002
Enter Name:Harika
Enter RollNum:1003
Enter Name:Divya
The Details are:
Rno:1001
Name:Anupama
Rno:1002
Name:Harika
Rno:1003
Name:Divya
e. Structures using Functions
#include<stdio.h>
struct book
{
int bno;
char bname[20];
};
void main()
{
struct book b={101,"JAVA"};
void disp();
clrscr();
disp(b);
getch();
}
void disp(struct book b)
{
printf("\nBook no:%d",[Link]);
printf("\nBook name:%s",[Link]);
}
Output:
Book no:101
Book name:JAVA
TRIVENI 100

20. UNIONS
Aim: Write a Program to demonstrate the unions.

Program:

union student
{
int rno;
char name[20];
float fees;
}s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Std Details:");
scanf("%d%s%f",&[Link],&[Link],&[Link]);
printf("\nThe Std Detials are:");
printf("\nRollNum:%d\nName:%s\nFees:%f",[Link],[Link],[Link]);
getch();
}
Output:

Enter Std Details:1001


Sathyaveni
5000
The Std Detials are:
RollNum:16384
Name:Sathyaveni
Fees:5000.000000
TRIVENI 101

21. FILES
Aim: Program to count numbers of (i)words (ii)lines (iii)special characters in a given text.

Program:

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int noc=0, now=1, nol=0, nos=0;
clrscr();
fp=fopen("p1.c","r");
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
noc++;
if(ch==' ')
{
now++;
nos++;
}
if(ch=='\n')
nol++;
}
fclose(fp);
printf("\nNumber of characters:%d",noc);
printf("\nNumber of words:%d",now);
printf("\nNumber of lines:%d",nol);
printf("\nNumber of spaces:%d",nos);
getch();
}
Output:
Number of characters:232
Number of words:27
Number of lines:20
Number of spaces:26
TRIVENI 102

22. fputs(), fgets() FUNCTIONS


Aim: Program to create a file to store and retrieve strings using fputs( ) and fgets( ).

Program:

#include<stdio.h>
void main()
{
FILE *f1;
char s[80];
clrscr();
printf("\nOpening a File in Writing Mode:\n");
printf("Enter the data into file (Press Ctrl+z at last)");
f1=fopen("[Link]","w");
while(strlen(gets(s))>0)
{
fputs(s,f1);
fputs("\n",f1);
}
fclose(f1);
printf("\nOpening a file in Reading Mode\n");
f1=fopen("[Link]","r");
while(fgets(s,79,f1)!=NULL)
printf("%s",s);
fclose(f1);
getch();
}

Output:

Opening a File in Writing Mode:


Enter the data into file (Press Ctrl+z at last)Twinkle twinkle little star
how why wonder what you are
Opening a file in Reading Mode
Twinkle twinkle little star
how why wonder what you are
TRIVENI 103

23. ENUMS
Aim: Write a Program to demonstrate the enums.

Program:

#include<stdio.h>
enum rest
{
idly=10,
dosa=15,
voda=20
};
enum rest r1, r2;
main()
{
r1=idly;
r2=dosa;
clrscr();
if(r1==r2)
printf("\nBoth are equal");
else
printf("\nBoth are not equal");
getch();
}

Output:

Both are not equal


TRIVENI 104

24. ARRAYS USING POINTERS


Aim: Program to access array elements using pointers

Program:

#include<stdio.h>
void main()
{
int a[]={10,20,30,40,50};
int i,*p;
clrscr();
p=&a[0];
printf("\nArray elements:");
for(i=0; i<5; i++)
{
printf("%d\t",*p);
p++;
}
getch();
}

Output:

Array elements: 10 20 30 40 50
TRIVENI 105

25. DYNAMIC MEMORY ALLOCATION


Aim: Demo of dynamic memory allocation.

Program:

#include<stdio.h>
void main()
{
int *p,n,i,sum=0;
clrscr();
printf("Enter [Link] Students:");
scanf("%d",&n);
p=(int *)malloc(n*sizeof (n));
printf("\nEnter marks:\n");
for(i=0;i<n;i++)
{
scanf("%d",(p+i));
sum+=*(p+i);
}
printf("\nThe No Of Students Are :%d",n);
printf("\nThe Grand Total Of All Student Marks Are:%d",sum);
getch();
}

Output:

Enter [Link] Students:5


Enter marks:
90
80
70
60
50
The No Of Students Are:5
The Grand Total Of All Student Marks Are:350
TRIVENI 106

RECORD PROGRAMS

[Link] program

1 Prime or not
2 Bubble sort
3 Multiplication of two matrices
4 Call by value & call by reference
5 Factorial of a number
6 Strings (Concatenation)
7 Structures
8 Fputs(), fgets() functions
9 Enums
10 Arrays using pointers
TRIVENI 107

Model paper1

SUBJECT-C PROGRAMMING
Max Marks: 75

Answer any FIVE of the following questions 5 X 5 = 25 M


1. Explain the advantages and disadvantages of C language?
2. Write about break, continue and goto statements in C
3. Explain different forms of If - Else statement?
4. Explain generations of programming languages.
5. Write about unions.
6. Define pointer. Explain how to define and access pointers.
7. What is storage class? Explain Storage classes.
8. Explain recursion.

Answer the following questions 5 X 10 = 50 M


[Link] is an operator? Explain types of operators in c.
(or)
Explain structure of a c program with example?

10. Write about different types of looping statements?


(or)
write a program to find given number is palindrome or not?

11. What is Function? Explain parameter passing techniques in c.


(or)
Define string. Explain character and string functions.

12. What is array? Explain types of arrays?


(or)
Write a 'C' program to find matrix multiplication?

13. Explain pointer arithmetic?


(or)
Explain array of structures using example?
TRIVENI 108

Model paper2
SUBJECT-C PROGRAMMING
Max Marks: 75

Answer any FIVE of the following questions 5 X 5 = 25 M


1. Explain the features of Clanguage?
2. What are the data types are available in C language?
3. Explain different forms of If - Else statement?
4. write a program to find given string is palindrome or not?
5. Differentiate Structure with Union?
6. What is pointer? Explain how to define a pointer with example?
7. Explain Storage classes?
8. Explain Enumerated Data type?

Answer the following questions 5 X 10 = 50 M


9. Explain history of C language?
(or)
Explain Input and output statements syntax with example?

10. Write about different types of looping statements?


(or)
Write a 'C' program to find given number is arm strong (or) not

11. What is array? Explain types of arrays?


(or)
Write a 'C' program to find matrix multiplication?

12. What is Function? Explain difference between call by value and call by
reference?
(or)
Explain String functions?

13. Explain file management in C?


(or)
Explain nested structure using example?
TRIVENI 109

April 2017
SUBJECT-C PROGRAMMING
Max Marks: 75

Answer any FIVE of the following questions 5 X 5 = 25 M


1. Explain various generations of programming languages.
[Link] the structures of c programs.
[Link] is recursion?Write a program to calculate factorial of a number using recursion.
[Link] jump statements available in c.
[Link] a program for addition of two matrices.
[Link] is a pointer? Explain passing arguments to functions using pointers.
[Link] are self referential structures.
[Link] break and continue statements.

Answer the following questions 5 X 10 = 50 M


UNIT-I
9. Explain Input and output functions of c language.
(or)
[Link] athe steps involved in algorithm development and draw a flow chart for sum and
average fo two numbers.

UNIT-II
[Link] iterative loops in c.
(or)
[Link] three categories of function prototype.

UNIT-III
13. Explain one dimensional array? Write a program to accept array of numbers and to find the
largest and smallest of the interred numbers.
(or)
[Link] string handling functions in detail.

UNIT-IV
[Link] in detail about dynamic memory management functions.
(or)
[Link] structures and union with examples.

UNIT-V
[Link] about file processing facilities available in c.
(or)
[Link] is a file? How to detect end of a file and explain the creation of temporary file.
TRIVENI 110

You might also like