0% found this document useful (0 votes)
30 views134 pages

Introduction to C Programming Concepts

The document provides an introduction to C programming, focusing on problem-solving techniques, algorithms, and flowcharts. It outlines the steps involved in problem-solving, including defining the problem, formulating a mathematical model, developing algorithms, and writing code. Additionally, it discusses the structure of algorithms, the use of pseudocode and flowcharts, and the types of programming languages, culminating in a brief history of the C programming language.

Uploaded by

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

Introduction to C Programming Concepts

The document provides an introduction to C programming, focusing on problem-solving techniques, algorithms, and flowcharts. It outlines the steps involved in problem-solving, including defining the problem, formulating a mathematical model, developing algorithms, and writing code. Additionally, it discusses the structure of algorithms, the use of pseudocode and flowcharts, and the types of programming languages, culminating in a brief history of the C programming language.

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

I SEMESTER
SUBJCET NAME : COMPUTER PROGRAMMING C
SUBJECT CODE : CS25CO1
CONCEPT : INTRODUCTION TO C

SINCET - CSE II
PROBLEM DEFINITION:
The computer is the symbol- manipulating machine that follows the set of
instructions called a program. Any computing has to be performed independently without
depending on the programming language and the computer.
PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number
of solutions.
The problem solving process starts with the problem specifications and ends with a
correct program.
The problem solving techniques involves the following steps
 Define the problem.
 Formulate the mathematical model.
 Develop an algorithm.
 Write the code for the problem.
 Test the program.
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques that helps in providing logic for
solving a problem.
Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
1. ALGORITHM

It is defined as a sequence of instructions that describe a method for solving a problem.


In other words it is a step by step procedure for solving a problem
 Should be written in simple English
 Each and every instruction should be precise and unambiguous.
 Instructions in an algorithm should not be repeated infinitely.
 Algorithm should conclude after a finite number of steps.
 Should have an end point
 Derived results should be obtained only after the algorithm terminates. 
Qualities of a good algorithm
The following are the primary factors that are often used to judge the quality of the algorithms.
Time – To execute a program, the computer system takes some amount of time.
The lesser is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given
problem, some of these may provide more accurate results than others, and
such algorithms may be suitable

SINCET - CSE II
Building Blocks of Algorithm
As algorithm is a part of the blue-print or plan for the computer program. An algorithm
is constructed using following blocks.
 Statements
 States
 Control flow
 Function
Statements
Statements are simple sentences written in algorithm for specific purpose. Statements may
consists of assignment statements, input/output statements, comment statements

Example:
 Read the value of ‘a’ //This is input statement
 Calculate c=a+b //This is assignment statement
 Print the value of c // This is output statement

Comment statements are given after // symbol, which is used to tell the purpose of the line.

States
An algorithm is deterministic automation for accomplishing a goal which, given an initial state,
will terminate in a defined end-state.
An algorithm will definitely have start state and end state.
Control Flow
Control flow which is also stated as flow of control, determines what section of code is to run in
program at a given time. There are three types of flows, they are
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow
Sequential control flow:
The name suggests the sequential control structure is used to perform the action one
after another. Only one step is executed once. The logic is top to bottom approach.
Example
Description: To find the sum of two numbers.
1. Start
2. Read the value of ‘a’
3. Read the value of ‘b’
4. Calculate sum=a+b
5. Print the sum of two number
6. Stop

SINCET - CSE II
Selection or Conditional control flow
Selection flow allows the program to make choice between two alternate paths based on
condition. It is also called as decision structure

Basic structure:
IFCONDITION is TRUE then
perform some action
ELSE IF CONDITION is FALSE then
perform some action
The conditional control flow is explained with the example of finding greatest of two
numbers.
Example
Description: finding the greater number
1. Start
2. Read a
3. Read b
4. If a>b then
4.1. Print a is
greater else
4.2. Print b is greater
5. Stop

Repetition control flow


Repetition control flow means that one or more steps are performed repeatedly until some
condition is reached. This logic is used for producing loops in program logic when one one more
instructions may need to be executed several times or depending on condition.

Basic Structure:
Repeat until CONDITION is
true Statements

Example
Description: to print the values from 1 to n
1. Start
2. Read the value of ‘n’
3. Initialize i as 1
4. Repeat step 4.1 until i< n
4.1. Print i
5. Stop

SINCET - CSE II
Function
A function is a block of code that performs a specific task. Function is also named as
methods, sub-routines.
Elements of functions:
1. Function Declaration
2. Body of the function (local declaration and statements)
3. Formal parameter
4. Return type
Syntax:
Data_types function_name(parameters) Ex:
{ int add(int a,int b)
local declaration; {
Executable €statements c=a+b;
return( ) return(c ):
} }
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2:Call the function add()
Step 3: Stop
Sub function add()
Step1:Functionstart
Step2:Geta,bValue
s Step 3: add c=a+b
Step 4: Printc
Step 5: Return

2. NOTATIONS OF AN ALGORITHM

Algorithm can be expressed in many different notations, including Natural Language,


Pseudo code, flowcharts and programming languages. Natural language tends to be verbose
and ambiguous. Pseudocode and flowcharts are represented through structured human
language.A notation is a system of characters, expressions, graphics or symbols designs used
among each others in problem solving to represent technical facts, created to facilitate the best
result for a program

Pseudocode

Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use any
programming language in its representation instead it uses the simple English language text as it is
intended for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation(code) in a high-
level language.
5

SINCET - CSE II
Example:
Pseudocode: To find sum of two numbers
READ num1,num2
sum=num1+num2
PRINT sum
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to
read the input, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF,
ELSE, ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
RAED name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Pseudocode:
Find greatest of two numbers READ a, b
IF a>b then
PRINT a is greater
ELSE
PRINT b is greate
ENDIF
5. Keep statements language independent.
Pesudocode must never written or use any syntax of any programming language.
Advantages of Pseudocode
 Can be done easily on a word processor
 Easily modified
 Implements structured concepts well
 It can be read and understood easily
 Converting pseudocode to programming language is easy as compared
with flowchart
Disadvantages of Pseudocode
 It is not visual
 There is no standardized style or format

SINCET - CSE II
COMPUTER PROGRAMMING UNIT I SINCET

Flowchart
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes,
diamonds, and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Flowchart Symbols

Symbol Purpose Description


Used to indicate the flow of logic by
Flow line connecting symbols
Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Used for airthmetic operations and data-


Processing manipulations.
Used to represent the operation in which
Desicion there are two alternatives, true and false.

On-page Connector Used to join different flowline

Off-page Connector Used to connect flowchart portion on


different page.

Predefined Used to represent a group of statements


Process/Function performing one processing task.

Control Structures using flowcharts and Pseudocode Sequence Structure

 Read a,b Start


values
 Calculate a=10,b=20
c-a+b
 Display c
value
 stop

SINCET - CSE II
Rules for drawing flowchart
1. In drawing a proper flowchart, all necessary requirements
should be listed out in logical order.
2. The flow chart should be clear, neat and easy to follow. There
should not be any room for ambiguity in understanding the
flowchart.
3. The usual directions of the flow of a procedure or system is
from left to right or top to bottom.
Only one flow line should come out from a process symbol.

4. Only one flow line should enter a decision symbol, but two or
three flow lines, one for each possible answer, cap leave the
decision symbol.

5. Only one flow line is used in conjunction with terminal symbol.

6. If flowchart becomes complex, it is better to use connector


symbols to reduce the number of flow lines.
7. Ensure that flowchart has logical start and stop.

Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more
effective way.
Proper Documentation
Flowcharts are used for good program documentation,
which is needed for various purposes.
Efficient Coding
Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite
complicated. In that case flowchart becomes complex and difficult
to use.
Alteration and Modification: If alterations are required the
flowchart may require re- drawing completely.

Reproduction: As the flowchart symbols cannot be typed, reproduction


becomes problematic.

7
SINCET - CSE II
Problem Analysis Chart (PAC)
Problem Analysis Chart (PAC) in C (or any programming language) is often used
in program design before coding. It helps break down a problem into smaller parts, so
you can design the input, process, and output clearly.
Structure of a Problem Analysis Chart
Problem : The problem statement or task to solve

Input : Data given to the program (variables, constants, files, etc.)


Process : Steps or logic applied to transform input into output
Output : Final result(s) produced by the program
Example Problem
Write a C program to calculate the sum and average of three numbers.

Problem Analysis Chart

 ProblemCalculate sum and average of three numbers


 Input Three integers (a, b, c)
 Process sum = a + b + c<br>avg = sum / 3.0
 Output Sum and average of the three numbers
Corresponding C Program
#include <stdio.h>
int main()
{
int a, b, c, sum;
float avg;
// Input
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
// Process
sum = a + b + c;
avg = sum / 3.0;
// Output
printf("Sum = %d\n", sum);
printf("Average = %.2f\n", avg);
return 0;
}

8
SINCET - CSE II
Programming Language
Programming Language is a formal language with set of instruction, to the
computer to solve a problem. The program will accept the data to perform computation.
Types of Programming Language
In general Programming languages are classified into three types. They are
 Low – level or Machine Language
 Intermediate or Assembly Language
 High – level Programming language
Low – level or Machine Language:
Machine language is the lowest-level programming language (except for
computers that utilize programmable microcode). Machine languages are the only
languages understood by computers. It is also called as low level language.
Example code:100110011 111001100
Assembly Language:
An assembly language contains the same instructions as a machine language,
but the instructions and variables have names instead of being just numbers. An
assembler language consists of mnemonics, mnemonics that corresponds unique
machine instruction.
Example code: start
add x, y
sub x,y
High – level Language:
A high-level language (HLL) is a programming language such as C, FORTRAN, or
Pascal that enables a programmer to write programs that are more or less independent
of a particular type of computer. Such languages are considered high- level because they
are closer to human languages and further from machine languages. Ultimately, programs
written in a high-level language must be translated into machine language by a compiler or
interpreter.
Example code: print(“Hello World!”)
High level programming languages are further divided as mentioned below.
Interpreted vs. Compiled Programming Language
Interpreted Programming Language Compile Programming Language
Translates one statement at a time Scans entire program and translates it
as whole into machine code
It takes less amount of time to analyze It takes large amount of time to
the analyze the
source code but the overall execution source code but the overall execution
time is slower time is comparatively faster
No intermediate object code is Generates intermediate object code
generated, hence are memory efficient which
further requires linking, hence requires
more memory
Continues translating the program until It generates the error message only
first error is met, in which case it stops. after scanning the whole program.
Hence debugging is easy. Eg: Python, Ruby Hence debugging
is comparatively hard. Eg: C,C++,Java

9
SINCET - CSE II
HISTORY OF C PROGRAMMING

C is a general-purpose, procedural programming language developed in the early


1970s by Dennis Ritchie at Bell Labs. It was initially designed for developing the UNIX
operating system and is often referred to as a "middle-level" language because it combines
elements of both high-level and low-level languages.

Structure of the C Program:


The basic structure of a C program is divided into 6 parts which makes it easy to
read, modify, document, and understand in a particular format. C program must follow
the below-mentioned outline in order to successfully compile and execute.
Debugging is easier in a well-structured C program.

Sections of the C Program


There are 6 basic sections responsible for the proper execution of a program.
Sections are mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

1. Documentation(Non Executable line)


This section consists of the description of the program, the name of the program,
and the creation date and time of the program. It is specified at the start of the program
in the form of comments. Documentation can be represented as:
// - single line comment
/* */ - Multiline comments

10
SINCET - CSE II
Example

// Documentation
/*
File: sum.c
Author: Ramesh babu
Description: program to find sum.
*/

2. Preprocessor Section or linking Section


All the header files of the program will be declared in the preprocessor section
of the program. Header files help us to access other's improved code into our code. A
copy of these multiple files is inserted into our program before the process of
compilation.
Syntax: #include< Header file name>
Example:
// Link
#include <stdio.h>
#include<math.h>
3. Definition
The #define preprocessor is used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the actual piece
of defined code.
Example:
// Definition
#define X 20
4. Global Declaration
The global declaration section contains global variables, function declaration,
and static variables. Variables and functions which are declared in this scope can be
used anywhere in the program.
Example:
// Global Declaration
int sum(int, int);
int p=120;
5. Main() Function
The main function is the entry point of a C program. It is a user-defined function
where the execution of a program starts. This section contains two parts; declaration
part and executable part
Declaration part:
The declaration part declares all the variables used in the executable part.
Executable part:
There is at least one statement in the executable part, these two
parts must appear between the opening and closing braces.
The program execution begins at the opening brace and ends at the
closing brace. The closing brace of the main function is the logical end of the
[Link] statements in the declaration and executable part end with a
semicolon.

 The return type of the main() function can be int as well as void too. void()
main tells the compiler that the program will not return any value.
 The int main() tells the compiler that the program will return an integer value.

11
SINCET - CSE II
Syntax:
Void main()
{
Declaration Part:
Execution part;
}

Example:
// Main() Function
int main()
{
int y = 55;
printf("Sum: %d",
sum(y));
return 0;
}
6. Sub Programs
User-defined functions are called in this section of the program. The control of the
program is shifted to the called function whenever they are called from the main or
outside the main() function. These are specified as per the requirements of the
programmer.
Example:
int sum(int x, int y)
{
int x=10; //local variable Declaration
int y=20:
return x+y;
}
Example: Below C program to find the sum of 2
numbers:
// Name of the program
#include <stdio.h> // Link
#define PI 3.14 // Definition
int sum(int ,int); // Global Declaration
int p=120;
int main(void) // Main() Function
{
int y = 55; // Local variable deeclaration
printf("Sum: %d", sum(y));
return 0}
int sum(int x, int y) //FunctionDeclaration
{
int x=10; //local variable Declaration
int y=20:
return x+y; //return statements
}

12
SINCET - CSE II
COMPILATION & EXECUTION PROCESS
The compilation is the process of converting the source code of the C language
into machine code. As C is a mid-level language, it needs a compiler to convert it into an
executable code so that the program can be run on our machine.
The C program goes through the following phases during compilation:

Source Code (.c)

Preprocessor --> Expanded Source

Compiler
--> Assembly Code(.s)

Assembler
--> Object Code (.o / .obj)

Linker
--> Executable (.exe / [Link])

Loader

-> Program in Memory --> Execution


Step 1: Creating a C Source File
We first create a C program using an editor and save the file as filename.
Step 2: Compiling using C compiler
Step 3: Executing the program
A compiler converts a C program into an executable. There are four phases for a C
program to become an executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
5. Execution
Pre-processing:
The preprocessor handles all lines starting with # (like #include, #define).It
replaces macros, includes header files, and removes comments. The pre-processed
output is stored in the filename.i.
Example:
#include <stdio.h>
#define PI 3.14

int main() {
printf("%f", PI);
}
After preprocessing, PI is replaced with 3.14 and the contents of stdio.h are included.
13
SINCET - CSE II
Compilation
The compiler translates the preprocessed C code into assembly [Link] Checks
for syntax errors and optimizes code Output: an assembly file (.s file, depending on
compiler).

