Computer Programming Coursefile (Updated)
Computer Programming Coursefile (Updated)
It is a high speed electronic device that accepts and stores input data and instructions, processes the
data and produces the desired output.
Input Output
(raw data / Instructions) (Information i.e. processed data)
COMPUTER SYSTEMS
COMPUTER SYSTEM
* It is made up of 2 major components
* They are :
1) Hardware
2) Software
HARDWARESOFTWARE
Computer Hardware :
ALU CU
Primary Memory
Secondary Memory
Computer Programming course file
Input Devices
These are used to enter data and programs into the computer
These are for man to machine communication
egs: Keyboard, mouse, scanner, touch screen, audio input.
Output Devices
These are used to get the desired output from the computer
These are for machine to man communication
egs: Printer, Monitor, Speakers
If the output is shown on monitor then it is called Soft copy
If the output is printed on a paper using printer then it is called hard copy
CPU (Central Processing Unit)
It is responsible for processing the instructions
It consists of 3 parts
1) ALU Arithmetic & Logic Unit
2) CU- Control Unit
3) Memory
ALU performs arithmetic operations like addition,subtraction,multiplication,division and
logical operations like comparisons among data
CU is responsible for movement of data inside the system
Memory is used for storage of data and programs. It is divided into 2
1) Primary Memory / Main Memory
2) Secondary Memory / Auxiliary Memory
1) Primary Memory
It is also called main memory
Data is stored temporarily i.e. data gets erased when computers is turned off
Eg: RAM
2) Secondary Memory
It is also called as auxiliary memory
Data is stored permanently so that user can reuse the data even after power loss.
Eg: Hard disk, CD, DVD, Floppy etc.
Computer Programming course file
Hardw
are
1. System Software
They constitute set of programs that manage the hardware resources of a computer
It is divided into 3 classes
System Software
Operating
SystemSystem
Support System Development
Operating System
It acts as an interface between the user and the hardware
Computer Programming course file
It makes the system to operate in an efficient manner
Egs: MS DOS, Windows, UNIX, LINUX, etc.
System Support
They provide some utilities and other operating services
eg: Sort utilities, disk formatting utilities, Security monitors
System Development
It includes
a) Language translators Used for converting programs into machine language
b) Debuggers for error free programs
c) CASE tools Computer Assisted Software Engineering Tools
2. Application Software
It contains programs for performing tasks
ItApplication
is divided intoSoftware
2 classes
general
application
purpose specific
Computer System
Peripherals CPU
System Software Application Software
o/p i/p
devices
devices
Operating System System SupportGeneral PurposeApplication Specific
System Development
Computer Programming course file
COMPUTER ENVIRONMENTS
In early days, there was only one environment i.e. the mainframe computer. It occupies much
space and consumed large amount of power.
With the invention of transistor and IC (Integrated Circuits) technology, mini computers were
introduced in which many components are fused together.
After invention of microprocessor technology, the environment changed resulting in mini-
computers and personal computers
The computing environments are classified into 4 types. They are
1) Personal computing environment
2) Time sharing environment
3) Client server environment
4) Distributed computing environment
1) Personal computing environment
In a personal computer, all the basic elements of the CPU are combined into the
microprocessor and all the hardware components are tied together.
The whole computer can be used by the user to perform his task independently
Advantage :
Computer is busy always reducing CPU idle time
Disadvantage
Response becomes slow as the number of users connected to the central computer increases
Terminals
Fig : Time-sharing environment
3) Client Server environment
This environment splits the computing function between a central computer and user
computer
Users are given personal computer (PCs) on workstations so that some of computation
responsibility can be moved form central computer and assigned to the workstation
Users workstations (or) micro computers are called as Clients
The powerful central mainframe (or) micro computer is known as Server
Computer Programming course file
Advantages
- Response time is faster
- Users are more productive
Disadvantage :
Writing and reading programs in machine language is very difficult
Machine instructions are difficult to remember
2) Symbolic Languages
It is also called as assembly language
An assembly program contains Mnemonics
Mnemonic means information can be memorized easily and is generally in the form of
abbreviations.
Advantage :
Easy to read and write programs in assembly language when compared to machine language
Computer Programming course file
Mnemonics are easy to remember
Disadvantage :
Assembly programs are machine dependent
Execution is slow since it needs conversion into machine language
Assembler is used to convert assembly language program into machine language.
Assembler
Assembly language program Machine Language code
3) High level languages
A set of languages which are very close to our native languages are called high-level
languages.
High level languages have control structures, I/o facilities, hardware independence
eg: FORTRAN, COBOL, PASCAL, C, C++ etc..
Advantage :
i) Machine independence i.e. programs are Portable i.e. programs can be moved from one
system to another
ii) Easy to learn and understand
iii) Takes less time to write programs
Disadvantage :
High level language programs needs a translator for conversion into machine language
Compilers (or) Interpreters are used for converting high level language program into
machine language..
Compiler / Interpreter
High language program Machine Language code
Dos/Linux Commands
Computer Programming course file
C file
#include<stdio.h>
Programmer Text Editor Source file main ( )
{
-----
-----
-----
}
Computer Programming course file
Preprocessor
Source File translation unit
B) Translator
It does the actual work of converting the program into machine language
It reads the translation unit and results in object module i.e., code in machine language
But it is not yet executable because it does not have the C and other functions included.
Translator
Translation unit Object Module .obj file
00110 100
10101 010
3) Linking programs
Linker assembles input /output functions, mathematical library functions and some of the
functions that are part of source program into final executable program
It is called as executable file that it is ready for execution .exe file
1011001100
Linker 110111011
Object file executable file 1100101010
4) Executing Programs
Loader is the software that gets the program that is ready for execution into the memory
When everything is loaded, the program takes control and the Runner begins its execution.
In the process of execution, the program reads the data from the user, processes the data and
prepares the output
Computer Programming course file
3) Design
It involves designing algorithms, flowcharts (or) GUIs (Graphical User Interfaces)
Computer Programming course file
Designing the algorithm is to develop a list of steps called algorithm to solve the problem
and then verify that the algorithm solves the problem intended.
Top down design is followed i.e. list the major steps (or) sub problems that need to be
solved
Flow charts are used to get the pictorial representation of the algorithm.
Algorithm for a programming problem consists of at least the following sub problems
1. Get the data
2. Perform the computations
3. Display the results
4) Coding / Implementation
This step involves writing algorithm as a program by selecting any one of the high level
languages that is suitable for the problem.
Each step of the algorithm is converted into one (or) more statements in a programming
language.
5) Testing
Checking / verifying whether the completed program works as desired is called Testing
Running the program several times using different sets of data verifies whether a program
works correctly for every situation provided in the algorithm.
After testing, the program must be free from the following errors.
a) Syntax errors
b) Logical errors
c) Run-time errors
6) Maintenance
It involves modifying a program to remove previously undetected errors and to keep it
up-to-date as government regulations (or) company polices change.
System
Many organizations
requirements maintains a program for some period of time i.e. 5 years
Analysis
Design
Coding
Testing
Maintenance
Computer Programming course file
r1 = -b + b 4ac / 2a
2
Procedure :
r2 = -b - b 2 4ac / 2a
3) Design
Algorithm
1. start
2. Read a,b,c values
3. Compute D=b2-4ac
4. if D>0 then
a) r1 = -b+ b 2 4ac / 2a
b) r2 = -b- b 4ac / 2a
2
Computer Programming course file
5. else if D= 0 then
a) compute r1 = -b/2a
r2=-b/2a
b) print r1,r2 values
6. else if d<0 then print roots are imaginary
7. Stop
Flowchart
Start
Compute D b2-4ac
True False
IS
D>0?
Compute
r1 -b+sqrt(D)/ 2a
r2 -b- sqrt(D)/ 2a False True
Is
D==0?
Compute
Prints roots are imaging r1 -b/2a
r2 -b/2a
Stop
Computer Programming course file
4. Implementation
C-code
# include<stdio.h>
# include<conio.h>
# include<math.h>
main ( )
{
float a,b,c,r1,r2,D;
clrscr ( );
printf (enter a,b,c values);
scanf ( %f %f %f, &a, &b, &c);
D= b*b 4*a*c;
if (D>0)
{
r1 = -b+sqrt (D) / (2*a);
r2 = -b-sqrt (D) / (2*a);
printf (Roots are real and are %f %f, r1, r2);
}
else if (D= =0)
{
r1 = -b/(2*a);
r2 = -b/(2*a);
printf (Roots are equal and are %f %f, r1, r2);
}
else
printf(Roots are imaginary);
getch ( );
}
5) Testing
Case 1: Enter a,b,c values : 1 4 3
r1 = -1
r2 = -3
Case 2: Enter a,b,c values : 1 2 1
r1 = -1
r2 = -1
Computer Programming course file
Case 3: Enter a,b,c values : 1 4 1
Roots are imaginary
Properties of an Algorithm
An algorithm must posses the following 5 properties. They are
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
1. Input : An algorithm must have zero (or) more number of inputs
2. Output: Algorithm must produce one (or) more number of outputs
3. Finiteness : An algorithm must terminate in countable number of steps
4. Definiteness: Each step of the algorithm must be stated clearly
5. Effectiveness: Each step of the algorithm must be easily convertible into program statements
Example
Algorithm for finding the average of 3 numbers
1. start
2. Read 3 numbers a,b,c
3. Compute sum = a+b+c
4. compute avg = sum/3
Computer Programming course file
5. Print avg value
6. Stop
oval
Input / output Input/output of data
Parallelogram
Rectangle
Desicion box Decision operations that
determine which of the
alternative paths to be followed
Diamond
Computer Programming course file
Connector Used to connect different parts
of flowchart
Circle
Flow Joins 2 symbols and also
represents flow of execution
Arrows
Pre defined process Modules (or)subroutines
specified else where
Pentagon
For loop symbol Shows initialization, condition
and incrementation of loop
variable.
Hexagon
Document Shows the data that is ready for
printout
Printout
Example
Flowchart for finding the average of 5 numbers
Start
Stop
Computer Programming course file
Computer Programming course file
Example:
/* Author : Ramu
Aim : Program for finding circumference of circle*/
#include<stdio.h>
#include<conio.h>
#define PI 3.1415
main ( )
{
float c, r;
clrscr ( );
Computer Programming course file
printf (enter radius of circle);
scanf (%f, &r);
c = 2 * PI * r;
printf (Circumference = %f, c);
getch ( );
}
C LANGUAGE ELEMENTS
C program contains several elements which are present in structure of C program. They are
1) Comment lines
2) Preprocessor directives
3) Variable declaration & data types
4) Executable statements
1. Comment lines
In C, comment lines are placed in /* */
Single line and multiple lines are enclosed in /* and */
Comment lines are ignored by the compiler
The documentation section is enclosed in comment lines
Documentation section consists of a set of comment lines giving the name of the program, the
author and other details, which the programmer would like to use later.
2. Preprocessor directives
It consists of a) link section
b) Definition Section
The link section provides instructions to the compiler to link functions from the system
library
eg : #include < stdio.h>
The definition section defines all symbolic constants
eg : #define PI 3.1415
Preprocessor directive must start with # (hash) symbol.
Computer Programming course file
1. real constant :
It must have at least one digit.
It must have a decimal point which may be positive or negative.
Use of blank space and comma is not allowed between real constants.
Example: +194.143, -416.41
2. integer constant :
It must have at least one digit.
It should not contain a decimal place.
It can be positive or negative.
Computer Programming course file
Use of blank space and comma is not allowed between real constants.
Example: 1990, 194, -394
3. character constant :
It is a single alphabet or a digit or a special symbol enclosed in a single quote.
Maximum length of a character constant is 1.
Example: 'T', '9', '$'
4. string constant :
It is collection of characters enclosed in double quotes.
It may contain letters, digits, special characters and blank space.
Example: "Hello"
Integral Type
Integer character
Signed Unsigned signed char
int unsigned int unsigned char
short int unsigned short int
long int unsigned long int
Variable declaration
Syntax:
Datatype v1,v2, vn;
Where v1, v2,...vn are names of variables
eg: int sum;
float a,b;
Variable can be declared in 2 ways
1. local declaration
2. global declaration
local declaration is declaring a variable inside the main block and its value is available within that
block
global declaration is declaring a variable outside the main block and its value is available through
out the program.
Eg :
int a, b; /* global declaration*/
main ( )
{
int c; /* local declaration*/
- - -
- - -
}
Computer Programming course file
EXECUTABLE STATEMENTS:
A C program contains executable statements
The C compiler translates the executable statements into machine language
The machine language versions of these statements are executed by the compiler when a user
runs program
Types
1) Input output statements
2) Assignment statements
1. Input output statements
Storing a value into memory is called input operation.
After executing the computations, the results are stored in memory and the results can be
displayed to the user by output operation
All input / output operations in C are performed using input / output functions
The most common I/o functions are supplied as part of the C standard I/O library through
the preprocessor directive # include<stdio.h>
Most commonly used I/o functions are
a) printf ( )
b) scanf ( )
a) printf ( ) function:
Syntax:
printf(format string, print list);
e.g.: printf (average of 3 numbers = %f,avg);
* The printf ( ) function displays the value of its format string after substituting the values of
the expressions in the print list.
Computer Programming course file
* It also replaces the escape sequences such as \n by their meanings.
b) scanf ( ) function
Syntax:
scanf (format string, input list);
e.g.: scanf (%d %f, &a, &b);
The scanf ( ) function copies into memory data typed at the keyboard by the program user
during program execution.
The input list must be preceded by ampersand ( &)
2) Assignment statements
The assignment statements stores a value (or) a computational result in a variable and is used
to perform most arithmetic operations in a program.
Syntax: variable=expression
e.g.:
1. c = a+b;
2. avg = sum/3;
3. r1 = (b*b 4 * a*c);
The variable before the assignment operator is assigned the value of the expression after it.
The previous value of variable is destroyed
Computer Programming course file
Program: Output
30
main ( )
10
{
200
int a= 20, b = 10;
2
0
Computer Programming course file
printf ( %d, a+b);
printf ( %d, a-b);
printf ( %d, a*b);
printf ( %d, a/b);
printf ( %d, a%b);
}
2).Relational operators :
These are used for comparing two expressions.
The output of a relational expression is either true (1) (or) false (0)
Program
main ( ) Output
{ 1
int a= 10, b = 20; 1
printf ( %d, a<b); 0
printf ( %d, a<=b); 0
printf ( %d, a>b); 0
printf ( %d, a>=b); 1
printf ( %d, a = =b);
printf ( %d, a ! =b);
3. Logical Operators
These are used to combine 2 (or) more expressions logically
They are logical AND (&&) logical OR ( || ) and logical NOT (!)
Computer Programming course file
Logical AND ( && )
exp1 exp2 exp1&&exp2
T T T
T F F
F T F
F F F
Logical OR( || )
exp1 exp2 exp1||exp2
T T T
T F T
F T T
F F F
Program:
main ( )
{
int a= 10, b = 20, c= 30;
Output
printf ( %d, (a>b) && (a<c)); 0
printf ( %d, (a>b) | | (a<c)); 1
printf ( %d, ! (a>b)); 1
}
4. Assignment operators
It is used to assign a value to a variable
Types
1) simple assignment
Program:
main ( ) Output
10
{ int a= 10,;
20
printf ( %d, a);
printf ( %d, a+ =10);
}
5. Increment and decrement operator:
a) Increment operator (++):
It is used to increment the value of a variable by 1
2 types : i) pre increment
ii) post increment
increment operator is placed before the operand in preincrement and the value is first
incremented and then operation is performed on it.
eg: z = ++a; a= a+1
z=a
increment operator is placed after the operand in post increment and the value is incremented
after the operation is performed
eg: z = a++; z=a
a= a+1
Program main ( )
{
main ( ) int a= 10, z;
z= a++;
{ printf (z= %d, z);
printf (a=%d, a);
int a= 10, z; } Output
z= ++a Output z=10
z=11 a = 11
printf (z= %d, z); a =11
b) Decrement operator : (- -)
It is used to decrement the values of a variable by 1
2 types : i) pre decrement
Computer Programming course file
ii) post decrement
decrement operator is placed before the operand in predecrement and the value is first
decremented and then operation is performed on it.
eg: z = - - a; a= a-1
z=a
decrement operator is placed after the operand in post decrement and the value is
decremented after the operation is performed
eg: z = a--; z=a
a= a-1
Program:
main ( )
main ( ) {
{ int a= 10, z;
z= a--;
int a= 10, z; printf (z= %d, z);
printf (a=%d, a);
z= --a } Output
Output z=10
printf (z= %d, z); z=9 a=9
a =9
printf ( a=%d, a);
}
6. Bitwise Operator
Unlike other operators, bitwise operators operate on bits (i.e. on binary values of on operand)
Operator Description
a&b = 8 a | b = 14
a^b
8 4 2 1
a =12 1 1 0 0
b =10 1 0 1 0
a ^b 0 1 1 0
a^b=6
Program
main ( )
{
int a= 12, b = 10; Output
printf ( %d, a&b); 8
}
Left Shift
If the value of a variable is left shifted one time, then its value gets doubled
eg: a = 10 then a<<1 = 20
32 16 8 4 2 1
1 0 1 0 a=10
a<<1 = 20
Computer Programming course file
Right shift
If the value of a variable is right shifted one time, then its value becomes half the original value
eg: a = 10 then a>>1 = 5
8 4 2 1
1 0 1 0 a=10
1 0 1 a>>1 0 Discard it
a>>1 = 5
Ones complement
If converts all ones to zeros and zeros to ones
Eg: a = 5 then ~a=2 [only if 4 bits are considered]
8 4 2 1
1 0 1 a=5
0 1 0 ~a
~a = 2
Program
main ( )
{
int a= 20, b = 10,c=10; Output
printf ( %d, a<<1); 40
}
Signed
1s complement = - [ give no +1]
Eg : ~10 = - [10+1] = -11
~-10 = - [-10+1] = 9
unsigned
1s complement = [65535 given no]
7. Conditional operator (? :)
It is also called ternary operator
Syntax:
exp1 ? exp2 : exp3
Computer Programming course file
if exp1 is true epx2 is evaluated, otherwise exp3 is evaluated
it can also be represented in if else form
if (exp1)
exp2;
else
exp3;
Program
main ( )
{ int z;
z = (5>3) ? 1:0; Output
printf (%d,z); 1
}
8) special operations
Some of the special operations are coma, ampersand(&), size of operators.
a) coma: ( , )
It is used as separator for variables
eg; a=10, b=20
b) Address:(&)
It is used to get the address of a variables.
C) Size of ( ) :
It is used to get the size of a data type of a variable in bytes.
Program:
main ( )
{
int a=10;
float b=20 ;
printf ( a= %d b=%f, a,b );
printf ( Adderss of a =%u &a ) ;
printf ( Adderss of b =%u &b ) ;
printf (Size of a = %d , sizeof (a) ) ;
printf ( Size of b = %d . sizeof (b) ) ;
} a b
Out Put : 10 20.00
a=10 b=20.00 1234 5678
Adderss of a =1 2 3 4
Computer Programming course file
Adderss of b = 5 6 7 8 Only for this example
Size of a = 2 bytes Size of b = 4 bytes
EXPRESSIONS
Def: An expression is a combination of operators and operands which reduces to a single
value
An operand is a data item on which an operation is performed.
An operator indicates an operation to be performed on data
eg; z = 3+2*1
z=5
Types Expression
1. Primary expressions
The operand in the primary expression can be a name, a constant or any parenthesized expression
E.g.: c = a+ (5*b);
2. Postifix expressions:
The operator will be after the operands in a postfix expression
Eg:
z=a++ ===> z= a
a = a+1
3. Prefix expressions
The operator is before the operand in a prefix expression.
Eg: z=++a ===> a = a+1
z= a
4. unary expression:
It contains one operator and one operand
eg: a++, --b
5. Binary expression
It contains 2 operands and one operator
Eg: a=b, c*d
6. Ternary expression
Computer Programming course file
It contains 3 operands and one operator
Eg ; Exp1? Exp2 :Exp3
If Exp1 is true ,Exp2 is executed. otherwise Exp3 is executed.
Primary Expression
() [] . -> expr++ expr-- left-to-right
Operators
+-
>> <<
== !=
&
&&
Computer Programming course file
||
Comma , left-to-right
Expressions are evaluated by the C compiler based on precedence and associativity rules.
If an expression contains different priority operators then precedence rules are considered.
C = 30 - 10 * 2
1
20
2
10
3
Here, 10*2 is evaluated first since * has more priority than - and =
If an expression contains same priority then assoiciativity rules are considered i.e. left right
(or right to left)
eg: z= a*b/c
z = 40 * 20 / 10 Here * and / have same priority so, left to right
associativity is considered
1
800
2
z
80
3
Eg: x =5 *4 + 8/2 x = 5 * 4 + 8 / 2
1 2
x = 24 Parenthesis has highest priority and comma has least priority among operators
Computer Programming course file
Type Conversions
Converting one data type into another is the concept of type conversion
2 types
1. Implicit type conversion
2. Explicit type conversion
Implicit type conversion is automatically done by the compiler by converting smaller data
type into a larger data type.
Eg: int i,x;
float f;
double d;
long int l;
x = l / i + i - f - d
long float
long float
float
`
Float
Double
int double
int float
Computer Programming course file
float
int
Here, the resultant of a+b is converted into into explicitty and then assigned to c
Program:
main ( )
{
Output
printf (%d, 5/2); 2
printf (%f, 5.5/2); 2.75
printf (%f, (float) 5/2); 2.5
}
Flow chart
Condition?
True False
Statement (s)
2. if else statement
If else statement takes care of true as well as false conditions
true block is executed when the condition is true and false block (or) else block is
executed when the condition is false.
Syntax:
if (condition)
{
True block statement(s)
}
else
{
False block statement(s)
}
Flow chart
Condition?
True False
Program
/* checking for even (or) odd number */
main ( )
{
int n;
printf (enter a number);
scanf (%d, &n);
if (n%2 ==0)
printf (%d is even number, n);
Computer Programming course file
else
printf( %d is odd number, n);
}
Output
1) enter a number 10 2) enter a number 5
10 is even number 5 is odd number
3. Nested if - else statement
A nested if is an if statement that is the object of either if (or) an else
if is placed inside another if (or) else
Syntax:
if (condition1)
{
if (condition2)
stmt1;
else
stmt2;
}
else
{
if (condition3)
stmt3;
else
stmt4;
}
Condition1
Condition2 Condition3
True False True False
FlowStmt1
chart Stmt2 Stmt3 Stmt4
True False
Computer Programming course file
else
{
if (b>c)
printf (%d is largest, b);
else
printf (%d is largest, c);
}
}
Output
enter 3 numbers = 10 20 30
30 is largest
Computer Programming course file
4. Else if ladder
This is the most general way of writing a multi-way decision
Syntax
if (condition1)
stmt1;
else if (condition2)
stmt2;
-----
else if (condition n)
stmtn
else
stmt x
flow chart
Condition1?
True False
Condition2?
True False
Stmt1
------
Stmt2
Condition n?
True False
Stmt n Stmt x
Switch (expression)
Exp =value2
Stmt2
|
|
default Stmt-x
Program
main ( )
{
int n;
printf (enter a numbers);
scanf (%d, &n);
switch (n)
{
case 0 : printf (zero)
Computer Programming course file
break;
case 1 : printf (one);
break;
default : printf (wrong choice);
}
}
Output
enter a number
1
one
False
Initialization Increment/
condition decrement
True
Program
main( )
{ Output
int k; 1
{ 3
printf (%d,k); 4
} 5
}
2) while loop
Syntax
while (condition)
{
Computer Programming course file
body of the loop
}
Flow chart
initialization
Is expression?
False
True
Incr/ dec
Program
main( )
{
int k; Output
k = 1; 1
while (k< = 5) 2
{
printf (%d,k); 3
k++; 4
}
} 5
3) do-while loop
Syntax
Initialization
do
Computer Programming course file
{
body of the loop
inc/ dec
} while (condition);
Flow chart
initialization
Incr/ dec
Is expression?
True
Flase
Program
main( )
{ Output
int k; 1
k = 1; 2
do 3
{ 4
printf (%d,k); 5
k++;
} while (k == 5);
}
Nested for loops
Computer Programming course file
In nested for loops one (or) more for statements are included in the body of the loop
The number of iterations in this type of structure will be equal to number of iterations in the
outer loop multiplied by the number of iterations in the inner loop
Program
main( )
{
int i,j; Output
for (i=1; i<=2; i++) 1
{ 2
for (j=1;j<=2; j++)
{ 2
printf (%d, i*j); 4
}
} 3
} 6
Execution i*j
i=1 j=1 1
j=2 2
i=2 j=1 2
j=2 4
i=3 j=1 3
j=2 6
Other related statements
1) break
2) continue
3) goto
Program
main( )
{ int i; Output
for (i=1; i<=5; i++) 1
{ 2
if (i= =3)
break;
}
}
2) continue
It is a keyword used for continuing the next iteration of the loop
It skips the statements after the continue statement
It is used with for, while and do-while
Syntax
{
Stmt1;
Stmt2;
continue;
Stmt3;
Stmt4;
}
Program
main( ) Output
1
{
3
int i;
4
for (i=1; i<=5; i++)
5
{
if (i= =2)
continue,
printf(%d, i)
}
}
Computer Programming course file
3) goto
It is used to after the normal sequence of program execution by transferring the control to
some other part of program
Program
main( ) Output
Hello
{
you
printf(Hello);
goto l1;
printf(How are);
l1: printf(you);
}
Computer Programming course file
ARRAYS
Array: An array is a group of related data items that share a comman name
(or) Homogenous collection of data items that share a comman name.
A particular value in an array is identified using its index number or subscript
Advantage
The ability to use a single name to represent a collection of items and to refer to an item by
specifying the item number enables the user to develop concise and efficient programs
Declaring for declaring array
Syntax : for declaring array:
Eg:
1. float height [50]
This declares height to be an array containing 50 float elements
2. int group[10]
This declares the group as an array to contain a maximum of 10 integer constants
Computer Programming course file
Individual elements are identified using array subscripts
While complete set of values are referred to as an array, individual values are called
elements
First element is identified by subscript zero i.e., a[0] represents first element of the array.
If there are n elements in array then subscripts range from 0 to n-1
Initialization
To store values into an array it can be done as follows.
a[0] = 10; 10 a[0]
a[1] = 20; 20 a[1]
a[2] = 30; 30 a[2]
a[3] = 40; 40 a[3]
a[4] = 50; 50 a[4]
An array can also be initialized at the time of declaration as follows
int a[5] = { 10,20,30,40,50};
Computer Programming course file
Program for compile time initialization and sequential access using for loop
main ( ) storing
{
int a[5] = a[0] 10 {10,20,30,40,50};
a[1] 20
int i;
a[2] 30
clrscr ( ); a[3] 40
printf (elements a[4] 50 of the array are);
for ( i=0; i<5; i++)
printf (%d, a[i]);
Computer Programming course file
getch ( );
}
accessing
Output: Elements of the array are
10 20 30 40 50
Program for runtime initialization and sequential access using for loop
main ( )
{
int a[5],i;
clrscr ( );
printf (enter 5 elements);
for ( i=0; i<5; i++)
Storing / assigning values to element of an array
scanf(%d, &a[i]);
printf(elements of the array are);
for (i=0; i<5; i++)
Accessing the elements of the aray
printf(%d , a[i]);
getch ( );
}
output
enter 5 elements 10 20 30 40 50
elements of the array are : 10 20 30 40 50
Note :
The output of compile time initialized program will not change during different runs of the program
The output of run time initialized program will change for different runs because user is given a
chance of accepting different values during execution.
qty Variable
179 value
5000 Address
Declaring a pointer
int *p;
It means p is a pointer variable that holds the address of another integer variable.
Initialization of a pointer
Address operator (&) is used to initialize a pointer variable.
Eg: int qty = 175;
int *p; VariablevalueAddress
qty1755000
p= &qty; p50005048
Computer Programming course file
p = &qty;
n = *p;
h) p1++
i) p2
j) sum + = *p2
j) p1 > p2
k) p1 = = p2
l) p1 ! = p2 Note : Comparisons can be used meaningfully in handling arrays and strings
base address
a= &a[0]=1000
if p is declared as integer pointer, then the array a can be pointed by the following assignment
p = a;
(or) p = &a[0];
Every value of a can be accessed by using p++ to move from one element to another. When
a pointer is incremented, its value is increased by the size of the datatype that it points to.
This length is called the scale factor
The relationship between p and a is shown below
P = &a[0] = 1000
P+1 = &a[1] = 1002
P+2 = &a[2] = 1004
P+3 = &a[3] = 1006
P+4 = &a[4] = 1008
Address of an element is calculated using its index and the scale factor of the datatype.
For eg:
instead of using array indexing, pointers can be used to access array elements.
*(p+3) gives the value of a[3]
a[i] = *(p+i)
Program
main ( )
{
int a[5];
int *p,i;
clrscr ( );
printf (Enter 5 lements);
for (i=0; i<5; i++)
scanf (%d, &a[i]);
p = &a[0];
printf (Elements of the array are);
for (i=0; i<5; i++)
printf(%d, *(p+i));
getch( );
}
Output
Enter 5 elements : 10 20 30 40 50
Elements of the array are : 10 20 30 40 50
Pointers and two dimensional arrays :
Memory allocation for a 2-dimensional array is as follows:
int a[3] [3] = {1,2,3,4,5,6,7,8,9};
a[0] [0] a[0] [1] a[0] [2] a[1] [0] a[1] [1] a[1] [2] a[2] [0] a[2] [1] a[2] [2]
1 2 3 4 5 6 7 8 9
1234 1236 1238 1240 1242 1244 1246 1248 1250
1st row 2nd row 3rd row
base address = 1234 = &a[0] [0]
Initialization
a[0] a[1] a[2] & is used for initialization
10 20 30
1234 1236 1238 Eg : int a[3] = {10,20,30};
int *p[3], i;
p[0] p[1] p[2]
1234 1236 1238
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i]; p[i] = a+i;
a
Accessing
Indirection operator (*) is used for accessing
Eg: for (i=0, i<3; i++)
printf (%d, *p[i]);
Program
main ( )
{
int a[3] = {10,20,30};
int *p[3],i;
for (i=0; i<3; i++)
p[i] = &a[i];
printf (elements of the array are)
for (i=0; i<3; i++)
Computer Programming course file
printf (%d \t, *p[i]);
getch();
}
Accessing :
Indirection operator (*) is used for accessing
Program
main ( )
{
int a = 10;
int *p;
int **q
p = &a;
q = &p;
printf(a =%d,a);
printf(a value through pointer = %d, *p);
printf(a value through pointer to pointer = %d, **q);
}
Output
a=10
a value through pointer = 10
a value through pointer to pointer = 10
Void pointers :
Computer Programming course file
It is a pointer that can hold the address of any datatype variable (or) can point to any datatype
variable
Declaration
void *pointername;
eg : void *vp;
Accessing
Type cast operator is used for accessing the value of a variable through its pointer.
Syntax:
* ( (type cast) void pointer)
Eg :
int i=10;
void *vp;
vp = &i;
printf (%d, * ((int*) vp));
type cast
Program
main ( )
{
int i =10;
float f = 5.34;
void *vp;
clrscr ( );
vp = &i;
printf (i = %d, * ((int*)vp));
vp = &f;
printf ( f = %f, * ((float*) vp));
getch ( );
}
Output
i = 10
f = 5.34
Memory allocation
Static Dynamic
(at compile (at
time)
run time)
If memory is allocated at compile time, it cannot be changed during execution. There will be
a problem of either insufficiency or else wastage of memory.
The solution is to create memory dynamically i.e. as per the requirement of the user during
execution of program.
The standard library functions used for dynamic memory management are:
1) malloc ( )
2) calloc ( )
3) realloc ( )
4) free ( )
1) malloc ( );
This function is used for allocating a block of memory in bytes at runtime.
It returns a void pointer, which points to the base address of allocated memory
Syntax :
void *malloc (size in bytes)
Eg:
1) int *ptr;
ptr = (int * ) malloc (1000);
2) int *ptr;
ptr = (int * ) malloc (n * sizeof (int));
Note : if the memory is not free, it returns NULL
2) Calloc ( ):
This function is used for allocating continuous blocks of memory at run time.
This is especially designed for arrays
It returns a void pointer which points to the base address of the allocated memory
Syntax : void *calloc ( numbers of elements, size in bytes)
Eg: 1) int *ptr;
ptr = (int * ) calloc (500,2);
Computer Programming course file
Here, 500 blocks of memory each of size 2 bytes will be allocated continuously. Total memory
allocated = 1000 bytes. ptr
2) int *ptr;
500 x 2
ptr = (int * ) calloc (n, sizeof (int));
= 1000
bytes
3. realloc ( ) :
It is used for reallocating already allocated memory
It can either reduce (or) extend the allocated memory
It returns a void pointer that points to the base address of reallocated memory
Syntax
void *realloc (pointer, newsize);
Eg:
int *ptr;
ptr = (int * ) malloc (1000);
---
---
---
ptr = (int * ) realloc (ptr, 500);
---
---
ptr = (int * ) realloc (ptr, 1500);
4. free ( ):
This function frees ( or) deallocates previously allocated memory space..
With dynamic runtime allocation, it is our responsibility to release the space when it is not
required for effective usage of memory.
Syntax
void *free (pointer);
Eg: int *ptr;
ptr = (int *) malloc (1000);
---
---
---
free (ptr);
scanf ( ) printf ( )
gets ( ) puts ( )
program : using printf ( ) and scanf ( ) for reading & writing strings.
Computer Programming course file
main ( )
{
char a[30];
printf(enter your name);
scanf ( %s,a);
printf (your name is %s,a);
getch ( );
}
Output
1. Enter your name : Ramu 2. Enter your name : Ram kumar
Your name is Ramu Your name is Ram
Note :
1. & is not used for accepting string because name of the string itself specifies the base address
of the string
2. space is not accepted as a character by scanf( )
3. \0 is automatically placed by the compiler at the end.
Program : Using gets ( ) and puts ( ) for reading and writing strings.
main ( )
{
char a[30];
printf ( enter your name);
gets (a);
printf(Your name is);
puts (a);
}
Out put
1. Enter your Name : Ramu 2) Enter your name : Ram kumar
Your name is ramu Your name is Ram kumar
Note : Space is also accepted as a character by gets ( )
Output
Computer Programming course file
Enter a string : Hello
Copied string = Hel
s1
It is also used for J a n 1 0 2 0 1 0 \0 extracting substrings;
Eg: char result[10], s1[15] = Jan 10 2010;
strncpy (result, &s1[4], (2);
result[2] = \0 1 0 \o result
o/p :Result = 10
4) strcat ( ):
This is used for combining or concatenating two strings.
The length of the destination string must be greater than the source string
The resultant concatenated string will be in the source string.
Syntax:
strcat (Source String, Destination string);
program
#include <string.h>
main()
{
char a[50] = Hello;
char b[20] = Good Morning;
clrscr ( );
strcat (a,b);
printf(concatenated string = %s, a);
getch ( );
}
Output
Concatenated string = Hello Good Morning
5) strncat ( ):
This is used for combining or concatenating n characters of one string into another.
The length of the destination string must be greater than the source string
The resultant concatenated string will be in the source string.
Syntax:
Computer Programming course file
strncat (Source String, Destination string,n);
program
#include <string.h>
main ( )
{
char a [30] = Hello;
char b [20] = Good Morning;
clrscr ( );
strncat (a,b,4);
a [9] = \0;
printf(concatenated string = %s, a);
getch ( );
}
Output
Concatenated string = Hello Good.
String comparison
6) strcmp
This function compares 2 strings
It returns the ASCII difference of the first two non matching characters in both the strings.
Syntax
int strcmp (string1, string2);
If the difference is equal to zero string1 = string2
If the difference is positive string1> string2
If the difference is negative string1 <string2
eg:
1) char a[10]= there
t h e r e \0
char b[10] = their
strcmp (a,b);
t h e i r \0
Output: string1 >string2 r > i
Program
main ( )
{
char a[50] b [50];
int d;
clrscr( );
printf (enter 2 strings);
scanf (%s %s, a,b);
d = strcmp (a,b);
if (d==o)
printf(%s is equal to %s, a,b);
else if (d>0)
prinft(%s is greater than %s,a,b);
else if (d<0)
printf(%s is less than %s, a,b);
getch ( );
Computer Programming course file
}
7. strncmp ( )
This function is used for comparing first n characters of 2 strings
Syntax :
strncmp ( string1, string2, n)
Eg: char a[10] = the;
char b[10] = there
strncmp (a,b,3);
Output : Both strings are equal
8. strrev( )
The function is used for reversing a string
The reversed string will be stored in the same string
Syntax : strrev (string)
Program
main ( )
{
char a[50] ;
clrscr( );
printf (enter a string);
gets (a);
strrev (a);
printf(reversed string = %s,a)
getch ( );
}
Output : enter a string Hello
Reverstring = olleH
o n e \0 t W o \0 t h r e e \0
a [0] 1234
a [1] 1238
a [2] 1242
Array of pointers
Advantage :
Unlinke the two dimensional array of characters. In (array of strings), in array of pointers to
strings there is no fixed memory size for storage.
The strings occupy only as many bytes as required hence, there is no was tage of space.
Program
main ( )
{
char *a[5] = {one, two, three, four, five};
int i;
clrscr ( );
printf ( the strings are)
for (i=0; i<5; i++)
printf (%s, a[i]);
getch ( );
}
Output
The strings are : one two three four five
Converting functions
Function
tolower ( ) Converts an upper case alphabet to lower case
Program
#include <ctype.h>
main ( )
{
char a = D;
clrscr ( );
if ( isalpha (a))
printf ( %c is an alphabet,a);
else
printf (%c is not an alphabet,a);
getch ( );
Computer Programming course file
}
Output
D is an alphabet
02 01 2010
Computer Programming course file
- o/p
02/01/2010
%s
Program
Computer Programming course file
main ( )
{
char a[50];
int day = 02, mon = 01, yr = 2010;
crlscr( );
sprintf (a, %d/%d/%d, day, mon, yr);
prinft ( todays date =%s, s);
getch ( );
}
Output
Todays date is 02/01/2010.
Computer Programming course file
FUNCTIONS
Def : A function is a self contained block that carries out a specific well defined task.
Advantages
1. Reusability i.e. a function may be used by many other programs.
2. The length of the source program can be reduced.
3. It is easy to locate and isolate a faulty function.
4. It facilitates top-down modular programming.
Main Program
Function
Function1
2 Function 3 Function 4
The splitting of a problem into its related sub problems is analogous to the process of refining
an algorithm.
e.g. Performing arithmetic operations on 2 numbers
1. find sum
2. find difference
3. find product
4. find quotient
Refined algorithm for 1st step
1.1 take 2 numbers a, b
1.2 sum, c = a + b
1.3 print sum
Structure chart
Find Difference
Find Sum Find Product Find Quotient
Product =
Input 2
a*b Print Product
Numbes a, b
Computer Programming course file
Output
Enter 2 numbers 10 20
Sum = 30
Function definition
When the compiler encounters a function call, the control is transferred to the function
definition.
All the statements ,in the called function, are together called as function definition
Function header
The first line in the function definition is called function header.
Actual parameter
All the variables inside the function call are called actual parameters.
Formal parameters
All the variable inside the function header are called formal parameters
Program
#include<stdio.h>
#include<conio.h>
main ( )
{
int mul (int, int); function prototype
int a,b,c;
clrscr( );
printf (enter 2 numbers);
scanf(%d %d, &a, &b);
Computer Programming course file
c = mul (a,b); function call
printf(product =%d,c); Actual parameters
getch ( );
}
int mul (int a, int b) Formal parameters
{ function header
int c;
c = a *b; Function definition
return c;
}
Output
Enter 2 numbers: 10 20
Product = 200
4. Register variables
Keyword : register
Register variables values are stored in CPU registers rather than in memory where normal
variables are stored.
Registers are temporary storage units in CPU
They allow faster access time for register variables than normal variables
eg:
main ( )
{
register int i;
for (i=1; i< =5; i++)
printf (%d ,i);
}
Output
1 2 3 4 5
Computer Programming course file
Type qualifiers
Const
volatile restrict
1. Const
There are 3 types of constants
a) Literal constants
b) Defined constants
c) Memory constants
a) Literal constants
unnamed constants are used to specify data
eg:
a=b+5 Here 5 is literal constant
b) defined constants
Computer Programming course file
They use preprocessor command define with #
Eg: #define PI 3.1415
c) Memory constants
It uses C type qualifier const to indicate that the data cannot be changed
Syntax: const type identifier = value
eg:
const float pi = 3.1415
it is simply giving a literal a name
Program
#define PI 3.1415
main ( )
{
const float cpi = 3.14
printf (literal constant = %f,3.14);
printf (defined constant = %f, PI);
printf (memory constant = %f,cpi);
}
Output
Literal constant = 3.14
Defined constant = 3.1415
Memory constant = 3.14
2. volatile
volatile type qualifier is used to tell the compiler that a variable is shared
That is, a variable may be referenced and changed by other programs (or) entities if it is
declared as volatile
Eg: volatile int x;
3. restrict
This is used only with pointers
It indicates that the pointer is only the initial way to access the deferenced data
It provides more help to the compiler for optimization.
Eg;
int *ptr
int a= 0;
ptr = &a;
Computer Programming course file
____
____
____
*ptr+=4;
Cannot be replaced with
____
____ *ptr+=9
____
*ptr+=5;
Here the compiler cannot replace the 2stmts *ptr+=4 and *ptr+=5 by one statement *ptr+=9,
because it does not know if the variable a can be accessed directly (or) through other
pointers.
Same program fragment using restrict qualifier is as follows
Eg;
restrict int *ptr
int a= 0;
ptr = &a;
____
____
____
*ptr+=4;
Can be replaced with
____
____ *ptr+=9
*ptr+=5;
____
____
Here the compiler can replace the 2 statements by one statement, *ptr+=9 because it is sure
that variable cannot be accessed through any other resources.
Computer Programming course file
Eg:
#include <stdio.h>
Output
main ( )
Hello
{
printf (hello);
}
The definition of the function printf ( ) is present in <stdio.h>header file.
3. Compiler control directives
C pre processor offers a feature known as conditional compilation, which can be used to
switch ON (or) OFF a particular line (or) group of lines in a program.
Eg: #if, #else, #endif etc.
#define LINE 1
main ( )
{ Output
#ifdef LINE This is line number one
printf (this is line number one)
#else
printf(This is line number two)
#endif
}
Computer Programming course file
Program :
main ( )
Computer Programming course file
{
enum week {mon, tue, wed, thu, fri, sat, sun};
clrscr ( );
printf (Monday = %d, mon);
printf (Thursday = %d, thu);
printf (Sunday = %d, sun);
}
Output : Monday = 0
Thursday =3
Sunday =6
Structure variables
There are 3 ways of declaring structure variables
1) struct book
{
int pages;
char author[30];
float price;
}b;
2) struct
Note : Tagname can be ignored if the
{
variable is declared of the time of defining
int pages;
structure
char author[30];
float price;
}b;
3) struct book
{
int pages;
char author[30];
float price;
};
struct book b;
Computer Programming course file
program
union sample
{
int a;
float b;
char c;
}
main ( )
{
union sample s = {10, 20.5, A};
clrscr( );
printf(a=%d,s.a);
printf(b=%f,s.b);
printf(c=%c,s.c);
getch ( );
}
Output
a = garbage value Only the variable that is stored at last will
retain its value
b = garbage value
c=A
2) syntax; 2) syntax;
Struct tagname union tagname
{ {
datatype member1; datatype member1;
datatype member2; Datatype member2;
----- -----
----- -----
----- -----
}; };
3). Eg: 3). Eg:
struct sample union sample
{ {
int a; int a;
float b; float b;
cha c; cha c;
}; };
4. Keyword : struct 4. Keyword : union
5. Memory allocation 5. Memory allocation
a 2 bytes
4
b 4 bytes
1 byte bytes a
c
b
7 bytes
c
6. Memory allocated is the sum of sizes of all the 6. Memory allocated is the maximum size
datatypes in structure
allocated among all the datatypes in union
(Here, 7bytes)
(Here, 4bytes)
7. Memory is allocated for all the members of the 7. Only one member will be residing in the
structure differently memory at any particular instance/
Union of structures
A structure can be nested inside a union and it is called union of structures
It is also possible to create a union inside a structure
Program
struct x
{
int a;
float b;
Computer Programming course file
};
union z
{
struct x s;
};
main ( )
{
union z u;
clrscr ( );
u.s.a = 10;
u.s.b = 30.5;
printf(a=%d, u.s.a)
printf(b=%f, u.s.b);
getch ( );
}
Output
a= 10
b = 30.5
Syntax
datatype name : bit length;
The datatype can be either int (or) unsigned int (or) signed int.
Bit length specifies the number of bits
The largest value that can be stored is 2n 1, where n is bit length
NOTE :
1) Bit fields cannot be arrayed
2) scanf ( ) cannot be used to read values into bit fields
3) cannot use pointer to access the bit fields
4) Bit fields should be assigned values within the range of their size
Bit Length Range of values
1 0 to 1
2 0 to 3 (22-1)
3 0 to 7 (23-1)
n 0 to 2n-1
Eg:
1) struct pack
{
int count;
unsigned a : 2;
unsigned b : 3;
Computer Programming course file
};
Here, count will be in 2 bytes. a and b will be packed into the next word.
2) struct pack
{
unsigned a : 2;
int count;
unsigned b : 3;
};
Here, a will be in 2 bytes, count in 2 bytes and b in 2 bytes.
Note ;
1. Bit Fields are packed into words as they appear in the definition
2. All unsigned bit fields must be placed in order for effectively using the memory
Program
struct vehicle
{
unsigned type : 3; Note: Instead of 6 bytes only 2 bytes of memory
unsigned fuel : 2; will be allocated
unsigned model : 3;
};
main ( )
{
struct vehicle v;
v.type = 4;
v. fuel = 2;
v. model = 5;
printf (type of vehicle =%d, v.type);
printf (fuel =%d, v.fuel);
printf (model =%d, v.model);
}
FILE *fp;
fp = fopen (sample.txt, w);
a Old content
Current content
Output stream
printf ( )
I/0 functions:
1) high level I/o
These are easily understood by human beings
Advantage: portability.
2) Low level I/o
These are easily understood by computer
Advantages. Execution time is less
Disadvantage: Non protability
High level I/o Functions
1) fprintf ( ) - to write data into a file
2) fscanf ( ) - To read data from a file
3) putc ( ) - to write a character into a file
4) getc ( ) - to read a character from a file
5) putw ( ) - To write a number into a file
6) getw ( ) - To read number from a file
7) fputs ( ) - To write a string into a file
8) fgets ( ) - To read a string from a file
fprint ( ) & fscanf ( ) functions
1) fprint ( )
Syntax : fprintf (file pointer, control string, variable list)
Eg: FILE *fp;
fprintf (fp, %d%c, a,b);
2)fscanf ( )
Syntax : (file pointer, control string, & variable list)
Eg: FILE *fp;
fscanf (fp, %d%c, &a,&b);
Program for storing the details of an employee in a file and print the same
main ( )
{
FILE *fp;
Computer Programming course file
int eno;
char ename [30];
float sal;
clrscr ( );
fp =fopen (emp.txt, w);
printf (enter the details of eno, ename, sal);
scanf (%d%s%f, &eno, ename, &sal);
fprintf (fp, %d%s%f, eno, ename, sal);
fclose (fp);
fp = fopen (emp.txt, r);
fscanf (fp, %d%s%f, &eno, ename, &sal);
printf (employee no: = %d, eno);
printf (employee name = %s, ename);
printf (salary = %f, sal);
fclose (fp);
getch( );
}
Program for storing the details of 60 employers in a file and print the same
main ( )
{
FILE *fp;
int eno, i;
char ename [80];
float sal;
clrscr ( );
fp = fopen (emp1. txt, w);
for (i=1; i<60; i++)
{
printf (enter the eno, ename, sal of emp%d, i);
scanf (%d%s%f, &eno, ename, &sal);
fprint (fp, %d %s %f, eno, ename, sal);
}
fclose (fp);
fp = fopen (emp1.txt, r)
for (i=1; i<60; i++)
Computer Programming course file
{
fscanf(fp, %d %s %f, &eno, ename, &sal);
printf (details of employee %d are \n, i);
printf (eno = %d, ename = %s, sal = %f, eno, ename, sal);
}
fclose (fp);
getch ( );
}
Program :
main ( )
{
FILE *fp;
char ch;
Computer Programming course file
clrscr ( );
fp = fopen (characters.txt, w);
printf (enter text. press ctrl+z at the end);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp);
}
fclose (fp);
fp =open (characters. txt, r);
printf (file content is \n);
while ((ch = getc (fp))! = EOF)
{
putchar (ch);
}
fclose (fp);
getch ();
}
Output:
Enter text press ctrl+z at the end.
Hello how r u ^z
File Content is
Hello How r u
Program for copying the contents of one file into another file
main ( )
{
FILE *fp1, *fp2;
char ch;
clrscr ( );
fp1 = fopen (file1.txt, w);
Computer Programming course file
printf (enter text press ctrl+z at the end);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp1);
}
fclose (fp1);
fp1 =fopen (file1. txt, r);
fp2 =fopen (file2. txt, w);
while ((ch = getc (fp1))! = EOF)
{
putc(ch,fp2);
}
fclose (fp1);
fclose (fp2);
fp2 = fopen (file2.txt, r);
printf (File2 contents are);
while ((ch = getc(fp2))! = EOF)
putchar (ch);
fclose (fp2);
getch ();
}
Program for displaying the contents of a file
main ( )
{
FILE *fp;
char ch ;
clrscr ( );
fp = fopen (file1.txt,r);
if (fp = = NULL)
{
printf (File does not exist);
}
else
{
printf (file content is)
Computer Programming course file
while ((ch = getc(fp))! = EOF)
putchar (ch);
}
fclose (fp);
getch ( );
}
Program to merge two files into a third file. (the contents of file1, file2 are placed in file3)
main ( )
{
FILE *fp1, *fp2, *fp3;
char ch;
clrscr ( );
fp1 = fopen (file1.txt, w);
printf (enter text into file1);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp1);
}
fclose (fp1);
fp2 = fopen (file2.txt, r);
printf (enter text into file2);
while ((ch = getchar ( ))! = EOF)
putc(ch, fp2);
fclose (fp2);
fp1 =fopen (file1. txt, r);
fp2 =fopen (file2. txt, r);
fp3 =fopen (file3. txt, w);
while ((ch = getc (fp1))! = EOF)
put c(ch,fp3);
while ((ch = getc (fp2))! = EOF)
putc(ch,fp3);
fclose(fp1);
fclose (fp2);
fclose (fp3);
fp3 = fopen (file3.tx, r);
Computer Programming course file
printf (File3 contents is);
while ((ch = getc(fp3)! = EOF)
purchar (ch);
fclose (fp3);
getch ();
}
fput c ( ) and fgetc ( ) functions :
1) fputc( ) : It is used for writing a character in to a file .
Syntax :
fputc (char ch, FILE *fp);
Eg : FILE *fp;
char ch;
fputc (ch.fp);
2. fgetc( ) : This is used for reading a character from a file
Syntax :
fputc (char ch, FILE *fp);
Eg : FILE *fp;
char ch;
ch = fgetc(fp);
fgets ( ) and fputs ( ) functions :
1) fgets ( ) : It is used for reading a string from a file
Syntax :
fgets (string variable, No. of characters, File pointer);
Eg : FILE *fp;
char str [30];
fgets (str,30,fp);
2) fputs ( ) : It is used for writing a string into a file
Syntax :
fputs (string variable, file pointer);
Eg : FILE *fp;
char str[30];
fputs (str,fp);
File
Keyboard gets ( ) fputs ( )
Program :
main ( )
{
FILE *fp;
char str [30];
int i,n;
clrscr ( );
printf (enter no of strings);
scanf (%d, & n);
fp = fopen (strings.txt, w);
for (i=1; i<=n; i++)
{
printf (enter string %d,i);
gets (str);
fputs (str, fp);
}
fclose (fp);
fp = fopen (strings.txt, r);
for (i=1; i<=n; i++)
{
fgets (str, 30, fp);
printf (string %d =, i);
puts (str);
}
fclose (fp);
getch ( );
}
fread ( ) and fwrte ( ) functions
1. fread ( ) : It is used for reading entire record at a time.
Syntax : fread( & structure variable, size of (structure variable), no of records, file pointer);
Eg : struct emp
{
int eno:
Computer Programming course file
char ename [30];
float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp);
2. fwrite ( ) : It is used for writing an entire record at a time.
Syntax : fwrite( & structure variable , size of structure variable, no of records, file pointer);
Eg : struct emp
{
int eno:
char ename [30];
float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp);
write a program for storing the details of 60 students into a file and print the same using
fread ( ) and fwrite ( )?
struct student
{
int sno;
char sname [30];
float marks;
};
main ( )
{
struct student s[60];
int i;
FILE *fp;
clrscr ( );
fp = fopen (student1. txt, w);
for (i=0; i<60; i++)
{
printf (enter details of student %d, i+1);
scanf (%d%s%f. &s[i].sno,s[i].sname, &s[i].marks);
fwrite (&s[i], sizeof (s[i]), 1, fp);
Computer Programming course file
}
fclose (fp);
fp = fopen (student1. txt, r);
for (i=0; i<60; i++)
{
printf (details of student %d are, i+1);
fread (&s[i], sizeof (s[i]) ,1,fp);
printf(student number = %d, s[i]. sno.);
printf(student name = %s, s[i]. sname.);
printf(marks = %f, s[i]. marks);
}
fclose (fp)
getch( );
}
Program :
main ( )
{
FILE *fp;
char str[30] = error is;
int i = 20;
clrscr ( );
fp = fopen (sample. txt, r);
if (fp = = NULL)
{
printf (file doesnot exist);
}
else
{
fprintf (fp, %d, i);
if (ferror (fp))
{
perror (str);
Computer Programming course file
printf (error since file is opened for reading only);
}
fclose (fp);
getch ( );
}
O/P: Error is : Error1 compiler generated.
Error since file is opened for reading by us.
3. feof ( )
It is used for checking whether end of the file has been reached (or) not.
Syntax :
int feof ( file pointer);
Eg : FILE *fp;
if (feof (fp))
printf (reached end of the file);
If returns a non zero if success and zero otherwise.
Program:
main ( )
{
FILE *fp;
int i,n;
clrscr ( );
fp = fopen (number. txt, w);
for (i=0; i<=100; i+10)
{
putw (i, fp);
}
fclose (fp);
fp = fopen (number. txt, r);
printf (fiel content is);
for (i=0; i<=100; i++)
{
n = getw (fp);
if (feof (fp))
{
printf (reached end of file);
Computer Programming course file
break;
}
else
{
printf (%d, n);
}
}
fclose (fp);
getch ( );
}
Outpute : File content is
10 20 30 40 50
60 70 80 90 100
Reached end of the file.
Eg :
1. fseek (fp,0,2) - fp is moved o bytes forward from the end of the file.
2. fseek (fp, 0, 0) fp is moved o bytes forward from beginning of the file
3. fseek (fp, m, 0) fp is moved m bytes forward from the beginning of the file.
4. fseek (fp, -m, 2) fp is moved m bytes backward from the end of the file.
Errors :
1. fseek (fp, -m, 0);
2. fseek(fp, +m, 2);
Write a program some content in to the file and print the following ?
1. Number of characters entered into the file.
2. Reverse the characters entered into the file.
main ( )
{
Computer Programming course file
FILE *fp;
char ch;
int n;
clrscr ( );
fp = fopen (reverse. txt, w);
printf (enter text press ctrl+z of the end);
while ((ch = getchar( ) ) ! EOF)
{
putc (ch, fp);
}
n = ftell (fp)
printf ( No. of characters entered = %d, n);
rewind (fp);
n = ftell (fp);
printf (fp value after rewind = %d,n);
fclose (fp);
fp = fopen (reverse.txt, r);
fseek (fp, -1, 2);
printf (reversed content is)
do
{
ch = getc (fp);
printf (%c, ch);
} while (!fseek (fp, -2, 1);
fclose (fp);
getch ( );
}
Output : Enter text press ctrl z at the end.
How are you ^z
No. of characters entered = 11
fp value after rewind =0
Reversed content is uoy era woh.
Computer Programming course file
Program:
main ( )
{
FILE *fp;
char oldfn [30], newfn [30];
char ch;
clrscr ( );
printf (enter old file name);
scanf (%s, oldfn);
fp = fopen (oldfn, w);
printf (enter text press ctrl+z of the end);
while ((ch = getchagr ( ))! = EOF)
putc (ch, fp)
fclose (fp);
printf (enter new file name);
scanf (%s, newfn);
Computer Programming course file
rename (oldfn, newfn);
fp = fopen (newfn, r);
printf (new file content is);
while ((ch = getchagr ( ))! = EOF)
putchar (ch);
fclose (fp);
getch ( );
}