Introduction to C Programming Concepts
Introduction to C Programming Concepts
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
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
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
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
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.
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.
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
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
10
SINCET - CSE II
Example
// Documentation
/*
File: sum.c
Author: Ramesh babu
Description: program to find sum.
*/
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:
Compiler
--> Assembly Code(.s)
Assembler
--> Object Code (.o / .obj)
Linker
--> Executable (.exe / [Link])
Loader
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.
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
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.
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
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.
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.
%f float 3.14
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
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
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:
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
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.
Increment Operator in C
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:
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:
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.
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.
* Dereference right-to-left
10 | Bitwise OR left-to-right
31
SINCET - CSE II
12 || Logical OR left-to-right
1. Formatted functions
2. Unformatted functions
Input\Output Function
Formatted Unformatted
input/ Output Input/output
function function
32
SINCET - CSE II
Formatted Input and Output Function
Input: scanf(), fscanf()
Output: printf(),fprint()
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()
syntax:
fscanf(FILE *fptr,“Control String”,&var1,&var2,….&var n);
Ex: printf(“Add=%d”,c);
fprintf()
fprintf() function is used to writes a formatted data in to a file.
syntax:
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()
variable name=getchar();
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)
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.
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);
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
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
Basic Structure:
Repeat for(i = 0;I<=5;i++)
{ Statement block;
}
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
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()
{
pg. 4
SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET
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:
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.
}
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 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:
}
getch();
pg. 10
SINCET - CSE II
COMPUTER PROGRAMMING C CONTRO STRUCTURE SINCET
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:-
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++;
}
}
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()…)
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.
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.
Actual parameters sends data to the formal Formal parameters receive data from the
parameters actual parameters.
SINCET - CSE II
COMPUTER PROGRAMMING C FUNCTIONS SINCET
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
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.
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.
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
[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);
}
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);
}
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.
1. malloc()
2. calloc()
3. realloc()
4. free()
Memory Allocation Process
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:
Example:
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.
Syntax:
p = (cast type*) calloc (n, byte-size);
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);
Example
Now the above statement increases the already allocated space to 15 bytes.
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( ) {
SINCET - CSE II
SINCET
data.i = 10;
data.f = 220.5;
strcpy( [Link], "C Programming");
return 0;
}
Output :
data.i : 10
data.f : 220.500000
[Link] : C Programming
#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.
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
"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.
Mode Description
"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.
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
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);
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);
Syntax:
fscanf(file_pointer, "format string", &var1, &var2, &var3….. &varn);
v1, v2, v3 refer to variables whose values are read from the disk.
"format string" represents the conversion specification.
Example:
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:
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);
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(); }
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);
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");
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.
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);
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
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)
SINCET - CSE II
Define putchar() :
Single character can be displayed using the function putchar().
The function putchar() stands for “putchar”and uses an
argument.
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.
PART B
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
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.
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 * )
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));
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