Assembly:
The assembler converts assembly code into machine code (object code).
Output: an object file (.o or .obj).
Linking
The linker combine the object file with required library files (like printf from stdio.h).If
some functions are declared but not defined in the code, the linker resolves them from
[Link]: an executable file (.exe on Windows, [Link] or custom name on Linux).
Linking can be of two types:
 Static Linking: All the code is copied to the single file and then executable file is
created.
 Dynamic Linking: Only the names of the shared libraries is added to the code
and then it is referred during the execution.
Execution
 The executable code is loaded into memory by the [Link] starts executing
from the main() function.

INTERACTIVE AND SCRIPT MODE


In the context of C programming, the terms "interactive mode" and "script
mode" are not typically used in the same way they are for interpreted languages like
Python. C is a compiled language, meaning source code must be translated into an
executable program before it can be run.
Script Mode (Standard C Programming):

 This is the primary and most common way to work with C.


 You write your C code in a text file, usually with a .c extension
(e.g., myprogram.c).
 This file is then compiled by a C compiler (like GCC) into an executable file.
 The executable file is then run from the command line, executing all the
instructions within the program.
 This mode is suitable for developing complete applications, as it allows for
structured code, error checking during compilation, and easy distribution of the
compiled executable.
Example (Script Mode):
//myprogram.c
#include<stdio.h>
int main()
{
printf("Hello \n");
return 0;
}
To compile and run:
Code
gcc myprogram.c -o myprogram
./myprogram

14
SINCET - CSE II
Interactive Mode (Limited C Environments/REPLs):

 While C itself doesn't have a built-in interactive shell like Python, some specialized
tools or environments offer a limited form of interactivity for C.
 C Interpreters: Tools like CINT or Cling (part of ROOT) provide a Read-Eval-Print
Loop (REPL) for C/C++. This allows you to type C code snippets directly and see
immediate results, which is useful for quick testing or learning.
 Debuggers: Debuggers like GDB allow you to interact with a running C program,
inspect variables, execute code line by line, and even change variable values during
execution. This provides a powerful interactive environment for debugging.
Example (Interactive with CINT/Cling - conceptual):
Code
cint> int x = 10;
cint> printf("Value of x: %d\n", x)
Value of x
COMMENTS
The comments in C are human-readable notes in the source code of a C program
used to make the program easier to read and understand. The C compiler ignores
comments during compilation, so they do not affect the program's execution.
//- single line comment
/* */ - Multiline comments
Example:
// Addition fi two program
/*
File: sum.c
Author: you
Description: program to find sum.
*/
INDENTATION:
Indentation improves the readability of the code. It is mainly used for code
inside looping statements, control structures, functions etc. as good intended code is
easy to maintain and is good looking. It makes the code more readable and easy to
understand. Some programming languages like Python made indentation mandatory
instead of using brackets, It makes code easy to read and understand.
Some Rules for indentation are:
 Each nested block should be properly indented and spaced with a tab space.
 All braces should start from a new line then the code comes following the end
braces from a new line.
Example:
int main()
{
int a = 10, b = 20;
if (a > b) {
printf( "a is greater than b");}
else
{
printf("b is greater than a");
}
return 0;}
15
SINCET - CSE II
TYPES OF ERRORS

There are different types of errors using a C program. In any programming


language errors are common. If we miss any syntax like parenthesis or semicolon
then we get syntax errors. Apart from this we also get run time errors during the
execution of code.
There are 5 types of error in C:
 Syntax Errors
 Runtime Errors
 Logical Errors
 Linked Errors
 Semantic Errors

Syntax Errors
These are also referred to as compile-time errors. These errors have occurred
when the rule of C writing techniques or syntaxes has been broken. These types of
errors are typically flagged by the compiler prior to compilation.
Example :
In the below program we are getting an error because of a missing semicolon at
the end of the output statement (printf()) called syntax error.
int main()
{
// missing semicolon
printf("Programming in C")
return 0;
}
2. Runtime Errors
This type of error occurs while the program is running. Because this is not a
compilation error, the compilation will be completed successfully. These errors occur
due to segmentation fault when a number is divided by division operator or modulo
division operator.
Example:Let us consider an array of length 5 i.e. array[5], but during runtime, if
we try to access 10 elements i.e array[10] then we get segmentation fault errors
called runtime errors.
Giving only an array length of 5
// a runtime error
#include <stdio.h>
int main()
{
int array[5];
printf("%d", array[10]);
return 0;
}
3. Logical Errors
Even if the syntax and other factors are correct, we may not get the desired
results due to logical issues. These are referred to as logical errors. We sometimes put
a semicolon after a loop, which is syntactically correct but results in one blank loop. In
that case, it will display the desired output.

16
SINCET - CSE II
Example:
In the below example, the for loop iterates 5 times but the output will be
displayed only one time due to the semicolon at the end of for loop. This kind of error
is called a logical error.
// a logical error
#include <stdio.h>
int main()
{
int i;
for(i = 0; i <= 5; i++);
{
printf("Programming in C ");
}
return 0;
}
Linker Errors
When the program is successfully compiled and attempting to link the different
object files with the main object file, errors will occur. When this error occurs, the
executable is not generated. This could be due to incorrect function prototyping, an
incorrect header file, or other factors. If main() is written as Main(), a linked error will
be generated.
Example:
Below is the C program to show the linker error.

// a linker error
#include <stdio.h>
int Main()
{
printf("C programming ");
return 0; }

5. Semantic Errors
When a sentence is syntactically correct but has no meaning, semantic errors
occur. This is similar to grammatical errors. If an expression is entered on the left side
of the assignment operator, a semantic error may occur.
Example:
Below is the C program to show semantic error.

// a semantic error
#include <stdio.h>
int main()
{
int x = 10;
b = 20, c;
x + y = c;
printf("%d", c);
return 0;
}

17
SINCET - CSE II
LANGUAGE TRANSLATORS
These are the programs which are used for converting the programs in one language
into machine language instructions, so that they can be executed by the computer.
 Compiler: It is a program which is used to convert the high level language
programs into machine language
 Assembler: It is a program which is used to convert the assembly level language
programs into machine language
 Interpreter: It is a program, it takes one statement of a high level language
program, translates it into machine language instruction and then immediately
executes the resulting machine language instruction and so on.

Comparison between a Compiler and Interpreter


COMPILER INTERPRETER
A Compiler is used to compile an entire An interpreter is used to translate each
program and an executable line of the program code immediately as
program is generated through the it is entered
object program
The executable program is stored in a disk The executable program is generated in
for future use or to run it in another RAM
computer and the interpreter is required for each
run of the program
The compiled programs run faster The Interpreted programs run slower
Most of the Languages use compiler A very few languages use interpreters.

C CHARACTER SET
A character set defines the valid characters that can be used in a sourse program
or interpreted when a program is running
Letters
Uppercase letter - A to Z
Lowercase letter - a to z
Digits
All decimal digits 0 to 9
Special characters
, Comma ~ Tilde + Plus
. Period @ At the rate - Minus
; Semicolon # Number sign > Greater than
: Colon $ Dollar Sign < Less than
? Question Mark % Percent Sign [ Left bracket
' Single Quote ^ Caret ] Right bracket
" Double Quote & Ampersand { Left brace
! Exclamation * Asterisk } Right brace
| Pipe ( Left parenthesis / Forward slash
_ Underscore ) Right parenthesis \ Backward slash

18
SINCET - CSE II
White Space Characters

 Blank space character


 Horizontal tab space character
 Vertical tab
 New line character
 Carriage return
 Form feed character

C TOKENS
The smallest individual units of a C program are known as tokens. Programs can
be written using the tokens and its syntax rules.

 C Tokens
 Keyword
 Identifier
 Constants
 String
 Special symbols
 Operators

IDENTIFIERS:
Identifiers refer to the names of variables, constants, functions and arrays.
These are user-defined names is called Identifiers. These identifier are defined
against a set of rules.
Rules for an Identifier
 An Identifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and
underscore( _).
 The first character of an identifier can only contain alphabet( a-z , A-Z ) or
underscore ( _).
 Identifiers are also case sensitive in C. For example name and Name are
two different identifier in C.
 Keywords are not allowed to be used as Identifiers.
 No special characters, such as semicolon, period, whitespaces, slash or
comma are permitted to be used in or as Identifier.
 C‟ compiler recognizes only the first 31 characters of an identifiers.

Ex : Valid Invalid
STDNAME Return
SUB1 $stay
TOT_MARKS 1RECORD
_TEMP 11NAME.
Y2K

19
SINCET - CSE II
C KEYWORDS

Keywords are reserved words whose meaning has already been explained to the compiler.
The keywords are also called reserved words. They must be written in lower case.

The list of C keywords is given below

auto break case char


const continue default do
double enum else extern
float for goto if
int long return register
signed short static sizeof
struct switch typedef union
unsigned void volatile while

DATA TYPES IN C

Each variable in C has an associated data type. It specifies the type of data that
the variable can store like integer, character, floating, double, etc
The variable's type must be specified at the declaration and once specified, it
cannot be changed.

20
SINCET - CSE II
Format
Size
Range Specifier
Data Type (bytes)
short int 2 -32,768 to 32,767 %hd
unsigned
2 0 to 65,535 %hu
short int
unsigned int 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to 2,147,483,647 %d
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long
4 0 to 4,294,967,295 %lu
int
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long
8 0 to 18,446,744,073,709,551,615 %llu
long int
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 1.2E-38 to 3.4E+38 %f
double 8 1.7E-308 to 1.7E+308 %lf
long double 16 3.4E-4932 to 1.1E+4932 %Lf

Note: The long, short, signed and unsigned are datatype modifier that can be used
with some primitive data types to change the size or length of the datatype.
FORMAT SPECIFIERS
To print values of different data types using the printf() statement and while
taking input using the scanf() function, it is mandatory to use format specifiers.
 It is a way to tell the compiler what type of data is in a variable.
 Some examples are %c, %d, %f, etc.

List of all the format specifies.

Specifier Data Type Example Input

%d int (decimal) 123

%i int (decimal, hex, octal) 0x1A (hex), 075 (octal)

%f float 3.14

%lf double 3.14159

%c char (single char) A

%s string (no spaces) Hello

%u unsigned int 400

%x hexadecimal unsigned int 1A

%o octal unsigned int 075

21
SINCET - CSE II
ESCAPE SEQUENCES:
Escape sequences consist of two or more characters, the first of which is the backslash
\ (called the "Escape character"); the remaining characters have an interpretation of the escape
sequence as per the following table

Escape sequence Meaning


\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh . . . Hexadecimal number of one or more digits

Constants
Constants refer to fixed values that do not change during the execution of a
program.
Note: constants are also called literals.
C supports several kinds of constants.

CONSTANTS

Numeric Character

Integer Real Single Character String

TYPES OF C CONSTANT:
1. Integer constants
2. Real or Floating point constants
3. Character constants
4. String constants
5. Backslash character constants
Integer constants:
An integer constant is a numeric constant (associated with
number) without any fractional or exponential part. There are three types
of integer constants in C programming:
 decimal constant(base 10)
 octal constant(base 8)
 hexadecimal constant(base 16)
22
SINCET - CSE II
Ex:

 Decimal constants: 0, -9, 22 etc


 Octal constants: 021, 077, 033 etc
 Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
Decimal Integer : the rules for represent decimal integer.
 Decimal Integer value which consist of digits from 0-9.
 Decimal Integer value with base 10.
 Decimal Integer should not prefix with 0.
 It allows only sign (+,-).
 No special character allowed in this integer.

Ex : valid invalid
7 $77

Octal : An integer constants with base 8 is called octal. These rules are :
 it consist of digits from 0 to 7.
 It should prefix with 0.
 It allows sign (+,-).
 No special character is allowed.

EX : VALID INVALID
0123 123 -> it because no prefix with 0
+0123 0128 -> because digits from 0 to 7.
Hexadecimal : An integer constant with base value 16 is called Hexadecimal.
 It consist of digits from 0-9,a-f(capital letters & small leters.
Ex : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
 it should prefix with 0X or 0x.
 it allows sign (+,-).
 No special character is allowed.

EX : OX1a, ox2f

Floating point/Real constants:


A floating point constant is a numeric constant that has either a
fractional form or an exponent form.
For example:
-2.0
0.0000234
-0.22E-5
Note: E-5 = 10-5

Real Constants : Real constant is base 10 number, which is


represented in decimal 0r scientific/exponential notation.

Real Notation : The real notation is represented by an integer


followed by a decimal point and the fractional(decimal) part. It is
possible to omit digits before or after the decimal point.
23
SINCET - CSE II
Character Constant:
Single Character Constant : A character constant is either a single alphabet, a single
digit, a single special symbol enclosed within single inverted commas.
a) it is value represent in ‘ ‘ (single quote).
b) The maximam length of a character constant can be 1 character.
EX : VALID INVALID
‘a’ “12”
‘b’ „ab‟
String constant : A string constant is a sequence of characters enclosed in double
quote, the characters may be letters, numbers, special characters and blank space etc

EX : “rama” , “a” , “+123” , “1-/a”


"good" //string constant
"" //null string constant
" " //string constant of six white space
Two ways to define constant in C
There are two ways to define constant in C programming.
1. const keyword
2. #define preprocessor
3.
Ex:const float PI=3.14;
#define PI 3.14
VARIABLES
Variable is a name of memory location. It is used to store data. Variables are
changeable, we can change value of a variable during execution of a program. . It can be
reused many times.
Rules to write variable names:
 A variable name contains maximum of 30 characters/ Variable
name must be upto 8 characters.
 A variable name includes alphabets and numbers, but it must start
with an alphabet.
 It cannot accept any special characters, blank spaces except under
score( _ ).
 It should not be a reserved word.

Ex: a, i , studname, mark


Declaration of Variables :
variable can be used to store a value of any data type. The declaration of variables
must be done before they are used in the program. The general format for declaring a
variable.
Variables are separated by commas and declaration statement ends with a semicolon.
Syntax :
data_type variable-1,variable-2,….. , variable-

Ex : int x,y,z;
float x,y;
char name;
24
SINCET - CSE II
Assigning values to variables :
values can be assigned to variables using the assignment operator
(=). The general format statement is :
Syntax : data_type variable = constant;
Ex: int a=10;
float y=9.12
char studname=”kumar”
Types of Variables in C
There are many types of variables in c:

 local variable
 global variable
 static variable

Storage Classes in C
Storage classes in C define the scope, lifetime, visibility, and default initial value
of variables. They determine where a variable is stored, how long it retains its value, and
how it can be accessed. Here are the four main storage classes in C:
 Automatic (auto)
 External (extern)
 Static
 Register
1. Automatic (auto)
 Scope: Local to the block in which the variable is defined.
 Lifetime: Exists only during the execution of the block.
 Default Value: Garbage (uninitialized).
 Storage: Stored in the stack.
 Keyword: auto (optional, as it's the default for local variables).

Example:
void example()
{
auto int x = 10; // Same as 'int x = 10;'
printf("%d", x);
}
2. External (extern)
 Scope: Global (accessible across multiple files).
 Lifetime: Exists throughout the program's execution.
 Default Value: Zero (0).
 Storage: Stored in the global memory.
 Keyword: extern.

Example:
extern int x; // Declaration
int x = 20; // Definition
void example()
{
printf("%d", x); // Access global variable
}
25
SINCET - CSE II
3. Static
 Scope: Local to the block (for local variables) or global (for global variables).
 Lifetime: Retains its value between function calls.
 Default Value: Zero (0).
 Storage: Stored in the global memory.
 Keyword: static
Example:
void example()
{
static int count = 0; // Retains value between calls
count++;
printf("%d", count);
}

4. Register
 Scope: Local to the block in which the variable is defined.
 Lifetime: Exists only during the execution of the block.
 Default Value: Garbage (uninitialized).
 Storage: Stored in CPU registers (if available).
 Keyword: register.
 Example:

void example()

{
register int x = 5; // Suggests storing in a CPU register
printf("%d", x);
}

These storage classes help optimize memory usage and control variable behavior
effectively.

OPERATOR IN C
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. By definition, an operator performs a certain operation on operands. An
operator needs one or more operands for the operation to be performed.
On the basis of the number of operands they work on, operators can be classified
into three types :
1. Unary Operators: Operators that work on single operand.
Example: Increment( ++) , Decrement(--)
2. Binary Operators: Operators that work on two operands.
Example: Addition (+), Subtraction( -) , Multiplication (*)
3. Ternary Operators: Operators that work on three operands.
Example: Conditional Operator( ? : )

26
SINCET - CSE II
Types of Operators in C
1. Arithmetic Operators
2. Relational operators
3. Logical operators
4. Increment and Decrement Operators
5. Assignment Operators
6. Short hand Assignment Operators
7. Conditional Operators
8. Special Operators

Arithmetic Operators
The arithmetic operators are used to perform arithmetic/mathematical
operations on operands.

Symbol Operator Description Syntax


+ Plus Adds two numeric values. a+b
Subtracts right operand from left
- Minus a-b
operand.
* Multiply Multiply two numeric values. a*b
a/b
/ Divide Divide two numeric values.
20 / 3 = 6.66
Returns the remainder after diving the a%b
% Modulus
left operand with the right operand. 20 % 3 = 2
+ Unary Plus Used to specify the positive values. +a
- Unary Minus Flips the sign of the value. -a

Increment and Decrement Operators

Symbol Operator Description Syntax


++ Increment Increases the value of the operand by 1. a++
-- Decrement Decreases the value of the operand by 1. a--

Increment Operator in C

The increment operator ( ++ ) is used to increment the value of a variable in an


expression by 1.
The Increment Operator in C can be used in two ways,
 Prefix (pre-increment)
 Postfix (post-increment).
Syntax:

Pre-increment Post-Increment
Syntax:
Syntax:
Variable name++;
++ variable name;
Example:
Example:
result = var1++;
result = ++var1;
result = var;
var = var + 1;
var = var + 1;
result = var;

27
SINCET - CSE II
Decrement Operator in C
The increment operator ( ++ ) is used to Decreases the value of a variable in an
expression by 1
The Decrement in C can be used in two ways,
 Prefix (Pre-Decrement)
 Postfix (Post-Decrement).
Pre-Decrement Post-Decrement
Syntax:
Syntax:
-- variable name;
Variable name--;
Example:
Example:
result = --var1;
result = var1++;
var = var + 1;
result = var;
result = var;
var = var + 1;
Relational Operators
The relational operators in C are used for the comparison of the two operands. All
these operators are binary operators that return true or false values as the result of
comparison.
These are a total of 6 relational operators in C:

Symbol Operator Description Syntax


Returns true if the left operand is less than
< Less than a<b
the right operand. Else false
Returns true if the left operand is greater
> Greater than a>b
than the right operand. Else false
Less than or Returns true if the left operand is less than
<= a <= b
equal to or equal to the right operand. Else false
Greater than Returns true if the left operand is greater
>= a >= b
or equal to than or equal to right operand. Else false
== Equal to Returns true if both the operands are equal. a == b
Returns true if both the operands are NOT
!= Not equal to a != b
equal.

Logical Operator:
Logical Operators are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition in consideration.
The result of the operation of a logical operator is a Boolean value
either true or false.

28
SINCET - CSE II
There are 3 logical operators in C:

Symbol Operator Description Syntax


Returns true if both the operands are
&& Logical AND a && b
true.
Returns true if both or any of the
|| Logical OR a || b
operand is true.
! Logical NOT Returns true if the operand is false. !a

Assignment Operators
Assignment operators are used to assign value to a variable. The left side operand
of the assignment operator is a variable and the right side operand of the assignment
operator is a value.

Symbol Operator Description Syntax


Assign the value of the right operand
= Simple Assignment a=b
to the left operand.

Short hand Assignment Operators or Compound Operators


The assignment operators can be combined with some other operators in C to
provide multiple operations using single operator. These operators are called compound
operators.
Short hand assignment operators:
Symbol Operator Description Syntax
Plus and Add the right operand and left operand and
+= a += b
assign assign this value to the left operand.
Minus and Subtract the right operand and left operand
-= a -= b
assign and assign this value to the left operand.
Multiply and Multiply the right operand and left operand
*= a *= b
assign and assign this value to the left operand.
Divide and Divide the left operand with the right operand
/= assign and assign this value to the left operand. a /= b
Assign the remainder in the division of left
Modulus and
%= operand with the right operand to the left a %= b
assign
operand.
AND and Performs bitwise AND and assigns this value
&= a &= b
assign to the left operand.
Performs bitwise OR and assigns this value to
|= OR and assign a |= b
the left operand.
XOR and Performs bitwise XOR and assigns this value
^= a ^= b
assign to the left operand.
Rightshift and Performs bitwise Rightshift and assign this
>>= a >>= b
assign value to the left operand.
Leftshift and Performs bitwise Leftshift and assign this
<<= a <<= b
assign value to the left operand.

29
SINCET - CSE II
Bitwise Operators
The Bitwise operators are used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then the calculation is performed on the
operands.
Note: Mathematical operations such as addition, subtraction, multiplication, etc. can be
performed at the bit level for faster processing.
There are 6 bitwise operators in C:
Symbol Operator Description Syntax
Performs bit-by-bit AND operation and
& Bitwise AND returns the result. a&b
Performs bit-by-bit OR operation and
| Bitwise OR a|b
returns the result.
Performs bit-by-bit XOR operation and
^ Bitwise XOR a^b
returns the result.
Bitwise First Flips all the set and unset bits on the
~ ~a
Complement number.
Shifts bits to the left by a given number
<< Bitwise Leftshift of positions; multiplies the number by 2 a << b
for each shift.
Shifts bits to the right by a given number
Bitwise
>> of positions; divides the number by 2 for a >> b
Rightshilft
each shift.

Conditional Operator ( ? : )
The conditional operator is the only ternary operator in C. It is a conditional
operator that we can use in place of if..else statements.
Syntax:
Expression1 ? Expression2 : Expression3;
Ex: a>b?a:b;

Special Operators:
, - Comma Operator
sizeof - sizeof Operator
Example:
sizeof(expression) sizeof(int)
sizeof(type_name)
& - Address-of operator

30
SINCET - CSE II
Operator Precedence and Associativity
Concept that decides which operator will be evaluated first in the case when there
are multiple operators present in an expression to avoid ambiguity. As, it is very common
for a C expression or statement to have multiple operators and in this expression.
The below table describes the precedence order and associativity of operators in C. The
precedence of the operator decreases from top to bottom.

Precedence Operator Description Associativity

() Parentheses (function call) left-to-right


[] Brackets (array subscript) left-to-right

1 . Member selection via object name left-to-right

-> Member selection via a pointer left-to-right

a++ , a-- Postfix increment/decrement left-to-right

++a , --a Prefix increment/decrement right-to-left

+,- Unary plus/minus right-to-left

!,~ Logical negation/bitwise complement right-to-left

Cast (convert value to temporary value of


2 (type) right-to-left
type)

* Dereference right-to-left

& Address (of operand) right-to-left

Determine size in bytes on this


sizeof right-to-left
implementation

3 *,/,% Multiplication/division/modulus left-to-right

4 +,- Addition/subtraction left-to-right

5 << , >> Bitwise shift left, Bitwise shift right left-to-right

< , <= Relational less than/less than or equal to left-to-right


6 Relational greater than/greater than or
> , >= left-to-right
equal to

7 == , != Relational is equal to/is not equal to left-to-right

8 & Bitwise AND left-to-right

9 ^ Bitwise XOR left-to-right

10 | Bitwise OR left-to-right

11 && Logical AND left-to-right

31
SINCET - CSE II
12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left


= Assignment right-to-left

+= , -= Addition/subtraction assignment right-to-left

*= , /= Multiplication/division assignment right-to-left


14
%= , &= Modulus/bitwise AND assignment right-to-left

^= , |= Bitwise exclusive/inclusive OR assignment right-to-left

<<=, >>= Bitwise shift left/right assignment right-to-left

15 , expression separator left-to-right

Standard input/output Function: <stdio.h>


Reading the data from input devices and displaying the results on the screen are the
two main tasks. The input/output functions permit the transfer of information between the
computer and the standard input/output device. These functions can be accessed from
anywhere within the program. These functions are primarily defined in the standard
input/output library, <stdio.h>

Input/output functions are classified into two types:

1. Formatted functions
2. Unformatted functions

Input\Output Function

Formatted Unformatted
input/ Output Input/output
function function

Formatted Formatted Unformatted Unformatted


input function Output function Input function Output function

printf() ggetc() Putc()


scanf()
fprintf() gets() Puts()
fscanf()
ggetche() Putchar()
getchar()
getch()

32
SINCET - CSE II
Formatted Input and Output Function
Input: scanf(), fscanf()
Output: printf(),fprint()

Formatted input function:


Scanf()
Scanf function used to get/read the Formatted input from the keyboard.
Syntax:

scanf(“Control String”,&var1,&var2,….&var

Here
Control String or formatted String - %d, %f, %c, %s, %lf
Var – variable name
Ex: scanf(“%d%f”,&a,&b);
fscanf()

fscanf() function used to get/read the Formatted input from a file.

syntax:
fscanf(FILE *fptr,“Control String”,&var1,&var2,….&var n);

Here, *fptr -- File pointer


Control String or formatted String -- %d, %f, %c, %s, %lf
Var --variable name
Ex: fscanf(f1,“%d%f”,&a,&b);

Formatted output function:


printf()
printf() function is used to display the output on the screen.
Syntax:
printf(“Control String”,var1,var2,….var
Here,
Control String or formatted String - %d, %f, %c, %s, %lf
Var – variable name

Ex: printf(“Add=%d”,c);
fprintf()
fprintf() function is used to writes a formatted data in to a file.
syntax:

fprintf(FILE *fptr,“Control String”,var1,var2,….var n);

Here, *fptr -- File pointer


Control String or formatted String -- %d, %f, %c, %s, %lf
Var --variable name
Ex: fprintf(f1,“Add=%d”,c);

33
SINCET - CSE II
UNFORMATTED CHARACTER ORIENTED I/O FUNCTIONS

The simplest of all input/output operations are reading a character from the
standard input unit (usually the keyboard) and writing it to the standard output unit
(usually the screen).
Unformatted Input and Output Function
Input: getc(), getch(), getchar(), gets(), getche()
Output: putc() putch(), putchar(), puts()

Unformatted input Function:


getchar()
getchar() function is used to reading a single character from the keyboard.
syntax:

variable name=getchar();

Ex: char s1;


s1=getchar();
gets()
gets function is used to read a string from the keyboard
syntax:

gets(variable name);
Ex: char s1[20];
gets(s1);
getc()
getc() is used to read a single character from the given stream.
Syntax:
getc (fptr);
fptr -- File pointer
Ex: getc(fp);
Unformatted Output Function:
putchar()
putchar() is used to display a single character on the screen.
Syntax:
putchar(variablename)

Ex: char s1;


putchar(s1);
puts()
puts() is used to display a string inputted by gets() function.
putchar(variablename)
Syntax:

Ex: char s1[20];


gets(s1);
puts(“ name is”);
puts(s1);
34
SINCET - CSE II
BUILT IN FUNCTIONS:
 A function is a named block of code that performs a specific task
 A function is a set of statements enclosed within curly brackets ({}) that take
inputs, do the computation, and provide the resultant output. You can call a
function multiple times, thereby allowing reusability and modularity in C
programming. A Function can also referred as a method or a sub-routine or a
procedure, etc..
Types of function:

 User-Defined Functions
 Library Functions or Built in functions
User-Defined Functions:
The user defined functions are defined by the user at the time of writing a
program. The user can understand the internal working of the function and can change
or modify them.
Library Functions or Built in functions
The standard library functions are built-in functions in C [Link]
functions are defined in header files.

Some of the common built-in functions in C include:

 Input/Output Functions: stdio.h


 Mathematical Functions: math.h
 String Functions: string.h
 Character oriented function:ctype.h
 Console input/Output function: conio.h
 Graphical oriented function :graphics.h

String Handling Function: <string.h> -unitII


strlen() Syn : int strlen(string1); Ex:strlen(“Hsip”);
strupr() Syn: char strupr( string1); Ex:strupr(“hsip”);
strlwr() Syn: char strlwr(string1); Ex: strlwr(“HSIP”);
strrev() Syn: char strrev(string1); Ex: strrev(“Hsip”);

strcat() Syn: char strcat(string1,string2); Ex:strcat(s1,s2);

strcpy() Syn: char strcpy(string1,string2); Ex:strcpy(s1,s2);


strcom() Syn: char strcom(string1,string2); Ex: strcom(s1,s2);
string1=string2 o/p= 0,string1>string2 o/p= 1,string1<string2 o/p= -1

35
SINCET - CSE II
Mathematical Function: <math.h>
sin() Syn: double sin(double r); Ex: sin(34.99);
cos() Syn: double cos(double r); Ex: cos(34.99);
tan() Syn: double tan(double r); Ex: tan(34.99);
floor() Syn: double floor(double r); Ex: floor(34.99);
ceil() Syn: double ceil(double r); Ex: ceil(34.99);
exp() Syn: double exp(double r); Ex: exp(34.99);
fabs() Syn: double fabs(double r); Ex: fabs(34.99);
abs() Syn: int abs(int r); Ex: abs(24);
sqrt() Syn: int sqrt(int r); Ex: sqrt(25);
pow() Syn: double pow(double x, double y); Ex: pow(2,3);

Graphical Oriented Function: <graphics.h>

initgraph() Syn: void initgraph(int gdriver, int gmode, char path);


Ex:initgraph(&gdrive,&gmode,””);
closegraph() Syn: void closegraph(); Ex: closegraph();
cleradevice() Syn: cleardevice(); Ex:cleardevice();
line() Syn: void line(int x1,int y1,int x2,int y2); Ex: line(10,10,200,200);
rectangle() Syn: void rectangle(int x1,int x2,int x3,int x4);
Ex:rectangle(100,100,200,200);
circle() Syn: void circle(int x,int y,int r); Ex: circle(100,150,90);
arc() Syn: void arc(int x,int y,int sa,int ea,int r); Ex: arc(100,100,0,135,50);
ellipse() Syn: void ellipse( int x,int y,int sa,int ea,int xr,int yr);
Ex: ellipse(100,100,0,360,50,25);
setcolor() Syn: setcolor(int color); Ex: setcolor(14);
setfillstyle() Syn: setfillstyle(int pattern,int color(); Ex: setfillstyle(1,14);
setlinestyle() Syn: setlinestyle(int style,int pattern,int width); Ex: setlinestyle(0,1,1);

Console input/output Function: <conio.h>


getch() Syn: variable name=getch(); Ex: S1=getch(); or getch();
putch() Syn: putch(variable name); Ex:putch(s1);
deline() Syn: deline(); Ex: deline();
gotoxy() Syn: gotoxy(); Ex: gotoxy();
wherex() Syn: wherex(); Ex: wherex();
wherey() Syn: wherey(); Ex wherey();
clrscr() Syn:clrscr(); Ex: clrscr();

Character Oriented Function: <ctype.h>


isdigit() Syn: int isdigit(char c); Ex: isdigit(c);
isalpha() Syn: int isalpha(char c); Ex: isalpha(c);
ispunct() Syn: int ispunct(char c); Ex: ispunct(c);
isupper() Syn: int isupper(char c); Ex: isupper(c);
islower() Syn: int islower(char c); Ex: islower(c);
toupper() Syn: int toupper(char c); Ex: toupper(c);
tolower() Syn: int tolower(char c); Ex: tolower(c);

36
SINCET - CSE II
Standard input/output Function: <stdio.h>
Formatted output function:
printf() Syn: Printf(“Control String”,var1,var2,….var n);
Ex: Printf(“Add=%d”,c);
fprintf() Syn: fprintf(FILE *fptr,“Control String”,var1,var2,….var n);
Ex: fprintf(f1,“Add=%d”,c);
Formatted input function:
scanf() Syn: scanf(“Control String”,&var1,&var2,….&var n);
Ex: scanf(“%d%f”,&a,&b);
fscanf() Syn: fscanf(FILE *fptr,“Control String”,&var1,&var2,….&var n);
Ex: fscanf(f1,“%d%f”,&a,&b);
Unformatted input Function:
getchar() Syn: variable name=getchar(); Ex: s1=getchar();
gets() Syn: gets(variable name); Ex: gets(s1);
getc() Syn: getc(variable name); Ex: getc(s1);
getw() Syn: getw(variable name); Ex: getw(n)
Unformatted Output Function:
putchar() Syn: putchar(variablename); Ex: putchar(s1);
puts() Syn: puts(variable name); Ex: puts(s1);
putc() syn: putc(variable name); Ex: putc(s1)
putw() Syn: putw(variablename); Ex: putw(n);

37
SINCET - CSE II
38
SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Control Structures
Control Structures are just a way to specify flow of control in programs. Control flow
which is also stated as flow of control, determines what section of code is to run in program at a
given time. There are three types of flows, they are
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow
Sequential control flow:
The name suggests the sequential control structure is used to perform the
action one after another. Only one step is executed once. The logic is top to bottom
approach.
Example
Description: To find the sum of two numbers.
1. Start
2. Read the value of ‘a’
3. Read the value of ‘b’
4. Calculate sum=a+b
5. Print the sum of two number
6. Stop

Selection or Conditional control flow


Selection flow allows the program to make choice between two alternate paths
based on condition. It is also called as decision structure

Basic structure:
If( condition) TRUE then
{
Statement block 1;
Else
Statement block2;
}

The conditional control flow is explained with the example of finding greatest of two numbers.

pg. 2

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Repetition control flow


Repetition control flow means that one or more steps are performed repeatedly
until some condition is reached. This logic is used for producing loops in program logic
when one one more instructions may need to be executed several times or depending
on condition.

Basic Structure:
Repeat for(i = 0;I<=5;i++)
{ Statement block;
}

The classification of control statements are given below:

Control Statements

Conditional Unconditional

- goto
Selection (or)Decision making Iteration or looping - break
- continue

-simple-if - while
-if-else - do-while
-nested if - for
-if-else-if ladder
- switch case

pg. 3

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Conditional Branching Statements


Selection Statement or Decision making Statements
In selection or conditional branching, the program control is transferred from one point to
another based on the outcome of a certain condition.

 simple-if Statement
 if-else Statement
 nested if Statement
 if-else-if ladder Statement
 switch case Statement

Simple-if Statement
This is the simplest form of decision control statement. In this form, a set of statements are
executed only if the condition given with if evaluates to true.
Its general syntax and flow chart is as under:-

if(condition)
{

Statements ;
}

Example:
/* program to check whether the given number is negative*/
#include<stdio.h>
#include<conio.h>
void main()
{

int num; clrscr();


printf(“enter the number”);
scanf(“%d”,&num); if(num<0)
{
printf(“the entered number is negative”);
}
getch();
}}

pg. 4

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

if- else statement:-

This is a bi-directional control statement. This statement is used to test a condition and
take one of the two possible actions. If the condition evaluates to true then one statement (or
block of statements) is executed otherwise other statement (or block of statements) is executed.
The general form and flow chart of if-else statement is as under:-

if(condition)
{

block of statements;
}
else
{

block of statements;
}

Example:

/*Program to find the biggest of two


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

int
num1,num2 ;
clrscr();
printf(“enter the two numbers”);
scanf(“%d
%d”,&num1,&num2);
if(num1>num2)
{
printf(“the number %d is big”,num1);
}
else
{
printf(“the number %d is big”,num2);
}
getch();

pg. 5

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Nested if-else

If we have if-else statement within either the body of an if statement or the body of else
Statement or in the body of both if and else, then this is known as nesting of if else statement.

The general form of nested if-else statement is as follows:-


if (condition1)
{
if (condition2)
{
Statements block 1;
}
else
{
Statements block 2;
}

}
else {
Statements block 3;
}

pg. 6

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Example:
/*program to find the largest of three numbers*/
#include<stdio.h>
#include<conio.h>
main()
{
int a, b,c;
printf(“enter the three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if (a >= b)
{
if (a >= c)
printf("%d is the largest number.", a);
else
printf("%d is the largest number.", c);
}
else
{
if (b >= c)
printf("%d is the largest number.", b);
else
printf("%d is the largest number.", c);
}}

Else if ladder

This is a type of nesting in which there is an if-else statement in every else part except the last
else part. This type of nesting is called else if ladder.
The general syntax and flow chart of else if ladder is as follows:-

If(condition1)
{
Statement block 1;
}
else if(condition2)
{
Statement Block 2;
}
else if(condition3)
{
Statement block 3;
}

Else
{
default statement;
}

pg. 7

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Example:
A program to illustrate the else if ladder:-
/*program to find the grade of the student*/
#include<stdio.h>
#include<conio.h>
void main()
{

int marks;
printf(“enter the percentage of the student”);
scanf(“%d”,&marks);
if(marks>=80)
printf(“your grade is a”);
else if(marks>=70)
printf(“your grade is b”);
else if(marks>=60)
printf(“your grade is c”);
else if(marks>=50)
printf(“your grade is d”);
else
printf(“Fail”);

getch();
}

pg. 8

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Switch case statement

 Switch case statements are a substitute for long if statements and has more flexibility and a
clearer format than else-if ladder.
 This statement is used to select one out of the several numbers of alternatives present in a block.
 This selection statement successively tests the value of an expression against a list of integer
or character constants. When a match is found, the statements associated with that constant
are executed.
The general syntax of switch case statement is as follows:-
switch(expression)

{
case value1: statement1;
break;
case value 2: statement2;
break;
case value 3: statement3;
break;
………………………
………………………
case value N: statement N;
break;
default: default statement;
}

pg. 9

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Example:

/*program to print day of the week*/


#include<stdio.h>
#include<conio.h>
void main()
{
int day; clrscr();
printf(“enter the day number from 1 to7”);
scanf(“%d”,&day);
switch(day)
{
case 1: printf(“monday”);
break;
case 2: printf(“tuesday”);
break;
case 3: printf(“wednesday”);
break;
case
4:printf(“thursday”);
break;
case 5:printf(“friday”);
break;
case 6:printf(“saturday”);
break;
case 7:
printf(“sunday”);
break;
default:printf(“wrong input”);

}
getch();

pg. 10

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Looping or Iterative statements:


Looping means that one or more steps are performed repeatedly until some condition is
reached. This logic is used for producing loops in program logic when one or more instructions
may need to be executed several times or depending on condition.

There are three types of loops in C language:-

1. while loop
2. do while loop
3. for loop
while loop (or) Entry Control loop
The simplest of the looping structure in C is the while statement. The while loop provides a mechanism
to repeat one or more statements while a particular condition is true.
It is an entry controlled loop because the control condition is placed as the first line of the code. If the control
condition evaluates to false, then the statements enclosed in the loop are never executed.

Syntax:

while (condition)
{
Statement 1;
Statement 2;
increment/decrement;
}

Example:
#include<stdio.h>
main()
{
int i = 0;
while (i < 5)
{
printf("%d\n", i);
i++;
}
Do While loop
The do-while loop is an exit controlled loop because the test condition is evaluated at the
end of the loop. Now the test condition is evaluated at the end. This clearly means that the
body of the loop gets executed at least one time
pg. 11

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET
Syntax:-
initialization;
do

{
Body of the loop;
increment/decrement;
} while( condition );

Example:
#include<stdio.h>
main()
{
int i = 0;
do
{
printf("%d\n", i);
i++;
} while (i < 5);
}

For loop
The for loop in C is a control flow statement used for iterative execution of a block of code. It is
particularly useful when the number of iterations is known or can be determined before the loop begins.
Syntax:-

for(initialization; condition; increment/decrement/update)


{

Statement block;
}

pg. 12

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET
Example:
#include<stdio.h>
main()
{
int i;
for(i=0;i<=5;i++)
{
printf("%d\n", i);
i++;
}
}

Unconditional Statements (or) Jumping Statements:


Jump statements (or) unconditional statements are used to transfer the control from one
part of the program to another part.
Type of unconditional statements
 goto
 break
 continue

goto statement:
It is an unconditional statement and it transfers the control to the another part of the
program. The goto statement is used as under:-
Syntax:
goto label;
...................
...................
...................
Label:
Statement;
....................
....................

pg. 13

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

Example:
#include <stdio.h>
int main() {
int n = 0;
// If the number is zero, jump to
// jump_here label
if (n == 0)
goto jump_here;
// This will be skipped
printf("You entered: %d\n", n);
jump_here:
printf("Exiting the program.\n");
return 0;
}

continue statement :
The continue statement is used inside the body of the loop statement. It is used when we want
to go to the next iteration of the loop after skipping some of the statements of the loop.
The continue statement is written as under:-
Syntax: continue;
Example:
Main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 4)
{ continue; }
printf("%d\n", i);
}
break statement:
Break statement is used inside the loops or switch statement. This statement causes an
immediate exit from the loop or the switch case block in which it appears.
It can be written as
break;

Example:
/*Program to understand the use of break
statement*/
#include<stdio.h>
main()
{
int n;
for(n=1;n<=5;n++)
{
if(n==3)
{
printf(“I understand the use of
break \n”); break;
}
pg. 14

SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET

printf(“Number = %d \n”,n);
}
printf(“Out of for loop \n”);
}
Output:
Number = 1
Number = 2
I understand the use of break Out
of for loop

pg. 15

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

FUNCTIONS
A function as series of instructions or group of statements with one specific purpose.
A function is a program segment that carries out some specific, well defined task.
A function is a self contained block of code that performs a particular task.

Types of functions
C functions can be classified into two types,
1. Library functions /pre defined functions /standard functions /built in functions
2. User defined functions
3.
Library functions /pre defined functions /standard functions/Built in Functions
These functions are defined in the library of C compiler which are used frequently in the
C [Link] functions are written by designers of c compiler.
C supports many built in functions like
• Mathematical functions -(pow(), sin( ), cos(), etc…
• String manipulation functions -(strlen(), strcopy()…)
• Input and output functions -( printf(), scanf()…)

User Defined Functions


The functions written by the programmer /user to do the specific tasks are called
user defined function(UDF’s).The user can construct their own functions to perform some
specific task. This type of functions created by the user is termed as User defined
functions.
Elements of User Defined Function
The Three Elements of User Defined function structure consists of :
1. Function Definition
2. Function Declaration
3. Function call
4. Return statement
[Link] Definition:
 A program Module written to achieve a specific task is called as function definition.
 Each function definition consists of two parts:
i. Function header
ii. Function body
General syntax of function definition

Function Definition Syntax Function Definition Example

Datatype functionname(parameters or argument list) int add( int a,int b)


{ {
Declaration part; int sum;
executable part; sum=a+b;
return statement; return sum;
}
}

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

Function header
Syntax:
datatype functionname(parameters)
It consists of three parts
a) Datatype:
 The data type can be int,float,char,double,void.
 This is the data type of the value that the function is expected to return to
calling function.
b) functionname:
 The name of the function.
 It should be a valid identifier.
c) parameters
 The parameters are list of variables enclosed within parenthesis.
 The list of variables should be separated by comma.

Ex: void add( int a, int b)


 In the above example the return type of the function is void
 the name of the function is add and
 The parameters are 'a' and 'b' of type integer.
Function body
The function body consists of the set of instructions enclosed between { and } .
The function body consists of following three elements:
a) declaration part: variables used in function body.
b) executable part: set of Statements or instructions to do specific activity.
c) Return statement : It is a keyword, it is used to return control back to calling
function.
If a function is not returning value then statement is:
return;
If a function is returning value then statement is:
return value;
2. Function Declaration
 The process of declaring the function before they are used is called as function
declaration or function prototype.

Function Declaration Syntax


datatypefunctionname(type p1,type p2,………type pn);
Example
int add(int a, int b);
void add(int a, int b);
 function declaration Consists of the data type of function, name of the function and
parameter list ending with semicolon.
Note: The function declaration should end with a semicolon ;

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

[Link] Call:
 The method of calling a function to achieve a specific task is called as function call.
 A function call is defined as function name followed by semicolon.
 A function call is nothing but invoking a function at the required place in the
program to achieve a specific task.
Ex:
void main()
{
int add( ); // function call without parameter
}
Formal Parameters and Actual Parameters
Formal Parameters:
 The variables defined in the function header of function definition are called
formal parameters.
 All the variables should be separately declared and each declaration must be
separated by commas.
 The formal parameters receive the data from actual parameters.
Actual Parameters:
 The variables that are used when a function is invoked)in function call) are called
actual parameters.
 Using actual parameters, the data can be transferred from calling function. to
the called function.
 The corresponding formal parameters in the function definition receive them.
 The actual parameters and formal parameters must match in number and type of data.

Differences between Actual and Formal Parameters

Actual Parameters Formal Parameters


Actual parameters are also called as Formal parameters are also
argument list. Ex: add(m,n) called as dummy parameters.
Ex:int add(int a, int b)
The variables used in function call are called as The variables defined in function
actual parameters headerare called formal parameters
Actual parameters are used in calling function Formal parameters are used in the
when a function is called or invoked function header of a called function.
Ex: add(m,n) Example:
Here, m and n are called actual parameters int add(int a, int b)
{ ………..
}
Here, a and b are called formal parameters.

Actual parameters sends data to the formal Formal parameters receive data from the
parameters actual parameters.

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

Categories of the functions

1. Function with no parameters and no return values


2. Function with no parameters and return values.
3. Function with parameters and no return values
4. Function with parameters and return values

1. Function with no parameters and no return values

1. Function with no parameters and no return values


(or)
Function without argument and no return values
Calling function Called function or function definition
/*program to find sum of two numbers using function*/
#include<stdio.h> int add (int a,int b) // function header
int add( int x,int y); // function declaration {
void main() int sum,a,b;
{ sum=a+b;
int x,y,z return ; //no return values
printf(“enter values for x and y:”); }
scanf(“%d %d”,&x,&y);
z=add(); // without arguments
printf(“Sum of two no’s=%d”,z);
}

 In this category no data is transferred from calling function to called function, hence
called function cannot receive any values.
 In the above example,no arguments are passed to user defined function add( ).
 Hence no parameter are defined in function header.
 When the control is transferred from calling function to called function a ,and b
values are read,they are added,the result is printed on monitor.
 When return statement is executed ,control is transferred from called function/add
to calling function/main.

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

2. Function with parameters and no return values


(or)
Function with argument and no return values
Calling function Called function or function definition
/*program to find sum of two numbers using function*/ int add (int a, int b) // function header
#include<stdio.h> {
int add( int x,int y); // function declaration int sum,a,b;
void main() sum=a+b;
{ return ; //no return values
int x,y,z }
printf(“enter values for x and y:”); scanf(“%d
%d”,&x,&y);
z=add(x,y); // with arguments
printf(“Sum of two no’s=%d”,z);

 In this category, there is data transfer from the calling function to the called
function using parameters.
 But there is no data transfer from called function to the calling function.
 The values of actual parameters m and n are copied into formal parameters a and b.
 The value of a and b are added and result stored in sum is displayed on the screen in
called function itself.

3. Function with no parameters and with return values


(or)
Function without argument and return values
Calling function Called function or function definition
/*program to find sum of two numbers using function*/
#include<stdio.h> int add (int a,int b) // function header
int add( int x,int y); // function declaration {
void main() int sum,a,b;
{ printf(“enter values for a and b:”);
int x,y,z scanf(“%d %d”,&a,&b);
z=add(); // with arguments sum=a+b;
return(sum) ; //no return values
printf(“Sum of two no’s=%d”,z); }

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

 In this category there is no data transfer from the calling function to the called
function.
 But, there is data transfer from called function to the calling function.
 No arguments are passed to the function add( ). So, no parameters are defined in the
function header
 When the function returns a value, the calling function receives one value from the
called function and assigns to variable result.
 The result value is printed in calling function.

4. Function with parameters and with return values


Calling function Called function or function definition
/*program to find sum of two numbers using function*/ int add(int a, int b) /* function header */
#include<stdio.h>
int add( int x,int y); // function declaration {
void main()
{ int sum;
int x,y,z sum=a+b;
printf(“enter values for x and y:”); return sum;
scanf(“%d %d”,&x,&y); }
z=add(x,y); // with arguments
printf(“Sum of two no’s=%d”,z);

 In this category, there is data transfer between the calling function and called
function.
 When Actual parameters values are passed, the formal parameters in called
function can receive the values from the calling function.
 When the add function returns a value, the calling function receives a value from the
called function.
 The values of actual parameters m and n are copied into formal parameters a and b.
 Sum is computed and returned back to calling function which is assigned to
variable result.

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

Passing parameters to functions or Types of argument passing


The different ways of passing parameters to the function are:
 Pass by value or Call by value
 Pass by address or Call by address

[Link] by value:
 In call by value, the values of actual parameters are copied into formal parameters.
 The formal parameters contain only a copy of the actual parameters.
 So, even if the values of the formal parameters changes in the called function, the
values of the actual parameters are not changed.
 The concept of call by value can be explained by considering the following program.
Example:
#include<stdio.h>
int swap(int a,int b);
void main()
{
int m,n;
printf("enter values for a and b:");
scanf("%d %d",&m,&n);
printf("the values before swapping are m=%d n=%d \n",m,n);
swap(m,n);
printf("the values after swapping are m=%d n=%d \n",m,n);
}

int swap(int a, int b)


{
int temp;
temp=a;
a=b;
b=temp;
}

 Execution starts from function main( ) and we will read the values for variables m
and n, assume we are reading 10 and 20 respectively.
 We will print the values before swapping it will print 10 and 20.
 The function swap( ) is called with actual parameters m=10 and n=20.
 In the function header of function swap( ), the formal parameters a and b
receive the values 10 and 20.
 In the function swap( ), the values of a and b are exchanged.
 But, the values of actual parameters m and n in function main( ) have not been
exchanged.
 The change is not reflected back to calling function.

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

2. Call by Address
 In Call by Address, when a function is called, the addresses of actual
parameters are sent.
 In the called function, the formal parameters should be declared as pointers
with the same type as the actual parameters.
 The addresses of actual parameters are copied into formal parameters.
 Using these addresses the values of the actual parameters can be changed.
 This way of changing the actual parameters indirectly using the addresses of
actual parameters is known as pass by address.
Example:
#include<stdio.h>
int swap(int a,int b);
void main()
{
int m,n;
printf("enter values for a and b:");
scanf("%d %d",&m,&n);
printf("the values before swapping are m=%d n=%d \n",m,n);
swap(&m,&n);
printf("the values after swapping are m=%d n=%d \n",m,n);
}

void swap(int*a, int*b)


{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

Differences between Call by Value and Call by reference

Call by Value Call by Address

When a function is called the values of When a function is called the addresses of
variables are passed variables are passed
The type of formal parameters should The type of formal parameters should be
be same as type of actual parameters same as type of actual parameters, but they
have to be declared as pointers.
Formal parameters contains the Formal parameters contain the addresses of
values of actual parameters actual parameters.

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

Recursion
 Recursion is a method of solving the problem where the solution to a problem depends on
solutions to smaller instances of the same problem.
 Recursive function is a function that calls itself during the execution.
 Consider Example for finding factrorial of 5
Factorial(5)=n*fact(n-1)

Example 1.
/******* Factorial of a given number using Recursion ******/ #include<stdio.h>
int fact(int n);

void main( )
{
int num,result;
printf("enter number:");
scanf("%d",&num);
result=fact(num);
printf("The factorial of a number is: %d",result);
}

int fact(int n)
{
if(n==0)
return 1;
else
return (n*fact(n-1));
}
output :
enter number:5
The factorial of a number is:120
Fibonacci Sequence:
The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Page 10

SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET

Example 2.
/******* Factorial of a given number using Recursion ******/
#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}

Page 11

SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
DYNAMIC MEMORY MANAGEMENT
The process of allocating memory at run time is known as dynamic memory
allocation.

Advantages
1. It provides flexibility in adding, deleting or rearranging data items in dynamic data
structures at run time.

2. It optimizes the use of storage space by allocating additional memory space or by


releasing unwanted space at run time.
Functions
There are four library functions used for allocating and freeing memory during
program execution. They are known as memory management functions.

1. malloc()
2. calloc()
3. realloc()
4. free()
Memory Allocation Process

Conceptual view of storage of C program

Local variables
(Stack)

Free memory
(Heap)

Global variables
(permanent storage area)

C program instructions
(permanent storage area)

The local variables are stored in an area called stack. The program instructions and
global variables are stored in a region called permanent storage area. The memory space
available between these two regions is used for dynamic allocation during the program
execution. This free memory region is called heap.

The size of the heap keeps changing during program execution due to death and creation of
variables. Hence memory "overflow" occurs during dynamic allocation process. In such case,
the memory allocation functions return a NULL pointer.

Page 1|3

SINCET - CSE II
malloc( ) – Allocating a block of memory
It is used to allocate a block of memory of specified size in bytes. And returns a pointer
to the first byte of the allocated space.

Syntax:

p = (cast type *) malloc (byte size);

p : pointer of type cast type


byte size : size of the space to be allocated

Example:

P = (int *) malloc (10 * sizeof(int));

The above statement allocates “10 times size of the int” bytes of memory space for
the pointer p of type int.
Example :
p = (char*) malloc (10);

The above statement allocates 10 bytes of memory space for the pointer p of type
char.

calloc( ) – Allocating multiple blocks of memory


It is used to allocate multiple blocks of memory space in bytes at run time. And sets
all bytes to zero and returns a pointer to the first byte of the allocated space. This function is
normally used for allocating memory space for derived data types such as arrays and
structures.

Syntax:
p = (cast type*) calloc (n, byte-size);

p : pointer of type cast type


n : total number of blocks
byte-size : total number of bytes in each block

Example
struct student
{
char name[15];
int no;
float percentage;
}s, *p;
p = (s*) calloc (45, sizeof(s));
Here s is of type struct student having three members: name, no, percentage. The above
statement allocates memory space to store the details of 45 such students.
Page 2|3

SINCET - CSE II
realloc( ) – Altering the size of the block

It is used to increase or decrease the size of memory already allocated with the help
of using malloc( ) or calloc( ) function. The process of changing the size of memory is called
as reallocation of memory.

Syntax
p = realloc (old pointer, new size);

p : pointer to the first byte of the new memory block


old pointer : pointer to the first byte of the old memory block
newsize : total number of bytes of new memory space to be allocated

Example

op = (char *) malloc (10);

The above statement allocates 10 bytes of memory space.

np = (char *) realloc (op, 15);

Now the above statement increases the already allocated space to 15 bytes.

Free() releasing the used space

It is used to free (release or deallocate) the block of memory space that is unused or
already used at run time
Syntax
free(p);
P: is the pointer tothe memory block which has been already created by malloc or calloc
function
Example
P= (chart*)malloc (10);
free(p);
The second statement free the allocated memory space of 10 bytes

Page 3|3

SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET - CSE II
SINCET

Union
Union can be defined as a user-defined data type which is a collection of different variables
of different data types in the same memory location. The union can also be defined as many
members, but only one member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory
location.
Syntax
union union name
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Example

union Data
{
int i;
float f;
char str[20];
} data;

Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish
to access

#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

SINCET - CSE II
SINCET

data.i = 10;
data.f = 220.5;
strcpy( [Link], "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.f : %f\n", data.f);
printf( "[Link] : %s\n", [Link]);

return 0;
}

Output :
data.i : 10
data.f : 220.500000
[Link] : C Programming

Accessing members of union using pointers


We can access the members of the union through pointers by using the (->) arrow operator.

#include <stdio.h>
union abc
{
int a;
char b;
};
int main()
{
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}

Output : 90

SINCET - CSE II
SINCET - CSE II
FILE PROCESSING

File:
File is a collection of bytes that is stored on secondary storage devices like disk.
There are two kinds of files in a system.
They are,
1. Text files (ASCII)
2. Binary files
 Text files contain ASCII codes of digits, alphabetic and symbols.
 Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version
of text files.

Basic operations in File


 Declare a file pointer variable
 Opening a file
 Closing a existing file
 Reading from the file
 Writing to the file
 Deleting the file

Declaration of file pointer:


A pointer variable is used to points a structure FILE. The members of the FILE
structure are used by the program in various file access operation, but programmers do not
need to concern about them.
Syntax:
FILE *file_pointer_name;
Example: FILE *fp;

Opening a file : fopen()


A data file must be opened before it can be created or processed; this associates the file
name with a buffer area.
Opening a file means creating a new file with specified filename and with accessing mode.

Syntax: FILE *fp;


fp = fopen("filename”,”made”);

Example:
FILE *fp1, *fp2;
fp1 = fopen("data", "r");
fp2 = fopen("[Link]", "w");
The file “data” is opened for reading, and “result” is opened for writing.
If “data” already exists, its contents are deleted and it is opened as a new file.

SINCET - CSE II
File Accessing Modes:
Text File Modes

Mode Description

"r" Opens a file for reading. File must exist.

"w" Opens a file for writing. Creates a new file or overwrites if it exists.

"a" Opens a file for appending. Data is added at the end. Creates file if needed.

"r+" Opens a file for reading and writing. File must exist.

"w+" Opens a file for reading and writing. Overwrites file or creates new one.

"a+" Opens a file for reading and appending. Creates file if it doesn’t exist.

Binary File Modes

Mode Description

"rb" Opens a binary file for reading. File must exist.

"wb" Opens a binary file for writing. Overwrites or creates a new file.

"ab" Opens a binary file for appending. Adds data to end. Creates file if needed.

"rb+" Opens a binary file for reading and writing. File must exist.

"wb+" Opens a binary file for reading and writing. Overwrites or creates new.

"ab+" Opens a binary file for reading and appending. Creates if needed.

Closing a existing file : fclose()


A file must be closed after all the operations of the file have been completed.
Syntax:

fclose(file_pointer);

By doing this, all the information associated with the file is flushed out from the buffer
and links to the file are broken. It prevents any misuse of the file.
Example:
fclose(fp);

This would close the file associated with the FILE pointer fp. The file pointer can be
reassigned for another file.
All files are closed automatically whenever a program terminates.

SINCET - CSE II
Creation of Text File

#include <stdio.h>
#include <conio.h>
void main()
{
char ch;
FILE *fp;
fp = fopen("[Link]", "w");
clrscr();
printf("\nType the text. Press enter key at end.\n");
printf("\nTo stop input, press ^Z and then Enter.\n");
while((ch = getchar()) != EOF)
putc(ch, fp);
fclose(fp);
getch();
}

Output:
Type the text. Press enter key at end.
Welcome to This Sample Test
Welcome to This Sample Test

Reading from the file:


The following function used to reading from the file.
 fread()
 fgetc()
 fgets()
 fscanf()

fread() function:

The fread statement is used to read x bytes (size of record) from the file ptr_myfile into
memory address &my_record. Only one block is requested. Changing the one into ten will
read in ten blocks of x bytes at once.

Syntax:
fread(&my_record, sizeof(struct rec), 1, ptr_myfile);
Example:
fread(buffer, sizeof(int),5, file);

fgetc() : Read a character from a file:


The getc function is used to read a character from a file which is opened in the read
mode.
Syntax:
int fgetc(FILE *pointer);

pointer: pointer to a FILE object that identifies


the stream on which the operation is to be performed.
Example: char c = fgetc(fp);
3

SINCET - CSE II
fgets()
fgets() is a built-in function in <stdio.h> used to read a line of text from input.
It stores the input into a character array and stops reading when it reaches a newline
character, the specified number of characters, or end-of-file (EOF).
Syntax:
fgets(buff, n, stream);

 buff: Pointer to the string buffer where the input will be stored.
 n: The maximum number of characters to read (including the null terminator).
 stream: The input stream, typically stdin for reading from the keyboard
Example:
fgets(buff, n, stdin);

fscanf() function : reading data from a file


The fscanf() function is used to read data from a file. It is similar to the scanf() function
except that fscanf() is used to read data from the disk.

Syntax:
fscanf(file_pointer, "format string", &var1, &var2, &var3….. &varn);

where fp refers to the file pointer.

v1, v2, v3 refer to variables whose values are read from the disk.
"format string" represents the conversion specification.
Example:

fscanf(fp, "%s %d %f", &name, &age, &cost);

Note:
The format specifier space compulsorily in the format string variable. Also, loop shall be used
to read values of the data stored in the disk.
Writing to the file:

The following functions used to writing to the file.


 fputc()
 fputs()
 fprintf()
 fwrite()
fputc() function: Write character to a file: putc() function
The function putc() is used to write a character variable x to the file opened in write
mode.

Syntax:
int fputc(int char, FILE *pointer)
char: character to be written.
This is passed as its int promotion.
pointer: pointer to a FILE object that identifies the
stream where the character is to be written.
Example:
fputc(string[i], fp);
4

SINCET - CSE II
fputs():
fputs() is a function declared in stdio.h header file. It is used to write the contents of
the file.
Syntax:
fputs(const *char str, FILE *fp);
where str is a name of char array that we write in a file and fp is the file pointer.
Example: fputs(str, fp);
fprintf() function:
fprintf() function is used to write data to a file. It is similar to the printf() function
except that fprintf() is used to write to the disk.
Syntax:
fprintf(fp, "format string", var1, var2, var3…varn);
Where fp refers to file pointer.
Example:
fprintf(fp, "%s %d %f", name, age, cost);
fwrite()
fwrite() is a built-in function used to write a block of data from the program into a
file. It can write arrays, structs, or other data to files but is especially designed to write
binary data in binary files.
Syntax:
fwrite(a, size, count, fptr);
a: Name of the array to be written.
size: Size of each element.
count: Number of elements to be written.
fptr: Pointer to the file
Example:
fwrite(s, sizeof(char), strlen(s), fptr);

Deleting the file:


When reading from a text-mode file character by character, one can look for the end-
of-file character. The symbolic constant EOF is defined in stdio.h as -1, a value never used by a
real character.
Eg: while((c=getc(fp)!=EOF).
This is the general representation of the End Of the File.
To create a file to store details of students
#include <stdio.h>
#include <conio.h>
void main()
{
int i, no, stu_age;
char stu_name[20];
FILE *fp;
fp = fopen("[Link]", "w");
clrscr();
printf("How many students?\n");
scanf("%d", &no);
for(i = 0; i < no; i++)
{
printf("Enter Student no, name, and age\n");
5

SINCET - CSE II
scanf("%d %s %d", &i, stu_name, &stu_age);
fprintf(fp, "%d %s %d", i, stu_name, stu_age);
}
fclose(fp);
getch(); }

Random Access to files of records:

For random access to files of record, the following functions are used.
 fseek()
 ftell()
 rewind()

fseek() : by using fseek(), one can set the position indicator anywhere in the file.
It’s prototype is,
int fseek(FILE *fp,long offset,int origin);

It has the origins as, SEEK_SET, SEEK_CUR,SEEK_END

ftell() : To determine the value of a file’s position indicator, use ftell().


The prototype is,
long ftell(FILE *fp);
rewind() :To set the position indicator to the beginning of the file, use the function rewind().
Its prototype is,
void rewind(FILE *fp);
Creating the header files in C :
Creating the header files using the following steps,
Step 1: Create the function, using function header and function body.
Example:
int add(int a,int b)
{
c=a+b;
return c;
}
Step 2: Save the above function using [ .h ] extension. and compile the code.
Example: above function can be save as myhead.h.
Step 3: Write the main program, include our own header file in the program. Now main
function
automatically includes the function available in the header file.
Example:
#include #include ”myhead.h”
void main()
{ int num1=10,num2=20,num3;
num3=add(num1,num2);
printf(“\n Sum of two numbers is : %d”,num3);
}
Note : When running the program, header file and the program must be present in the same
folder.

SINCET - CSE II
Error handling suring IO Operation
The error may occur during IO [Link] error situations include,
1. opening a file with an invalid file name.
2. Trying to use a file that has not been opened.
3. Trying to read a file that may not be present.
4. Trying to read a file beyond the EOD mark
5. Trying to write into a write producted file.
6. Device overflow
If we uncheck the error. The program maybehave abnormal when an error
occured. It may result the following
The program execution is terminated
Incorrect output
Detecting IO error
The feof() and ferror() functions are used to detect IO errors in the file

feof():
It is used to test for an end of the [Link] returns nonzero integer value if all of the
data from the specified file has been read and returns zero
Example
if(feof(dp))
Printf("end of the file");
It's displays the message " end of the file" when reaching the end of the
condition.

ferror()
It is used to report the status of the file indicated. It returns a nonzero integer value if
an error has been detected upto that point during processing. It returns zero otherwise.

Example
if(ferror(fp)!=0)
Printf("An error has occurred);
It displays the message"An error has occured " if the reading is not successful.
#include <stdio.h>

int main() {
FILE *fptr = fopen("[Link]", "w");

Check Error When Writing Data


// Write data to the file
fprintf(fptr, "Hello, GFG!");

// Check error after writing data into file


if(ferror(fptr)==0)
printf("Data written successfully.");
fclose(fptr);
return 0;
}

SINCET - CSE II
UNIT-I / PART-A
1. What are the different data types available in “C”? (May 14)
There are four basic data types available in C.
 int
 float
 char
 double
2. What is an Operator, Operand and Keywords?
 Operator
 An operator is a symbol that specifies an operation to be performed on
operands. Example: *, +, -, / are called arithmetic operators.
 Operand
 The data items that operators act upon are called operands. Example: a+b;
In this statement a and b are called operands.
 Keywords
 Keywords are certain reserved words that have standard and pre-
defined
meaning in C. These keywords can be used only for their intended purpose.
3. Define Constants in C. Mention the types.
The constants refer to fixed values that the program may not alter during its
execution. These fixed values are also called literals. Constants can be of any of the
basic data types like an integer constant, a floating constant, a character constant,
or a string literal. There
are also enumeration constants as well. The constants are treated just like
regular variables except that their values cannot be modified after their
definition.
4. What are Ternary operators or Conditional operators? (or) Give an Example for
Ternary operator. (Nov/Dec 14)
Ternary operators is a conditional operator with symbols ? and :
Syntax: test ? expression1 : expression2
 test-Any Boolean expression.
 expression1-An expression returned if test is true.
 expression2-An expression returned if test
is false. #include<stdio.h>//Header File
void main()//Main function of every C program
{
int a,b,c;
clrscr();
printf("Enter the values of a and b:");
scanf("%d%d" ,&a,&b
c = a>b ? a : b; //Ternary operator
printf("Larger number=%d" ,c);
}
Output
Enter the values of a and
b:30 90 Larger number=90

SINCET - CSE II
5. What are the Bitwise operators and logical operators available in C ?
 Bitwise operators
 Bitwise AND, | - Bitwise OR, ~ - One„s Complement, >> - Right shift, << -
Left shift,
 ^ - Bitwise XOR are called bit field operators.
 Example: k=~j; where ~ take one„s complement of j and the result is
stored in k.
 Logical operators
 The logical operators available in C are &&- Logical AND, || - Logical OR,
! - Logical NOT
6. What is a Variable? Illustrate it with an example. (Nov/Dec 14)
 A variable is a data name used for storing a data value.
 Can be assigned different values at different times during program
execution.
 Can be chosen by programmer in a meaningful way so as to reflect its
function in the program.
 Example: int i, num; //i, num are variables that can store integer values
7. What is the difference between Logical AND and Bitwise AND?
 Logical AND (&&): Only used in conjunction with two expressions, to test
more than one condition. If both the conditions are true the returns 1. If
false then return 0.
 AND (&): Only used in Bitwise manipulation. It is a unary operator.

8. What is the importance of keywords in C. (May 15)


C programs are constructed from a set of reserved words which provide control
and from libraries which perform special functions. The basic instructions are
built up using
a reserved set of words, such as main, for, if, while, default, double, extern, for,
and int, etc., C demands that they are used only for giving commands or making
statements.
9. What is type casting?
Type casting is the process of converting the value of an expression to a
particular data type.
Example:
int x, y; c = (float) x/y; where a and y are defined as integers. Then the result of
x/y is
converted into float.
10. What are various types of C operators? (Jan 14)
 Arithmetic Operators
 Increment and Decrement Operators
 Assignment Operators
 Relational Operators
 Logical Operators
 Conditional Operators
 Bitwise Operators

SINCET - CSE II
11. What are the main features and applications of C language? (Jan 11)
C is case sensitive language.
 Modularity: we can split the C program into no. of modules. It allows
reusability of modules.
 Middle level language: as a middle level language C combines both the
advantages of low level and high level languages. (arrays, pointers etc).
Efficient Use of Pointers
 General purpose programming language: C can be used to implement any
kind of applications such as math‟s oriented, graphics, business oriented
applications.
 Portability: we can compile or execute C program in any operating
system (unix,dos,windows).
 Powerful programming language: C is very efficient and powerful
programming language, it is best used for data structures and designing
system software.
12. What is the difference between while loop and do…while loop? (or)
Differentiate
Entry and Exit controlled constructs. (Jan 13)
While do-while
Its an entry controlled loop Its an exit controlled loop
In the while loop the condition is first In the do…while loop first the
executed. If the condition is true then it statement is executed and then the
executes the body of the loop. When the condition is checked. The do…while
condition is false it comes of the loop loop will execute
at least one time even though the
condition is false at the very first time
Syntax: Syntax:
while(condition) do
{ {
//body of the loop //body of the loop
} } while(condition);
13. What is a Modulo Operator? What is the use of sizeof( ) operator?
 Modulo Operator
„%‟ is modulo operator. It gives the remainder of an integer division
o Example: a=17, b=6. Then c=%b gives 5.
 Sizeof( ) operator
 The sizeof ( ) operator gives the bytes occupied by a variable.
 No of bytes occupied varies from variable to variable depending upon
its data types.
Example:
int x,y;
printf(“%d”,siz
eof(x));
Output: 2

SINCET - CSE II
14. Define with example integer and floating type of data in C language. (Jan 11)
 The int is used to define integer numbers. An integer occupies 2 bytes
memory space and its value range limited to -32768 to +32767 (that is, -215
to +215-1) Example: int count=5
 The float is used to define floating point numbers. The float data type is used
to store fractional numbers (real numbers) with 6 digits of precision. Floating
point numbers are denoted by the keyword float.
Example: float miles = 4.5
15. What are the I/O Functions in C? (May 15, Jan 16)
 Formatted I/O Statements
 scanf(),printf()
 Unformatted I/O Statements:
 getchar(), putchar(), gets(), puts()
16. What is the difference between ++a and a++?
 ++a means do the increment before the operation (pre increment)
 a++ means do the increment after the operation (post
increment) Example:
a=5;
x=a++; /* assign x=5 but „a‟ value is incremented to
6*/ y=a; /*now y assigns y=6*/
x=++a; /*assigns x=7 and a value is incremented to 7*/
17. Construct an infinite loop using while?
while (1){ }
Here 1 is a non zero, value so the condition is always true. So it is an infinite loop.
18. What is a program?
A program is a set instruction written to carry out a particular task, so that
computer can perform some specified task. Example program to find sum of 2
numbers #include<stdio.h>
void main()
{ int a, b, sum; printf("\nEnter two no: "); scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum : %d", sum);
}
Output : Enter two no: 5 6 Sum : 11
19. What is a global variable?
The global variable is a variable that is declared outside of all the functions. The
global variable is stored in memory, the default value is zero. Scope of this
variable is available in all the functions. The variable is live as long as the
program terminates.
Example: #include<stdio.h>
int a,b; //a,b are global variables main()
{...}
20. What are the Escape Sequences present in “C”?
Escape Sequence Symbol Escape Sequence Name
\n New Line
\t Tab space
\r Carriage return
\f Form feed

SINCET - CSE II
21. Write the limitations of getchar( ) and scanf( ) functions for reading strings
 getchar( )-To read a single character from stdin, then getchar() is the
appropriate.
 scanf( ) allows to read more than just a single character at a time. In scanf()
when there is a blank was typed, the scanf() assumes that it is an end
22. What is the difference between scanf() and gets() function?
In scanf() when there is a blank was typed, the scanf() assumes that it is an [Link]()
accepts any datatype using appropriate format specifier. gets() assumes the enter key
as end. That is gets() gets a new line (\n) terminated string of characters from the
keyboard
and replaces the „\n‟ with „\0‟. It accepts the input as only strings
23. Define Compilation, linking process? (or) What is meant by Linking process. (Jan
16)
 Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the
creation of an 'object' file. This step doesn't create anything the user can actually
run. Instead, the compiler merely produces the machine language instructions that
correspond to the source code file that was compiled.
 Linking refers to the creation of a single executable file from multiple object
files. In this step, it is common that the linker will complain about undefined
functions (commonly, main itself). During compilation, if the compiler could
not find the definition for a particular function, it would just assume that the
function was defined in another file. If this isn't the case, there's no way the
compiler would know it doesn't look at the contents of more than one file at a
time. The linker, on the other hand, may look at multiple files and try to find
references for the functions that weren't mentioned.
24. Write a C Program to find factorial of a given number using iteration.
#include<stdio.h> int main()
{
int i=1,f=1,num; printf("Enter a number: "); scanf("%d",&num); while(i<=num)
{
f=f*i; i++;
}
printf("Factorial of %d is: %d",num,f); return 0;
}
Output:
Enter a number: 5 Factorial of 5 is 120
25. Write a for loop statement to print numbers from 10 to 1. (Jan 14)
for( i=10;i>=1;i--)
printf(“\n%d”,i);

26. List some preprocessor directives in C.(Jan14, 16)


 Macro Replacement Directive (#define,#undef)
 Source File Inclusion Directive (#include)
 Line Directive (#line)
 Error Directive (#error)

SINCET - CSE II
27. Give the rules for defining preprocessor.
 # pound symbol used before preprocessor directive
 # must be first character in source file or first non white space character in a
line
 New line character ends preprocessor directive
 Only single space/tab space allowed between preprocessing tokens
 Can appear anywhere in program but generally paced in beginning of
program
 The preprocessor cannot have termination with semicolon.
28. What is meant by storage class?
Every C variable has a storage class and a scope. The storage class determines the
part of memory where storage is allocated for an object and how long the storage
allocation continues to exist. It also determines the scope which specifies the part
of the program over which a variable name is visible, i.e. the variable is accessible
by name. The following are the storage classes which can be used in a C Program.
 auto ,register ,static and extern

29. Define Static Storage Class (Dec 14)


Storage class specifier static specifies that the declared object can be used both
in local scope and global scope. Static variable/object has a value throughout the
execution of the program and the object will be saved in main memory
Example: static int a;
30. What is meant by Preprocessor Directives?
 Preprocessor is controlled by directives (commands) known as
Preprocessor Directives
 Preprocessor directives are not part of C language
 It consists of various preprocessing tokens
Begins with pound symbol(#)
31. Difference between Storage class and data type
Data type Storage class
It refers to the type of information It refers to the scope and
lifetime of the
represented by a variable variable within the program
Example: int, char, float Example: register, static, extern
32. What is the use of pre-processor directives? (May 14,15, 19)
 It makes programs easier to develop,
 easier to read,
 easier to modify
 C code more transportable between different machine architectures.
33. What is the use of #define processor? (Dec 14)
#define directive is used to define Macros –which are tokens that can be replaced
for user defined sequence of characters
Syntax: #define macro-name replacement-list
Example: #define PI 3.14

SINCET - CSE II
34. What is enumeration constant?
An enumeration is a list of constant integer values, as in enum boolean {NO, YES};
The first name in an enum has value 0, the next 1, and so on, unless explicit values
are specified. Names in different enumerations must be distinct. Values need not
be distinct
in the same enumeration
35. What is external storage class? (May 18)
A variable declared with the extern storage-class specifier is a reference to a variable
with the same name defined at the external level in any of the source files of the
program. A variable declared with the extern keyword is visible only in the block in
which it is declared
36. How does a pre-processor work? (May 18)
 Preprocessor translator converts high level language program to an
equivalent program in another high language
 Preprocessor is controlled by directives (commands) known as
Preprocessor Directives
 Preprocessor directives are not part of C language
 It consists of various preprocessing tokens
 Begins with pound symbol(#)
37. Difference between formatted and unformatted input [Link] one
example for each. (May 19)
 Formatted input : The function scanf() is used for formatted input from standard
input and provides many of the conversion facilities of the function printf().
 Example: scanf(“ %c %d”,&name, &rollNo);
 Unformatted input : Unformatted I/O is the most basic form of I/O and it is
simple, efficient and [Link] is an input stream object in order to read a
portion of information in the form of bytes, without any translation.
getchar() and getch() functions will read a single character from the
standard input.
Example: char ch; ch = getchar();
UNIT-I / PART-B
1. (i) Explain in detail about “C” declarations and variables. (Jan 11)
(ii) What are constants? Explain the various types of constants in C. (May 15)
2. Discuss about the various data types in “C”.
3. Explain about the various decision making statements in “C” language. (or) Write
notes
on Branching Statements in C. (Jan 14,16 May 14,18)
4. Explain various operators in c with example? (or) Explain the different types of
operators used in C with necessary program. (Dec 14, May 15,18)
5. Explain briefly about the formatted and unformatted I/O function in C. (Jan 12)
6. Explain the different looping statement with example? (or) What is the purpose of
looping statement? Explain in detail the operations of various looping statement
with examples. (Jan 14,16, Dec 14, , May 15, 18, 19)
7. (i) Write a C program to check whether the given number is palindrome or not.
(May 18)
(ii) Write a C program to sum of digits of an integer. (Jan 12, May 14)

SINCET - CSE II
8. Write a program to solve the Quadratic equation. (May 15)
9. Write a program to find whether a number is prime or not. (May 14)
10. Describe the structure of a C program using “Calculator program” example. (Jan
12)
11. Explain in detail about preprocessor directives with examples.
12. Explain the concept of storage classes with suitable example. (or) What are the
Storage
classes available in C ? Demonstrate the working of each storage class.(May 14,
19, Jan 16)
13. Write a C program to find the sum of 10 non-negative numbers entered by the
user.
(May 14)
14. Write a C program to find the largest among 3 numbers entered by the user. (May
19)

SINCET - CSE II
UNIT -2 (ARRAYS and STRINGS)

[Link] scanf() function:


Scan f () function is used to read the value from the input device.

1. Define printf () function:


Print f ()function is used to display data on the monitor.

2. Define decision making statement:


These statements are used to execute particular set of instruction for based on certain
condition.
Ex:if, if else, nested if, if else if ladder, switch.

3. Define looping statement :


Looping statement are used to execute a group of instruction repeatedly at till some
condition is satisfied.
Example: while, do while, for loop.

4. Define unconditional statement:


This condition is used to transfer the control to other statement without checking any
condition.
Example : goto, break.

5. Define simple if statement:


It is used to execute some statements for a particular condition.

6. Define switch statement :


Switch statement is the simple form of if….else….. If ladder construct. Switch statement
is a multi branch decision statement.

7. Define for statement :


The for loop is entry controlled loop that provides a more concise loop control structure.

8. Define goto statement:


Goto statement can transfer the control to any place in a program. It is useful to provide
branching within a loop.

9. Define break statement:


Break statement exit from the loop can be accomplished by using the break statement.

10. Define exit statement:


It is used to terminate the program it is same as break statement.

11. what is getchar() :


Getchar () function is used to read one character at a time from the standard input
device.

SINCET - CSE II
Define putchar() :
Single character can be displayed using the function putchar().
The function putchar() stands for “putchar”and uses an
argument.

12. Define Array


Array is a collection of similar type of values
All values are stored in
continuous memory locations
All values share a common
name
Linear data structure. The elements are organized in a sequential order.
13. Name any two library functions for handling string
strlen() – finds the length of a string. It returns an integer
value. It counts the no. of characters except null character &
returns the count
strlen(str)
strcpy() – copies the source string into destination string. So, the
source string should be enough to store the destination string.
strcpy(source,destination)
3. Declare a float array of size 5 and assign 5 values to it
Declaration : float price[5];
Initialization : float
price[5]={200.50,150.25,25.5,55.75,40.00};
(or) float price[]={1.2,3.4,6.5,7.8,9.8};

4. Give an example for initialization of string array


String is a character array.
Collection of one or more characters- enclosed with in
double quotes Declaration : char name[10];
Initialization :
char
name[10]=‖Indi
a‖; car
name[10]={‗I‘,‘
n‘,‘d‘,‘i‘,‘a‘};
The char array is terminated by ‗\0‘

5. How a character array is is declared


Declaration : char name[n];
This array can
store n-1
characters.
Initialization :
char
name[10]=‖Indi
a‖; car
name[10]={‗I‘,‘

SINCET - CSE II
n‘,‘d‘,‘i‘,‘a‘};
The char array is terminated by ‗\0‘
6. Write example code to declare two dimensional array
Two dimensional array is an array with two subscript values. First
subscript specifies the row & second subscript specifies the
column. Used to process matrix operations.
Declaration : datatype array_name [r][c];
int matrixA[10][10];
This matrixA can store 100 elements in a row major order.

7. What is mean & median of a list of elements?

Mean : Average of the N elements


can be computed by sum of N
elements/N
Ex: 2,1,3,4,5
Mean = (2+1+3+4+5)/5 = 3
Median : Middle element of a list. To find the median, the
list must be sorted first. If N is odd then Median= (N+1)/2
Ex: 1,2,3,4,5
Median= 6/2 . The element at
3rd position is the median If N is
even then then Median is the
average of Median=
(a[(N+1)/2]+a[(N-1)/2])/2
Ex: 1,2,3,4,5,6
Median=(a[3]+a[2])/2
=4+3/2
=3.5

PART B

1. Explain in detail about One - dimensional Array

2. Explain in detail about Two Dimensional Array

3. Explain in detail about String Operations

4. Write a c program for 3 X 3 Matrics Multiplication

5. String handling Functions

SINCET - CSE II
FUNCTIONS AND POINTERS
Modular programming - Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion– Pointers – Pointer operators – Pointer arithmetic –
Arrays and pointers – Array of pointers – Parameter passing: Pass by value, Pass by reference.

UNIT-III / PART-A
1. What is meant by Recursive function?
If a function calls itself again and again, then that function is called Recursive function.
2. What is a Pointer? How a variable is declared to the pointer?
Pointer is a variable which holds the address of another variable.
Pointer Declaration: datatype *variable-name;
Example: int *x, c=5; x=&a;
3. What are the uses of Pointers?
Pointers are used to return more than one value to the function, Pointers are more
efficient in handling the data in arrays, Pointers reduce the length and complexity of the
program, They increase the execution speed, The pointers saves data storage space in
memory
4. What are * and & operators means?
„*‟ operator means „value at the address‟ „&‟ operator means „address of‟
5. What is meant by Preprocessor?
Preprocessor is the program, that process our source program before the compilation.
6. How can you return more than one value from a function?
A Function returns only one value. By using pointer we can return more than one value.
7. Is it possible to place a return statement anywhere in „C‟ program?
Yes. The return statement can occur anywhere.
8. What is the difference between an array and pointer?
Array Pointer

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


allocated space.
It cannot be resized. It can be resized using
realloc (),
It cannot be reassigned, Size of(array Pointers can be reassigned, Sezeof(pointer
name) gives the number of bytes occupied name) returns the number of bytes used to
by the array. store the pointer variable.
9. What is dangling pointer?
In C, a pointer may be used to hold the address of dynamically allocated. Memory After
this memory is freed with the free() function, the pointer itself will still contain the
address of the released block. This is referred to as a dangling pointer. Using the pointer
in this state is a serious programming error. Pointer should be assigned NULL after
freeing memory to avoid this bug.

SINCET - CSE II
10. Is using exit() the same as using return?
No. The exit() function is used to exit your program and return control to the operating
system. The return statement is used to return from a function and return control to the
calling function. If you issue a return from the main() function, you are essentially returning
control to the calling function, which is the operating system. In this case, the
return statement and exit() function are similar.
12. What is meant by Recursive function?
If a function calls itself again and again, then that function is called Recursive function.

13. What is the difference between NULL and NUL?


NUL is the name of the first character in the ASCII character set. It corresponds to a zero
value. There's no standard macro NUL in C, but some people like to define it. NULL can
be defined as ((void*)0), NUL as '\0'. Both can also be defined simply as 0. If they're
defined that way, they can be used interchangeably.

14. What is a "null pointer assignment" error? What are bus errors, memory faults, and core
dumps?
Null pointer assignment is a message you might get when an MS-DOS program finishes
executing. Some such programs can arrange for a small amount of memory to be
available "where the NULL pointer points to" (so to speak). If the program tries to write
to that area, it will overwrite the data put there by the compiler. When the program is
done, code generated by the compiler examines that area. If that data has been changed,
the compiler-generated code complains with null pointer assignment.
15. Write the syntax for including functions?
The syntax for including functions in program is return_type function_name(datatype
var1, datatype var2,…);
//FUNCTION DECLARATION
int main()
{
variable_name = function_name(var1, var2, …);
//FUNCTION CALL
….. Return 0;
}
return_type function_name(datatype var1, datatype var2,…)
//FUNCTION DEFINITION
{
….. statements
…… return(variable);
}
16. What is Pointer Arithmetic?
A pointer is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can on a numeric value. There are four arithmetic
operators that can be used on pointers: ++, --, +, and -.

SINCET - CSE II
17. How does free() know how much memory to release?
There's no standard way. It can vary from compiler to compiler, even from version to
version of the same compiler. free(), malloc(), calloc(), and realloc() are functions; as
long as they all work the same way, they can work any way that works.
18. Can math operations be performed on a void pointer?
No. Pointer addition and subtraction are based on advancing the pointer by a number
of elements. By definition, if you have a void pointer, you don't know what it's pointing
to, so you don't know the size of what it's pointing to. If you want pointer arithmetic to
work on raw addresses, use character pointers.
19. What is a void pointer?
A void pointer is a C convention for "a raw address." The compiler has no idea what type
of object a void pointer "really points to." If you write
int *ip;
ip points to an int. If you write void *p; p doesn't point to a void!
20. What is indirection?
If p is a pointer, the value of p is the address of the object. *p means "apply the
indirection operator to p"; its value is the value of the object that p points to. *p is an
lvalue; like a variable, it can go on the left side of an assignment operator, to change the
value. If p is a pointer to a constant, *p is not a modifiable lvalue; it can't go on the left
side of an assignment.
21. What is the difference between far and near pointers?
Compilers for PC compatibles use two types of pointers.
 near pointers are 16 bits long and can address a 64KB range. far pointers are 32
bits long and can address a 1MB range.
 near pointers operate within a 64KB segment. There's one segment for function
addresses and one segment for data.
22. What do you mean by array of pointers?
 An array of pointers is an indexed set of variables in which the variables
are pointers (a reference to a location in memory).
 Pointers are an important tool for creating, using, and destroying all types of data
structures.
Example: int *ptr[10];
The above statement declares array of an array of 10 pointers where each of the pointer
points to an integer variable.
23. What is built-in functions?
The standard library functions are built-in functions to handle tasks such as
mathematical computations, I/O processing, string handling etc. Built-in function is a
set of code that takes a finite number of input and optionally returns a value. These
functions are defined in the header file. Functions that operate on string expression are
classified as string functions, they include functions for finding the length
of a given text, remove certain words from a text etc.
24. Why should I prototype a function?
A function prototype tells the compiler what kind of arguments a function is looking to
receive and what kind of return value a function is going to give back. This approach
helps the compiler ensure that calls to a function are made correctly and that no
erroneous type conversions are taking place.

SINCET - CSE II
25. Should a function contain a return statement if it does not return a value?
In C, void functions (those that do not return a value to the calling function) are not
required to include a return statement. Therefore, it is not necessary to include a return
statement in your functions declared as being void. In some cases, your function might
trigger some critical error, and an immediate exit from the function might be necessary.
In this case, it is perfectly acceptable to use a return statement to bypass the rest of the
function's code.
26. How do you use a pointer to a function?
The hardest part about using a pointer-to-function is declaring it. Consider an example.
You want to create a pointer, pf, that points to the strcmp() function. The strcmp()
function is declared in this way:
int strcmp( const char *, const char * )

27. List the advantage of recursion. (May 18)


 Reduce unnecessary calling of function.
 Through Recursion one can Solve problems in easy way while its iterative solution
is very big and [Link] example to reduce the code size for Tower of Honai
application, a recursive function is bet suited.
 Extremely useful when applying the same solution.
28. What is the need for functions? (May 19)
Functions are used because of following reasons
 To improve the readability of code.
 Improves the reusability of the code, same function can be used in any program
rather than writing the same code from scratch.
 Debugging of the code would be easier if you use functions, as errors are easy to
be traced.
 Reduces the size of the code, duplicate set of statements are replaced by function
calls.
29. What is the output of the following code fragment? (May 19)
int =456, *p1, **p2; p1=&x;
p2=&p1;
printf(“Value of x is: %d\n”, x); printf(“Value of *p1 is: %d\n”, *p1); printf(“Value of *p2
is: %d\n”, *p2);
Output:
Value of x is: 456 Value of *p1 is: 456
Value of *p2 is: 1640617564

SINCET - CSE II
UNIT-III / PART-B
1. When is a null pointer used? (May 18)
2. What do you mean by Call by reference? Explain with an example.
3. What do you mean by Call by Value? Explain with an example.
4. Write a „C‟ Program to interchange two values using call by reference (or)
What is pass by reference? Explain swapping of 2 values using pass by reference in „C‟.
(May 19)
5. Can you subtract pointers from each other? Why would you?
6. How do you use a pointer to a function? When would you use a pointer to a function?
7. Write a C program to generate Fibonacci series using function.
8. Write a C Program to find factorial of a given number using recursive function.
9. What is Pointer? How to pass pointer as an argument in function?
10. How can you pass an array to a function by value?
11. Explain the use of pointers in array handling with an example. (Nov 07)
12. Write a function using pointers to add matrix and to return the resultant matrix to the
calling function. (May 08)
13. (i) Explain the purpose of a function prototype. And specify the difference between the user
defined function and built-in function (May 18)
(ii) Write the C program to find the value of sin(x) using the series up to the given
accuracy (without using user defined function) also print sin(x) using library function.
(May 18)
14. (i) What is difference between pass by value and pass by reference? Write the C coding for
swapping two numbers using pass by reference. (May 18)
(ii) What is recursion? Explain the procedure to compute sin(x) using recursive
functions. Write a C code for the same. (May 19)
15. When is a null pointer used? (May 18)

SINCET - CSE II
STRUCTURES AND UNION
Structure - Nested structures – Pointer and Structures – Array of structures – Self referential
structures – Dynamic memory- typedef – Union - Storage classes and Visibility

UNIT-IV / PART-A
1. What is a structure? (or) State the meaning of the root word struct. (May 15,18)
 It‟s a User defined data type
 Can hold many data objects of different data types (heterogeneous) may contain the
integer elements, float elements and character elements. etc.
 Collection of variables under single name
 Can conveniently used to represent a record
2. Give syntax for structure definition
Syntax:
[storage class specifier][data type] struct [structure name]
{
Data _type memeber_name[, member name 2,..];
Data _type memeber_name[, member name 2,..];
}[variable name];
Example:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
3. Define structure declaration.
 Variables/constants for structure types can be declared at definition or after
definition
 [storage class specifier] struct named_Structure-type identifier name
[=initialization list];
 Struct key word mandatory
 A structure must end with a semicolon
Example: Declare variables Book1,Book2 of type Books
struct Books Book1;
struct Books Book2;
4. Write the rules for declaring a structure?
 A structure must end with a semicolon
 Struct key word mandatory
 Each structure member must be terminated.
 The structure variable must be accessed with dot(.) operator.
 Structure decaration list (structure members):
1. Can have char, float, double, int, array[], pointer* other structure types
2. Cannot have void, function type, same structure instance
3. Can have pointer to an instance of itself which is called as self referential
structures.

SINCET - CSE II
5. Write the three ways to pass structure variables.
 Pass each member of the structure as an actual argument of the function call.
 Pass a copy of the entire structure to the called function
 Through pointer pass the structure as an argument.
6. How structure elements can be accessed?
Structure members can be accessed using
1. Direct member access operator/dot operator
 Represented as (.)
 It‟s a Binary Operator
 Syntax: Structure_name.structure_member_name
2. Indirect member access operator/arrow operator
 Represented as (->)
 It‟s to access structure members by the pointer to the structure
 Syntax: Pointer_to_Structure->structure_member_name
7. Differentiate between array and structure. (OR) Compare and contrast a structure
with an array (May 19)

Array Structure
An array is a collection of variables of A structure is a collection of variables
same data type of different data types
An array is a derived data type It is a user defined data type.
The individual data members of an array The individual data members of the
can be initialized. structure cannot be initialized.
Array elements can be accessed by Structure members can be accessed using
indexing the array name. dot operator / arrow operator
8. Give rules for initializing structure
 The individual data members of the structure cannot be initialized.
 The structure variables can be initialized at compile time only.
 The order of data members in a structure must match the order of values in enclosed
brackets.
 We can initialize only some of the data members of the structure.
 The uninitialized data members can be initialized by default with zero(0) for int and
float 0.0 and „\0‟ for character and strings.
9. Define nested structure.
 Structure within another structure is called as nested structure
 Used to create complex data types
 Nested Structures contain declaration of members of other structure types
 We can also define a structure within declaration list of another structure
 Double braces used to initialize nested structure objects
 Eg: emp={name,salary,{date of birth}};
 It is used to increase the readability of the program by reducing the complexity.

SINCET - CSE II
10. Define the Structure called ID_card to hold the details of the student. (Jan 16)
struct ID_card
{
char name[50];
char address[50];
int age;
} b1,b2;
11. What are self-referential structures?
A structure consisting of at least a pointer member pointing to the same structure is
known as self-referential structure.
Example: struct Books
{
int book_id;
struct Books* ptr; };//ptr is a pointer pointing to structure type Books
12. Write the syntax of pointers to structures.
A pointer can be declared in such a way that it points to a structure data type. A pointer to a
structure is created as follows
struct student
{
int rno;
char name[23]; float avg;
};
struct student *str;
13. Difference between array and structures.
Array Structures
Array elements are of same data types Structure elements are of different data
(Homogeneous). type (heterogeneous).
Array allocates static memory and uses Structures allocate dynamic memory and
index / subscript for accessing elements uses (.) operator for accessing the member
of the array. of a structure.
Array is a pointer to the first element of it.
Structure is not a pointer
An array is a derived data type A structure is a user-defined data type
Example for Array Declaration Example for Structure Declaration
int b1[3]; struct Books {
int a; char b;
}b1;
14. Explain typedef with syntax and an example. (or) Specify the use of typedef. (Nov 18)
typedef is a keyword used in C language to assign alternative names to existing types. Its
mostly used with user defined data types, when names of data types get slightly complicated.
Syntax:
typedef existing_name alias_name
Example:
typedef unsigned long ulong;

SINCET - CSE II
15. Explain array of structures with an example.
Declaring an array of structure is same as declaring an array of fundamental types. Since an
array is a collection of elements of the same type. In an array of structures, each element
of an array is of the structure type.
Example:
struct car
{
char make[20];
char model[30];
int year;
};
17. Define dynamic memory allocation functions and list its types.
The process of allocating memory during program execution is called dynamic memory
allocation.
C language offers 4 dynamic memory allocation functions. They are,
1. malloc()
2. calloc()
3. realloc()
4. free()
18. Explain malloc with its syntax.
 malloc () function is used to allocate space in memory during the execution
of the program.
 malloc () does not initialize the memory allocated during execution. It
carries garbage value.
 malloc () function returns null pointer if it couldn‟t able to allocate requested
amount of memory.
Syntax: malloc (number *sizeof(int));
19. Explain calloc with its syntax.
 It allocates multiple blocks of requested memory. calloc () initializes the
allocated memory to zero
 Calloc () function is also like malloc () function. But calloc () initializes the
allocated memory to zero. But, malloc() doesn‟t.
Syntax : calloc (number, sizeof(int));

20. Explain realloc with its syntax.


 realloc () function modifies the allocated memory size by malloc () and calloc ()
functions to new size.
 If enough space doesn‟t exist in memory of current block to extend, new block is
allocated for the full size of reallocation, then copies the existing data to new block
and then frees the old block.
Syntax: realloc (pointer_name, number * sizeof(int));

21. Explain free function with example.


free () function frees the allocated memory by malloc (), calloc (), realloc () functions
and returns the memory to the system.
Syntax: free (pointer_name);

SINCET - CSE II
22. What is the output of the following code fragment? (May 19)
struct point
{ int x; int y;
}; struct point origin, *pp; main()
{
pp=& origin;
printf("origin is (%d%d)\n",(*pp).x,pp->y);
} Output: origin is (00)
UNIT-IV / PART-B
1. What is a structure? Create a structure with data members of various types and declare
two structure variables. Write a program to read data into these and print the same.
Write short notes on structure Declaration. (Jan 16)
2. Write a program to print student grade using structure / Write a C program to create a
mark sheet for students using structure. (Jan 14)
3. (i) Write short notes on nested structure / Explain the concept of structure within
structure with suitable program.
(ii) Define and declare a structure to store date, which including day, month and year.
(Jan 14)
4. Define a structure called book with book name, author name and price. Write a C program to
read the details of book name, author name and price of 200 books in a library and display
the total cost of the books and book details whose price is above
Rs.500. (May 15)
5. Write a C program to store the employee information using structure and search
a particular employee using employee number? (Jan 14) (May 14)
6. Explain dynamic memory allocation in detail (or) What is dynamic memory allocation?
Explain various C functions that are used for the same with examples. (May 19)
7. i) Difference between static memory allocation and dynamic memory allocation in c.
ii) Difference between malloc( ) and calloc( ) functions in c.

8. Write a C program to implement singly linked list using dynamic memory allocation.
9. Define structure in C. Also specify the pointer and structure with example. (May 18)
10. i) Write a C program for accessing structure member through pointer using dynamic
memory allocation. (May 18)
ii) Write a short note on singly linked list and specify how the nodes are created in
singly linked list. (May 18)
11. What are self -referential structures? Explain with suitable examples. (May 19)

SINCET - CSE II
FILE PROCESSING
Files – Types of file processing: Sequential access, Random access – Sequential access file - Random

access file

UNIT-V / PART-A
1. What is a File?
A File is a collection of related information that is permanently stored on the disk
and allows us to access and alter the information whenever necessary.
2. How do you open a file?
The File is opened by the statement
fp=fopen(“file-name”,”mode”);Where „fp‟ means file pointer, mode is
the file opening mode such as write, read, or append mode.
3. How do you close a file?
The file is closed by the statement fclose(file-pointer);
4. Mention any five file functions. (Jan 14)
fopen() :Creates a new file for use Opens a new existing file for use
fclose() : Closes a file which has been opened for use
fprintf() : Writes a set of data values to a
file fscanf() : Reads a set of data values
from a file
fseek() : Sets the position to a desired point in the
file ftell() : Gives the current position in the file
rewind() : Sets the position to the beginning of the file.
5. What is the use of rewind () function?
This function is used to reset the pointer to the beginning of the file.
6. What do you mean by Command line arguments? (or) What does argv and argc indicate
in command-line argument? (May 18,19)
The main functions can have arguments passed which are called as command line
arguments. There are two command line arguments:Argument count denoted by
argc and Argument vector denoted by argv
The argc is an integer variable which denotes the number of parameters passed and
argv is pointer to array of character strings. The syntax is as follows:
main( int argc , char * argv[ ])
{
….. }
It can also be returned as
main(argc,argv)
int
argc;
char *
argv[];
{
….
}

SINCET - CSE II
7. What is sequential access file?
To reading or writing data records in sequential order, that is, one record after the
other. To read record 10, for example, you would first need to read records 1
through 9.
8. What is Random access file?
To the ability to access data at random. The opposite of random access is sequential
access. To go from point A to point Z in a sequential-access system, you must pass
through all intervening points. In a random-access system, you can jump directly to
point Z.
9. Define what is the advantage of a random access file?
If the amount of data stored in a file is fairly large, the use of random access will allow
you to search through it quicker. If it had been a sequential access file, you would have
to go through one record at a time until you reach the target data. A random access file
lets you jump directly to the target address where data is located.
10. Define How do you search data in a data file using random access method?
Use the fseek() function to perform random access input/ouput on a file. After the file
was opened by the fopen() function, the fseek would require three parameters to work:
a file pointer to the file, the number of bytes to search, and the point of origin in the file.
11. Write a program in C language to create a data file.
#include <stdio.h> void main()
{
FILE *fptr;
fptr = fopen("[Link]", "w"); fclose(fptr);
}
12. What is the use of fseek() function?
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer -It is the pointer which points to the file.
displacement -It is positive or negative. This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position. This is attached
with L because this is a long integer.
13. Write a program to copy contents of [Link] file to [Link] file.
#include<stdio.h> #include<conio.h> #include<stdlib.h> void main() {
FILE *fp1, *fp2; char ch; clrscr();
fp1 = fopen("[Link]", "r");
fp2 = fopen("[Link]", "w"); while (1) {
ch = fgetc(fp1); if (ch == EOF)
break; else
putc(ch, fp2);
}
printf("File copied Successfully!"); fclose(fp1);
fclose(fp2);
}
14. Why ftell() method is used in C files?
This function returns the value of the current pointer position in the file. The value is
count from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.

SINCET - CSE II
15. Compare Text file and Binary file.
 Text file is human readable because everything is stored in terms of text. In binary
file everything is written in terms of 0 and 1, therefore binary file is not human
readable.
 A newline(\n) character is converted into the carriage return-linefeed
combination before being written to the disk. In binary file, these conversions will
not take place.
 In text file, a special character, whose ASCII value is 26, is inserted after the last
character in the file to mark the end of file. There is no such special character
present in the binary mode files to mark the end of file.
 In text file, the text and characters are stored one character per byte. For example,
the integer value 1245 will occupy 2 bytes in memory but it will occupy 5 bytes in
text
file. In binary file, the integer value 1245 will occupy 2 bytes in memory as well as in file.
16. Define File Pointer in C.
 To access any file, we need to declare apointer to FILE structure and then
associate it with the particular file.
 This pointer is referred to as file
pointer. Syntax to declare file pointer:
FILE * fp;
17. List down functions for reading and writing data of a file.
 Reading or writing characters using fgetc() and fputc() functions.
 Reading or writing string using fgets() and fputs() functions.
 Reading or writing integers using getw() and putw() functions.
 Reading or writing formatted IO using fscanf() and fprintf() functions.
 Reading or writing records using fread() and fwrite() functions.
18. What is purpose of library function feof()?
feof() function is a file handling function in C programming language which is used to
find the end of a file. Syntax: int feof(FILE *fp);
19. Write about the basic operations on files?
 Naming a file
 Opening a file
 Reading data from file
 Writing data into file
 Closing a File
20. How can you restore a redirected standard streams?
C library functions named dup() and fdopen(), you can restore a standard stream such
as stdout to its original state. The dup() function duplicates a file handle. You can use the
dup() function to save the file handle corresponding to the stdout standard stream.
The fdopen() function opens a stream that has been duplicated with the dup() function.
21. Why files are needed? (May 19)
 When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them
all. However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.
 You can easily move your data from one computer to another without any changes.

SINCET - CSE II
UNIT-V / PART-B
1. Write a program that will receive a filename and a line of text as command line
Arguments and write the text to the file.
2. Write a program to copy the contents of one file into another.
3. Write a program that appends one file at the end of another.
4. Write a program that compares 2 files and returns 0 if they are equal and 1 if they
are not.
5. Explain in detail various functions for sequential file manipulations and operations.
6. Write a complete C program for reading an employee file containing { emp
no,name,salary, address}. Create an output file containing the name of those
employees along with their salary and address. (Jan 14)
7. a) Write the C program to find the number of lines in a file.
b) Write the C program to print contents in reverse order of a file.
8. Write the C program to compare contents of two files.
9. Explain the types of file processing with necessary examples. (May 18)
10. Write the C coding for finding the average of number stored in sequential access
file. (May 18)
11. Write the case study of “How sequential Access file is differing from Random
Access file”. (May 18)
12. Write a C program to write all the members of an structures to a file fwrite( ).
Read thearray from the file and display on the screen. (May 18)
13. Explain in detail various operations that can be done on the file giving
suitable examples. (May 19)
14. Explain in detail random access in files along with the functions used for the same
in C. Give suitable examples. (May 19)

SINCET - CSE II

You might also like