Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
INTRODUCTION TO COMPUTERS
UNIT - I
INTRODUCTION
Input Unit:
The storage unit of the computer holds data and instructions that
are entered through the input unit, before they are processed. It
preserves the intermediate and final results before these are sent to
the output devices. It also saves the data for the later use. The
various storage devices of a computer system are divided into two
categories.
2
Computer Programming & Data Structures
Memory Size:
All digital computers use the binary system, i.e. 0’s and 1’s. Each
character or a number is represented by an 8 bit code.
Output Unit:
Control Unit:
It controls all other units in the computer. The control unit instructs
the input unit, where to store the data after receiving it from the
user. It controls the flow of data and instructions from the storage
unit to ALU. It also controls the flow of results from the ALU to the
storage unit. The control unit is generally referred as the central
3
Computer Programming & Data Structures
The control unit and ALU of the computer are together known as the
Central Processing Unit (CPU). The CPU is like brain performs the
following functions:
Computer
System
Hardware Software
4
Computer Programming & Data Structures
5
Computer Programming & Data Structures
Software
System Application
software software
1. System Software
6
Computer Programming & Data Structures
2. Application software
7
Computer Programming & Data Structures
9
Computer Programming & Data Structures
10
Computer Programming & Data Structures
a. Advantages:
b. Disadvantages:
a. Advantages:
b. Disadvantages:
i. It is machine dependent.
ii. It requires the translator program called Assembler.
12
Computer Programming & Data Structures
a. Advantages:
i. Easy to follow.
ii. Easy to understand
iii. Easy to modify and debug.
iv. Suitable for complex applications.
b. Disadvantages:
13
Computer Programming & Data Structures
14
Computer Programming & Data Structures
The code in a source file stored on the disk must be translated into
machine language; this is the job of the compiler. The c compiler is
two separate programs. the preprocessor and the translator.
15
Computer Programming & Data Structures
16
Computer Programming & Data Structures
17
Computer Programming & Data Structures
1.6 ALGORITHMS
Properties:
1. Finiteness: An algorithm should have finite number of steps.
2. Definiteness: Any step of an algorithm should be definite and
unambiguous.
3. Effectiveness: An algorithm should be effective in solving the
problem that it's meant for.
4. Input: It should have zero or more inputs.
5. Output: It should have 1 or more outputs.
18
Computer Programming & Data Structures
Before writing an algorithm for a problem, one should find out what
is/are the inputs to the algorithm and what is/are expected output
after running the algorithm.
Step 1: Start
Step 2: Read the two numbers into a, b
Step 3: c a+b
Step 4: write/print c
Step 5: Stop.
Step 1: start
Step 2: read a positive integer no
Step 3: sum←0 dig←0
Step 4: dig ← no mod 10
Step 5: sum ← sum + dig
Step 6: no ← no/10
Step 7: repeat steps 3, 4, 5 until no greater than zero
Step 8: print sum
Step 9: stop
Example3: Algorithm to find the roots of a quadratic
equation.
Step 1: start
Step 2: read a, b, c values
Step 3: compute d=b*b-4ac
19
Computer Programming & Data Structures
Expected output:
Temperature in Celsius
Algorithm:
20
Computer Programming & Data Structures
M = 10
N=5
(Where M and N are variables)
IF (M >= N) Then
Statement 1
Else
Statement 2
END IF
Statement 3
According to this example, the condition of M>=N is true (since M is
10 and N is 5), and statement 1 will be executed. The execution of
statement 3 follows that.
Advantages
21
Computer Programming & Data Structures
knowledge, and has few formal syntax rules. It saves time that is
otherwise spent in debugging and testing codes, since it allows
programmers to spot and correct errors.
Disadvantages
1.8 FLOWCHARTS
(Or)
22
Computer Programming & Data Structures
4) Only one flow line should come out from a process symbol.
5) In the case of use of decision symbol, only one flow line should
enter to it (decision symbol), but there may be two or three flow
lines coming out of the decision symbol, one for each possible
answer.
6) In a flowchart only one flow line should come to the end symbol.
23
Computer Programming & Data Structures
24
Computer Programming & Data Structures
25
Computer Programming & Data Structures
26
Computer Programming & Data Structures
28
Computer Programming & Data Structures
Except for the simplest program, one set of test data will not
completely validate a program.
INTRODUCTION TO C LANGUAGE
29
Computer Programming & Data Structures
2.1 BACKGROUND
30
Computer Programming & Data Structures
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section
5. Main function section
{
Declaration section
Executable section
}
6. Sub program or function section
31
Computer Programming & Data Structures
/* simple program in c */
#include<stdio.h>
main()
{
printf(“welcome to c programming”);
} /* End of main */
2.3 C-TOKENS
CONSTANTS E.g.15.4,‘a’,200
E.g.rate,no_of_hours
IDENTIFIERS
E.g. int, printf
KEY WORDS
Fig. 1: C-Tokens
IDENTIFIERS
There are few rules that govern the way variables are
named(identifiers).
where data type could be float, int, char or any of the data
types.
e.g. float a, b, c;
int e, f, grand total;
char present_or_absent;
KEYWORDS
33
Computer Programming & Data Structures
volatile while
E.g.: int a, b;
char c;
34
Computer Programming & Data Structures
Derived data types are used in ‘C’ to store a set of data values.
Arrays and Structures are examples for derived data types.
C Provides a facility called typedef for creating new data type names
defined by the user. For Example, the declaration,
typedef int Integer;
makes the name Integer a synonym of int. Now the type Integer
can be used in declarations, casts, etc, like,
35
Computer Programming & Data Structures
2.5 VARIABLES
Syntax: variable_name=value;
e.g.: a=10;
Example:
/* write a program to show assigning of values to variables */
#include<stdio.h>
main()
{
int a;
float b;
printf("Enter any number\n");
b=190.5;
scanf("%d",&a);
printf("user entered %d", a);
printf("B's values is %f", b);
}
2.6 CONSTANTS
36
Computer Programming & Data Structures
3. Unsigned constants are written with a terminal ‘u’ or ‘U’, and the
suffix ‘ul’ and ‘UL’ indicates unsigned long. for example 123456789u
is a Unsigned constant and
1234567891ul is an unsigned long constant.
\a Alert
\b Backspace
\f Form feed
\n New Line
\r Carriage return
37
Computer Programming & Data Structures
\t Horizontal Tab
\v Vertical Tab
The first name in the enum has the value 0 and the next 1
and so on unless explicit values are specified.
2.7 OPERATORS
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
38
Computer Programming & Data Structures
operator meaning
+ add
- subtract
* multiplication
/ division
% modulo division(remainder)
operator meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
It is the form of
ae-1 relational operator ae-2
non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0 0 0 0
op-1 !op-1
39
Computer Programming & Data Structures
non-zero zero
zero non-zero
v is variable
op binary operator
exp expression
a=a+1 a+=1
a=a-1 a-=1
a=a%b a%=b
40
Computer Programming & Data Structures
operator meaning
Example1:
41
Computer Programming & Data Structures
Example3:
Example4:
2.8 EXPRESSIONS
2.8.1 Precedence
2.8.2 Associativity
Some examples
43
Computer Programming & Data Structures
A*B–C
(M + N) * (X + Y)
Variable = expression
High * / %
Low + -
44
Computer Programming & Data Structures
45
Computer Programming & Data Structures
(float) a
Syntax: varname=getchar();
The getchar() is used only for one input and is not formatted.
Formatted input refers to an input data that has been arranged in a
particular format, for that we have scanf.
e.g. scanf("%d%d",&a,&b);
%f floats
%l long
%c character
Syntax: putchar(varname);
Example:
#include<stdio.h>
main()
{
int a,b;
float c;
printf("Enter any number");
a=getchar();
printf("the char is ");
putchar(a);
printf("Exhibiting the use of scanf");
printf("Enter three numbers");
scanf("%d%d%f",&a,&b,&c);
printf("%d%d%f",a,b,c);
}
2.11 STATEMENTS
47
Computer Programming & Data Structures
Statement Types
1. Null Statement:
Eg:
//null statement
2. Expression Statement:
Eg: a=2;
3. Return Statement:
4. Compound Statements:
Example:
{
//Local Declarations
48
Computer Programming & Data Structures
int x;
int y;
int z;
//Statements
x=1;
y=2;
…
} //End Block
2.12.1 If Statements
if statement:
if(test expression)
Syntax:
if (test expression)
{
statement block;
}
statement–x;
Example:
/* program for if */
#include<stdio.h>
main()
{
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
49
Computer Programming & Data Structures
if a>b
printf(“ a is greater”);
if b>a
printf(“b is greater”);
}
if–else statement:
Syntax:
if (test expression)
{
statement block1;
}
else
{
statement block2;
}
statement –x ;
Example:
Syntax:
50
Computer Programming & Data Structures
if(text cond1)
{
if (test expression2
{
statement block1;
}
else
{
statement block 2;
}
}
else
{
statement block2;
}
statement-x ;
if else ladder:
Syntax:
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;
If for suppose we have more than one valid choices to choose from
then we can use switch statement in place of if statements.
Syntax:
switch(expression)
51
Computer Programming & Data Structures
{.
case value-1
block-1
break;
case value-2
block-2
break;
--------
--------
default:
default block;
break;
}
statement–x;
In case of
if(cond1)
{
statement-1;
}
if (cond2)
{
statement-2;
}
Example:
case 5 : grade=”second”;
break;
case 4 : grade=”third”;
break;
default : grade =”fail”;
break;
}
printf(“%s”,grade);
}
2.13 LOOPING
While Statement :
Example:
scanf(“%f%d”,&x,&n);
y=1.0;
count=1;
while(count<=n)
{
y=y*x;
count++;
}
printf(“x=%f; n=%d; x to power n = %f”,x,n,y);
}
Do While Statement :
The while loop does not allow body to be executed if test condition
is false. The do while is an exit controlled loop and its body is
executed at least once.
Syntax:
do
statement-body;
}while(test condition);
Example:
54
Computer Programming & Data Structures
}while(row<=ROW);
}
For Loop :
It is also an entry control loop that provides a more concise
structure
Syntax:
Example:
break statement:
55
Computer Programming & Data Structures
Example:
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
If you want to exit from more than one level of loop, the
break is the wrong thing to use.
continue statement:
This statement has only a limited number of uses. The rules for
its use are the same as for break, with the exception that it doesn't
apply to switch statements. Executing a continue starts the next
iteration of the smallest enclosing do, while or for statement
immediately. The use of continue is largely restricted to the top of
loops, where a decision has to be made whether or not to execute
the rest of the body of the loop. In this example it ensures that
division by zero (which gives undefined behaviour) doesn't happen.
Example:
#include <stdio.h>
#include <stdlib.h>
56
Computer Programming & Data Structures
main()
{
int i;
Syntax:
goto L1;
/* whatever you like here */
L1: /* anything else */
57
Computer Programming & Data Structures
It's hard to give rigid rules about the use of gotos but, as with
the do, continue and the break (except in switch statements), over-
use should be avoided. More than one goto every 3–5 functions is a
symptom that should be viewed with deep suspicion.
UNIT-II
3.0 INTRODUCTION
58
Computer Programming & Data Structures
3.2 FUNCTIONS IN C
59
Computer Programming & Data Structures
1. Library Functions
Library Functions
60
Computer Programming & Data Structures
//local declarations
……
……
//statements
……
return-type
Specifies the type of value that a function returns using the return
statement. It can be any valid data type. If no data type is specified
the function is assumed to return an integer result.
function-name
argument declaration
62
Computer Programming & Data Structures
2. in a function call
63
Computer Programming & Data Structures
Note: The prototype normally goes near the top of the program and
must appear before any call is made to the function.
Example:
void main ()
64
Computer Programming & Data Structures
{
Body of the
// local declarations
function
No
... appears in the
Semicol
// statements definition
on
...
65
Computer Programming & Data Structures
Observe from the figure 3.5 that the function greeting () do not
receive any values from the function main () and it does not return
any value to the function main ().Observe the transfer of control
between the functions indicated with arrows.
66
Computer Programming & Data Structures
#include<stdio.h>
void main ()
clrscr ();
getch ();
void sum ()
3.2.6.2
{ FUNCTIONS WITH NO ARGUMENTS AND RETURN
VALUES
return expression;
67
Computer Programming & Data Structures
example: return(x+y);
return (6*8);
return (3);
return;
In the above example, observe from the figure 3.6 that the function
getQuantity () do not receive any value from the function main
().But, it accepts data from the keyboard, and returns the value to
the calling function.
68
Computer Programming & Data Structures
#include<stdio.h>
void main ()
int c;
clrscr ();
RETURNING
getch (); VALUES FROM MAIN ()
int sumwe
When () use a return statement in main (), some program returns
a termination code to the calling process (usually to the O.S).The
return values must be an integer.
For many Operating Systems, a return value of ‘0’ indicates that the
program terminated normally. All other values indicate that some
error occurred. For this reason, it is good practice to use an explicit
return statement.
Local Variables
69
Computer Programming & Data Structures
Function arguments
1. actual arguments/parameters
2. formal arguments/parameters
Actual arguments/parameters
formal arguments/parameters
formal parameters are the variables that are declared in the header
of the function definition. These list defines and declares that will
contain the data received by the function. These are the value
parameters, copies of the values being passed are stored in the
called functions memory area.
70
Computer Programming & Data Structures
Observe from the figure 3.7 that the function printOne () receives
one value from the function main (), display the value copy of a.
#include<stdio.h>
void main ()
int a, b;
clrscr ();
1. call by value
2. call by reference
call by value
When a function
// C program illustrates is
callcalled
by value with actual parameters, the values of
actual parameters are copied into the formal parameters. If the
#include<stdio.h>
values of the formal parameters changes in the function, the values
ofvoidthe
swapactual
(int , int parameters
); are not changed. This way of passing
parameters is called call by value (pass by value).
void main ()
In the below example, the values of the arguments to swap () 10
{
and 20 are copied into the parameters x and y.Note that the values
of int
x and
a, b; y are swaped in the function. But, the values of actual
parameters remain same before swap and after swap.
clrscr ();
73
Computer Programming & Data Structures
Observe from the above figure 3.8 t the function sqrt receive one
value from the function main (), finds the square of the number and
sends the result back to the calling function.
#include<stdio.h>
void main ()
int a, b;
clrscr ();
getch ();
Computer Programming & Data Structures
75
Computer Programming & Data Structures
The above figure shows how two of the C standard functions that
we have used several times are brought into out program. The
include statement causes the library header file for standard input
and output(stdio.h) to be copied in to our program It contains the
declaration for printf and scanf.Then,when the program is linked,
the object code for these functions is combined with our code to
build the complete program.
76
Computer Programming & Data Structures
#include<stdio.h>
void main ()
int a, b;
x=read ();
y=read ();
return x+y;
}
Inintthe
read above
() example ,when the main() function executes it finds
the function call sum(), then the control is transferred from main()
to{ the function sum(),here we are calling the function read(), then
the control transferred to read() function,then the body of the
int p;
function read() executes,the control transfered from read to sum()
printf (“\n Enter any value: “);
77
Scanf (“%d”, &p);
return p;
}
Computer Programming & Data Structures
and once again the same is done for rading some other value. Then
the addition is performed this value is carried from sum() to
main().Observe the chain of control transfers between the nested
functions.
3.5 RECURSION IN C
Iteration definition
=n*(n-1)*(n-2)…….3*2*1 if n>0
Recursion definition
BASE CASE
fact (n) =1 if n=0
GENERAL CASE
=n*fact (n-1) if n>0
78
Computer Programming & Data Structures
#include <stdio.h>
int i;
4! = 24
i=4;
if (number ==0)
return 1;
else
79
Computer Programming & Data Structures
ITERATION RECURSION
81
Computer Programming & Data Structures
1. #include <filename>
Example: #include<stdio.h>
Note: here we can’t include user files why because it searches for
the files in the standard library only.
2. #include “filename”
note: We can also include file that is not present in the current
directory by specifying the complete path of the file like
#include “e:\muc.h”
83
Computer Programming & Data Structures
84
Computer Programming & Data Structures
#define CIRCLE_AREA( x ) PI * ( x ) * ( x )
#define RECTANGLE_AREA( x, y ) ( ( x ) *
(y))
to become rectArea = ( ( a + 4 ) * ( b + 7 ) );
85
Computer Programming & Data Structures
#define Mac =0
…..
…..
a=Mac;
….
will result in
num==0;
This is unwanted.
#include<stdio.h>
int main()
int a=10;
86
Computer Programming & Data Structures
Symbolic Constants
Nested Macros
For example,
87
Computer Programming & Data Structures
Undefining Macros
Example
#define Val 30
#undef Val
#define val 50
Predefined Macros
88
Computer Programming & Data Structures
Command Meaning
89
Computer Programming & Data Structures
90
Computer Programming & Data Structures
Syntax
#if expression1
#elif expression2
#else
#endif
91
Computer Programming & Data Structures
#endif
Command Meaning
#elif
Specifies alternate code in multi-way
decision.
#ifdef name
Tests for the macro definition.
#ifndef name
Tests whether macro is not defined .
92
Computer Programming & Data Structures
93
Computer Programming & Data Structures
Syntax:
Example:
auto int a;
Program:
#include <stdio.h>
#include <conio.h>
void main()
{
auto int i=10;
clrscr();
{
auto int i=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
getch();
}
Output :
20
10
94
Computer Programming & Data Structures
When the calculations are done in CPU, then the value of variables
are transferred from main memory to CPU. Calculations are done
and the final result is sent back to main memory. This leads to
slowing down of processes.
Program:
/* Program to demonstrate register storage class*/
#include <stdio.h>
#include <conio.h>
void main()
{
register int i=10;
clrscr();
{
register int i=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
getch();
}
Output: 20
10
95
Computer Programming & Data Structures
Program:
/* Program to demonstrate static storage class.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
void incre(void);
clrscr();
for (i=0; i<3; i++)
incre();
getch();
}
void incre(void)
{
int avar=1;
static int svar=1;
avar++;
svar++;
printf("\n\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}
Output:
Automatic variable value : 2 Static variable value : 2
96
Computer Programming & Data Structures
Program:
/* Program to demonstrate external storage class.*/
#include <stdio.h>
#include <conio.h>
97
Computer Programming & Data Structures
printf("\n\n\t %d",i);
}
Output: 20
10
3.8 ARRAYS IN C
3.8.1 INTRODUCTION
98
Computer Programming & Data Structures
Element type: what kind of data will your array hold? ints,
double, chars? Remember, we can only choose one type.
In C, the arrays can be classified based on how the data items are
arranged for human understanding
99
Computer Programming & Data Structures
int number;
For example:
int temp[5];
100
Computer Programming & Data Structures
For example:
double stockprice[31];
Where :
101
Computer Programming & Data Structures
If you know all the data at compile time, you can specify all your
data within brackets:
If we omit the size of your array, but specify an initial set of data,
the compiler will automatically determine the size of your array.
This way is referred as initialization without size.
102
Computer Programming & Data Structures
temp[0]temp[1] temp[2]temp[3]temp[4]
103
Computer Programming & Data Structures
Option 4
If you do not know any data ahead of time, but you want to
initialize everything to 0, just use 0 within { }.
For example:
Figure 3.17
104
Computer Programming & Data Structures
For example:
Figure 3.18
105
Computer Programming & Data Structures
Figure 3.19
for(i=0;i<365;i++)
temperature[i] = 0;
#include <stdio.h>
void main()
int a[10];
scanf(“%d”,&size);
scanf(“%d”,&a[i]);
double stockPrice[5];
106
Computer Programming & Data Structures
107
Computer Programming & Data Structures
Example,
char names[3][4];
};
108
Computer Programming & Data Structures
#include <stdio.h>
int main(void)
int a [ M ] [ N ], i, j, sum = 0;
printf(“a [ %d ] [ %d ] = %d “, i, j, a[ i ] [ j ]);
printf (“\n”);
109
}
Computer Programming & Data Structures
type arrayName[s1][s2][s3]….[sm];
int a[10][3][2];
110
Computer Programming & Data Structures
findMax(a,n);
will pass all the elements contained in the array a of size n.The
called function expecting this must be appropriately defined.
111
Computer Programming & Data Structures
// C program to find Maximum value in a given list int findMax(int x[],int size)
#include<stdio.h> {
{ for(i=1;i<size; i++)
scanf(“%d”,&n); {
UNIT-III
4.0 INTRODUCTION POINTERS
112
Computer Programming & Data Structures
Pointers are one of the derived types in C. One of the powerful tool
and easy to use once they are mastered.
The basic data types in C are int, float, char double and void.
Pointer is a special data type which is derived from these basic data
types.
Pointer Constants
Pointer Values
Pointer Variables
113
Computer Programming & Data Structures
= 64 * 1K
= 64 * 1024 bytes
114
Computer Programming & Data Structures
0 1
2 3
4 5
.. ..
.. ..
32278 32279
.. ..
65530 65531
65532
65534 65535
115
Computer Programming & Data Structures
int i=10;
i Variable Name
10 Variable value
Pointer Values
int a[10];
117
Computer Programming & Data Structures
The * Operator
This tells the compiler three things about the variable ptr_name.
int *pi;
Initializing Pointers
ptr_name=&var;
119
Computer Programming & Data Structures
*ptr_name
Example1
120
Computer Programming & Data Structures
121
Computer Programming & Data Structures
i pi
10 8342
8342 8338
Example2
122
Computer Programming & Data Structures
The following code illustrates how to declare int ,char and float
pointers. Here we have declared three variables of type int, float
and char ,also three pointer variables points to int, float and char.
Remember here pf points to the value of type float but its type is
unsigned integer only.
123
Computer Programming & Data Structures
124
Computer Programming & Data Structures
Example:
int* pa;
int* pb;
125
Computer Programming & Data Structures
Example:
Dangling Pointers
int *pi;
pi
Garbage Value
126
Computer Programming & Data Structures
Example:
pj = pj + 3; // pj=1018+(3*4)1030 address
Example:
POINTER EXPRESSIONS
a= *p1 + *p2;
z = 10 / *p2;
f = *p1 * i;
NULL Pointer
128
Computer Programming & Data Structures
double *pval2 = 0;
ptr_ptr=&ptr_name;
129
Computer Programming & Data Structures
**ptr_ptr;
It is equalent to *(*(&ptr_name));
Example
130
Computer Programming & Data Structures
int i=10;
float *pf;
131
Computer Programming & Data Structures
Casting pointers
Example:
int V = 101;
Void Pointer
void
Example:
int V = 101;
float f=98.45;
133
Computer Programming & Data Structures
Call by Reference
134
Computer Programming & Data Structures
The way function return an int, float and char, it can return a
pointer.
To make a function return a pointer it has to be explicitly
mentioned in the calling function as well as in the function
declaration.
Three things should be done to avail the feature of functions
return pointer.
135
Computer Programming & Data Structures
// local declarations
// executable statements
136
Computer Programming & Data Structures
Example:
Note: function return pointer does not have any advantage except
in the handling of strings.
138
Computer Programming & Data Structures
display
139
Computer Programming & Data Structures
The next after the declaration is calling the function using function
pointer. before calling takes place we must initialize the function
pointer with the address of the function.
f_ptr=function_name;
(*f_ptr)(argument’s);
141
Computer Programming & Data Structures
142
Computer Programming & Data Structures
143
Computer Programming & Data Structures
The name of the array num gets the base address. Thus by
writing *num we would be able to refer to the zeroth element
of the array, that is 1.
Then *num and *(num+0) both refer to the element 1.and
*(num+2) will refer 3.
When we have num[i] , the compiler internally converts it to
*(num+i).
In this light the following notations are same.
144
Computer Programming & Data Structures
num [0] num [1] num [2] num [3]num [4] elements
1 2 3 4 5
values
ptr
base address
145
Computer Programming & Data Structures
Example
146
Computer Programming & Data Structures
Note: Note that the array name num is a constant pointer points to
the base address, then the increment of its value is illegal, num++
is invalid.
int a [3][4];
147
Computer Programming & Data Structures
Columns
0 1 2 3
0
1 2 3 4
Rows 1 5 6 7 8
2
9 10 11 12
Example
148
Computer Programming & Data Structures
149
Computer Programming & Data Structures
*(*(*(a+i) +j) +k) --> value stored at kth dimension ith row jth
column
150
Computer Programming & Data Structures
Example
151
Computer Programming & Data Structures
152
Computer Programming & Data Structures
Example
153
Computer Programming & Data Structures
Example
Here we see the first situation in which C does not pass values to a
function. The reason for this change is that a lot of memory and
time would be used in passing large arrays every time we wanted to
use one in function.
154
Computer Programming & Data Structures
dimensional array and one dimensional are same but subscripts are
changed.
#include<stdio.h>
int main ()
int a[5][4]={
{0, 1, 2, 3},
};
square(a);
return 0;
The above program find the squares of the elements of the array
.Here we passed the name of the array as an argument to the
function an in the called function the formal argument is created
and points to the elements of the calling function argument array.
155
Computer Programming & Data Structures
The dataflow between the calling function and called function can be
divided into three strategies:
1. Downward flow
` 2. Upward flow
3. Bi-directional flow
156
Computer Programming & Data Structures
The called function may change the values passed, but the
original values in the calling function remain unchanged.
The call by value mechanism in C is a perfect solution for the
communication in the downward direction.
158
Computer Programming & Data Structures
159
Computer Programming & Data Structures
The type qualifier associated with some values which do not change
frequently. There are three type qualifiers in C,
1. const
160
Computer Programming & Data Structures
2. volatile
3. restrict
When a storage class, such as static, and a type qualifier are both
needed, the storage class comes before the type qualifier.
4.10.1 CONSTANTS
Example,
161
Computer Programming & Data Structures
Example,
int i = 5, j = 6;
When the keyword const is associated with the type, that is, it
is placed before the type, then the object being referenced is
a constant, but the pointer itself is not.
Can change value of pointed-to object, but pointer must
always refer to the same address.
Example,
162
Computer Programming & Data Structures
int i = 5, j = 6;
*p = j; /* Valid. i is now 6 */
4.10.2 VOLATILE
volatile int x;
4.10.3 RESTRICTED
int *ptr;
int i=0;
ptr=&i;
*ptr = *ptr+4;
*ptr = *ptr+5;
164
Computer Programming & Data Structures
int i=0;
ptr=&i;
*ptr = *ptr+4;
*ptr = *ptr+5;
4.11 STRINGS IN C
This may be written as ‘\0’ (zero not capital ‘o’). This is the
only character whose ASCII value is zero.
Depending on how arrays of characters are built, we may
need to add the null by hand, or the compiler may add it for
us.
Declaring a String
166
Computer Programming & Data Structures
If you know all the characters at compile time, you can specify all
your data within brackets:
Example,
char s[6]={‘h’,’e’,’l’,’l’,’o’};
h e l l o \0
167
Computer Programming & Data Structures
char s[10]={‘h’,’e’,’l’,’l’,’o’};
200 201 202 203 204 205 206 207 208 209 --> Address
168
Computer Programming & Data Structures
char s[]={‘h’,’e’,’l’,’l’,’o’};
h e l l o \0
char s[]=”hello”;
Here the length of the string is 5 bytes, but size is 6 bytes. The
compiler reserves 5+1 memory locations and these locations are
169
Computer Programming & Data Structures
h e l l o \0
char str3[5];
170
Computer Programming & Data Structures
Similarly,
char s1[4]=“abc”;
char s2[4];
s2=s1; /* Error */
Strings can be read from the keyword and can be displayed onto
the monitor using the following I/O functions.
The string can be read using the scanf function also. The format
specifier associated with the string is %s.
171
Computer Programming & Data Structures
Disadvantages
Syntax: %ws
NOTE:
172
Computer Programming & Data Structures
Example:
#include<stdio.h>
2. Precision Specifier
Syntax: %w.ns
#include<stdio.h>
#include<conio.h>
void main()
{
173
char s []={‘R’,’A’,’M’,’A’,’N’,’A’,’N’,’D’,’A’}:
clrscr();
printf(“%0.2s\n”,s);
Computer Programming & Data Structures
OUTPUT:
RA
RAMA
RAM
NOTE:
3. Left justification
Syntax: %-w.ns
174
Computer Programming & Data Structures
Example:
#include<stdio.h>
#include<conio.h> OUTPUT:
void main ()
{
RA
char s []={‘R’,’A’,’M’,’A’,’N’,’A’,’N’,’D’,’A’}:
clrscr(); RAMA
175
Computer Programming & Data Structures
The function accepts string from the keyboard. The string entered
includes the white spaces. The input will terminate only after
pressing <Enter Key>. Once the <Enter key > is pressed ,a null
character(\0) appended at the end of the string.
Advantage
puts(str);
176
Computer Programming & Data Structures
type variable-name[][];
The second subscript gives the length of each item in the array.
Example:char list[6][10]={
“akshay”,
“parag”,
“raman”,
“srinivas”,
“gopal”,
“rajesh”
};
177
Computer Programming & Data Structures
strcat () function:
strcat(string1,string2);
String1 and string2 are character arrays. When the function strcat is
executed, string2 is appended to string1.It does so by removing
the null character at the end of string1 and placing string2 from
there.
178
Computer Programming & Data Structures
strcat(part1,”Good”);
strcat(strcat(string1,string2),string3);
Example
#include <stdio.h>
#include <string.h>
main ()
strcmp(str1,str2);
179
Computer Programming & Data Structures
Example: strcmp(name1,name2);
strcmp(name1,”John”);
strcmp(“their” ,”there”);
#include <stdio.h>
#include <string.h>
main ()
char password[255];
strcpy () function:
strcpy(string1,string2);
180
Computer Programming & Data Structures
strcpy(city1,city2);
#include <stdio.h>
#include <string.h>
main ()
char word2[255];
Output:
strlen () function:
181
Computer Programming & Data Structures
n=strlen(string);
Example:
#include<stdio.h>
#include<string.h>
void main()
Output: 4
{
char name[100]="Gore";
Note, however, that the
size of the array is 100
strrev () function
strrev(string);
Example:
#include<stdio.h>
#include<string.h>
char s[]=”hello”;
Computer Programming & Data Structures
OUTPUT:
olleh
strstr () function:
The function strstr searches the string s1 to see whether the string
s2 is contained in s1.If yes, the function returns the position of the
first occurrence of the sub-string. Otherwise, it returns a NULL
pointer.
else
183
Computer Programming & Data Structures
Example: strrchr(s2,’m’);
184
Computer Programming & Data Structures
char *p=”hello”;
185
Computer Programming & Data Structures
h e l l o \0
1000
char *p2;
p1=p2; //valid
186
Computer Programming & Data Structures
Example:
char s [] =”hello”;
s[i] --> *(s+i) --> *(i+ s) all will point to the ith character in
the given string.
char s [ ]=”hello”;
char *ptr;
*ptr --> *(ptr+i) --> *(i+ptr) will point value at the ith
character.
#include<stdio.h>
void main ()
char s [] =”hello”;
ptr=s;
OUTPUT
hello
OUTPUT
#include<stdio.h> 1
void main () 2
i j k l
1
4000 2
5000 3
6000 7000 4
The above figure 4.14 shows contents and the arrangement of the
array of pointers in memory. Here, arr contains the addresses of int
variables i, j, k and l. The for loop is used to print the values
present at these addresses.
189
Computer Programming & Data Structures
where data type refers to the data type of the array. arr_ptr refers
to the name of the array and size is the maximum number of
elements in the row.
p[i] +j --> points the address of the element ith row and jth
column
# include <stdio.h>
int main ()
char *name [] = {
"Illegal month",
"October", "November",
"December"
};
191
Computer Programming & Data Structures
192
Computer Programming & Data Structures
Exercise Programs
193
Computer Programming & Data Structures
194
Computer Programming & Data Structures
ASSIGNMENT IV
195
Computer Programming & Data Structures
UNIT IV
5.0 INTRODUCTION
The basic data types in C are int, float and char. using these data
types, we can derive some other data types, the data types that are
derived from the basic data types are called derived data types.
5.1 STRUCTURES
196
Computer Programming & Data Structures
Structure Definition
Advantages
197
Computer Programming & Data Structures
Tagged Structure
Structure Variables
Typedef Structure
Tagged Structure
struct tag_name
type1 member1;
type2 member2;
……………
198
Computer Programming & Data Structures
Where,
struct student
int roll_number;
float avg_marks;
199
Computer Programming & Data Structures
The following figure shows the memory organization for the above
example.
s1
200
Computer Programming & Data Structures
The number of bytes allocated for the structure variable is the sum
of sizes of the individual members. In the above example the size of
s1=16 bytes (10+2+4).
Structure Variables
struct tag_name
type1 member1;
type2 member2;
Where,
struct student
int roll_number;
float avg_marks;
} s1;
We can omit the tag name from the structure definition, the
following is valid.
struct
int roll_number;
float avg_marks;
} s1, s2;
202
Computer Programming & Data Structures
Typedefined Structure
typedef struct
type1 member1;
type2 member2;
where,
203
Computer Programming & Data Structures
//Structure Definition
typedef struct
int roll_number;
float avg_marks;
/* structure declaration */
The rules for structure initialization are similar to the rules for array
initialization. The initializers are enclosed in braces and separate by
commas. They must match their corresponding types in the
structure definition.
204
Computer Programming & Data Structures
Consider the structure definition for student with three fields name,
roll number and average marks. The initialization of variable can be
done as shown below,
struct student
int roll_number;
float avg;
R a v i \0 1 0 6 7 . 8
205
Computer Programming & Data Structures
Consider the structure definition for student with three fields name,
roll number and average marks. The initialization of variable can be
done as shown below,
struct student
char name[5];
int roll_number;
float avg;
};
Points to Remember
For example,
struct s
206
Computer Programming & Data Structures
int rno;
} s1;
is invalid.
For example,
For example,
s1= {“ravi”};
207
Computer Programming & Data Structures
For example,
Structures use a dot (.) operator to refer its elements, also known
as period operator.
Before dot, there must always be a structure variable. After the dot,
there must always be a structure element.
208
Computer Programming & Data Structures
structure_variable_name. structure_member_name
struct student
int roll_number;
float avg;
};
209
Computer Programming & Data Structures
struct student
int roll_number;
float avg;
};
s1.marks [0] --> will refer the 0th element in the marks
s1.marks [1] --> will refer the 1st element in the marks
s1.marks [2] --> will refer the 2ndt element in the marks
210
Computer Programming & Data Structures
211
Computer Programming & Data Structures
Example,
struct student
{
212
Computer Programming & Data Structures
float avg;
} a, b;
a=b; //copies b in to a
213
Computer Programming & Data Structures
214
Computer Programming & Data Structures
Operation Meaning
215
Computer Programming & Data Structures
Expression Meaning
struct tag_name1
type1 member1;
…….
216
Computer Programming & Data Structures
…….
};
struct tag_name2
type1 member1;
……
……
……
};
outer_structure_variable.innerstructurevariable.membername
Example: Consider the student information name, roll no, DOB and
avg. The DOB consists of day, month, and year. It can be defined as
shown below,
217
Computer Programming & Data Structures
struct data
int day;
int month;
int year;
};
struct student
int roll_number;
float avg;
} s1;
s1.dob.day
s1.dob.month
s1.dob.year
218
Computer Programming & Data Structures
s1
struct tag_name1
Example
{
struct student
{
type1 member1;
char name [10];
…….
int roll_number;
…….
struct data
219
struct tag_name2
{
{
int day;
type1 member1;
Computer Programming & Data Structures
in the
220
Computer Programming & Data Structures
221
Computer Programming & Data Structures
222
Computer Programming & Data Structures
struct student
char name[10];
int rno;
float avg;
// program illustrates reading and displaying of student information for a class of
students
}; using array of structures
#include<stdio.h>
struct student
struct student s[3];
{
char rollno[10];
Defines array called s, which contains three elements. Each element
char name[20];
is defined to be of type struct student.
char branch[10];
For char
the gender;
student details, array of structures can be initialized as
follows,
struct birthday
struct
{ student s[3]={{“ABC”,1,56.7},{“xyz”,2,65.8},
{“pqr”,3,82.4}};
int day;
The memory organization of the variables is illustrated in the below
char month[10];
Figure,
int year;
s
}DOB; Name rno avg
int i,n,j,sum=0;
223
struct student s[10];
sum=0;
for(j=0;j<3;j++)
scanf("%d",&s[i].sub[j]);
sum=sum+s[i].sub[j];
s[i].avg=sum/3.0;
printf("\n******************************************");
printf("\n******************************************");
224
for(i=0;i<n;i++)
{
Computer Programming & Data Structures
(*ptr).structure_member1
(*ptr).structure_member2
struct student
int rno;
char name[10];
float avg;
};
ptr=&s1;
226
Computer Programming & Data Structures
Now the members of the structure can be accessed by using the dot
operator as shown below,
227
Computer Programming & Data Structures
Remember that on the left hand side of the dot operator, there
must always be a structure variable, whereas on the left hand side
of -> operator there must be always be a pointer to structure. This
method is efficient, preferred over the previous method.
ptr
4001
5001
228
Computer Programming & Data Structures
229
Computer Programming & Data Structures
#include<stdio.h>
struct student
int rno;
float *ptr;
};
231
Computer Programming & Data Structures
232
Computer Programming & Data Structures
Explanation
233
Computer Programming & Data Structures
………
………
return(expression);
The called function must be declared for its type, appropriate to the
data type it is expected to return.
234
Computer Programming & Data Structures
235
Computer Programming & Data Structures
Explanation
236
Computer Programming & Data Structures
Note that here the calling of function fun becomes quite compact,
fun (s1); Then the formal argument in the called function defined as
struct type struct student.
237
Computer Programming & Data Structures
238
Computer Programming & Data Structures
239
Computer Programming & Data Structures
Struct tag_Name
type1 member1;
type2 member2;
….
240
Computer Programming & Data Structures
Example,
struct node
I int data;
} n1, n2;
241
Computer Programming & Data Structures
5.8 UNIONS
union tag_name
type1 member1;
type2 member2;
……..
242
Computer Programming & Data Structures
{ { {
tagged
union variable union typedef union
243
Computer Programming & Data Structures
a.c
a.i
a.f
For the above example, union contains three members, each with a
different data type. However, we can use only one of them at a
time.
a.c
a.i
a.f
244
Computer Programming & Data Structures
245
Computer Programming & Data Structures
246
Computer Programming & Data Structures
union u
char c;
int i;
float f;
247
Computer Programming & Data Structures
248
Computer Programming & Data Structures
uu.aa.i uu.aa.j
uu.bb.x uu.bb.y
249
Computer Programming & Data Structures
250
Computer Programming & Data Structures
…………… ……………
…………… ……………
}; };
251
Computer Programming & Data Structures
5.9 TYPEDEF
252
Computer Programming & Data Structures
where,
Note that using typedef, we are not creating new data types.
Instead we are creating only new name for the existing data type.
These new data type names are called user-defined data types.
Advantages
253
Computer Programming & Data Structures
typedef struct
type1 member1;
type2 member2;
254
Computer Programming & Data Structures
{ {
}; } EMP;
int age;
float bs;
255
Computer Programming & Data Structures
256
Computer Programming & Data Structures
257
Computer Programming & Data Structures
enum type_Name
member1;
member2;
….
258
Computer Programming & Data Structures
Where,
{ {
RED, SUNDAY,
BLUE, MONDAY,
GREEN …
}; SATURDAY
259
Computer Programming & Data Structures
260
Computer Programming & Data Structures
We can override it and assign our own values, For example, for
example to make JAN start with 1 we could use the following
declaration
enum month
JAN=1, FEB, MAR, APR, MAY,JUN, JUL, AUG, SEP, OCT, NOV,
DEC
} m1;
enum days
} d1, d2;
261
Computer Programming & Data Structures
typedef enum
} DAYS;
262
Computer Programming & Data Structures
263
Computer Programming & Data Structures
264
Computer Programming & Data Structures
There are several variables whose max values are small enough to
pack into a single memory location. We can use ‘bit fields’ to store
several values in a single integer.
struct tag_Name
Where,
265
Computer Programming & Data Structures
Remember that a signed bit field should have at least 2bits (1bit for
sign). The bit_length is decided by the range of value stored. The
largest value that can be stored is 2n-1, where n is bit_length.
The first field always starts with first bit of the word.
A bit can not overlap integer boundaries. This is, the sum of
lengths of all fields in a structure should not be more than the
size of a word. In case, it is more, the overlapping field is
automatically forced to the beginning of the next word.
There can be unnamed field declared with size. Example,
unsigned : bit_length;
266
Computer Programming & Data Structures
267
Computer Programming & Data Structures
268
Computer Programming & Data Structures
Exercise Programs
name string
reg no integer
major string
result string
269
Computer Programming & Data Structures
(b) To print out hotels with room charges less than a given
value.
270
Computer Programming & Data Structures
(b) The highest marks in each subject and the Roll No. of the
student who secured it.
ASSIGNMENT V
271
Computer Programming & Data Structures
6.0 INTRODUCTION
The I/O library functions can be classified into two broad categories:
272
Computer Programming & Data Structures
Console I/O refers to the operations that occur at the keyboard and
screen of the computer. Because input and output to the console is
such a common affair, a subsystem of the ANSI I/O file system was
created to deal exclusively with console I/O. Technically, these
functions direct their operations to the standard input (stdin) and
standard output (stdout) of the system.
Disadvantages
6.1 FILES
273
Computer Programming & Data Structures
6.1.1 BUFFER
When the computer reads, the data move from the external
device to memory; when it writes, the data move from
memory to the external device. This data movement often
uses a special work area known as buffer.
Example: input.txt
program.c
6.1.4 STREAM
Buffer
//C program
abcdefg
…
..
Stream
abcdefg
File
Figure: 6.1 data flow
275
Computer Programming & Data Structures
1. Create a stream
2. Open a file
4. Close file
Creating a Stream
FILE *fp;
276
Computer Programming & Data Structures
Opening File
When file processing is complete, we close the file. After closing the
file the stream is no longer available.
277
Computer Programming & Data Structures
The function that prepares a file for processing is fopen. It does two
things: first, it makes the connection between the physical file and
the file stream in the program. Second, it creates a program file
structure to store the information needed to process the file as
shown in Figure 6.3
278
Computer Programming & Data Structures
C Program Buffer
#include<stdio.h> abcdefghijklmnopqrstu
vwxyz
void main () stream
{
….}
stream
1 2 3 ..
File
File Structure
Syntax,
The file mode is a string that tells C compiler how we intend to use
the file: read existing file, write a new file or append to a file.
279
Computer Programming & Data Structures
Once the files are open, they stay open until you close them or end
the program (which will close all files.)
File Mode
When we open a file, we explicitly define its mode. The mode shows
how we will use the file: for reading, for writing, or for appending.
The read mode (r) opens an existing file for reading. When a file is
opened in this mode, the file marker is positioned at the beginning
of the file (first character). The file marker is a logical element in
the file structure that keeps track of our current position in the file.
The write mode (w) opens for writing. If the file doesn’t exist, it is
created. IF it is already exists, it is opened and all its data are
erased; the file marker is positioned at the beginning of the file
(first character) It is an error to try to read from a file opened in
write mode. A file opened for writing is shown in figure 6.4.
The append mode (a) also opens an existing for writing. Instead of
creating a new file, however, the writing starts after the last
character; that is new data is added, or appended, at the end of the
file.
280
Computer Programming & Data Structures
IF the file doesn’t exist, it is created and opened. In this case, the
writing will start at the beginning of the file; File opened in append
mode are shown in Figure 6.4.
In this mode file is opened for both reading and writing the data. If
a file does not exist then NULL, is returned.
In this mode file is opened for both writing and reading the data. If
a file already exists its contents erased. If a file does not exist then
new file created.
In this mode file is opened for reading the data as well as data can
be added at the end.
The above figure shows the file marker position in different modes.
281
Computer Programming & Data Structures
fclose (file_pointer);
Once a file is closed, its file pointer can be reused for another
file.
282
Computer Programming & Data Structures
283
Computer Programming & Data Structures
Example:
Example:
284
Computer Programming & Data Structures
float a; int b;
int a, b;
FILE *fptr1;
The fscanf function would read values from the file "pointed"
to by fptr1 and assign those values to a and b.
End of File
285
Computer Programming & Data Structures
286
Computer Programming & Data Structures
int a = 5, b = 20;
FILE *fptr2;
fprintf function works like printf except that it specifies the file
in which the data will be displayed. The file can be standard
output (stdout) or standard error (stderr) also.
Example,
287
Computer Programming & Data Structures
// OUTPUT
288
Computer Programming & Data Structures
ch =getchar ();
289
Computer Programming & Data Structures
The getc functions read the next character from the file stream,
which can be a used-defined stream or stdin, and converts it in to
an integer. This function has one argument which is the file pointer
declared as FILE.
If the read detects an end of file, the function returns EOF, EOF is
also returned if any error occurs. The functionality of getc/fgetc
same.
290
Computer Programming & Data Structures
getc (fp);
fgetc (fp);
Example,
char ch;
For fputc, the function takes two arguments. The first parameter is
the character to be written and the second parameter is the file,
The second parameter is the file pointer declared as FILE.
Syntax,
Example,
char ch;
291
Computer Programming & Data Structures
292
Computer Programming & Data Structures
The gets and fgets function take a line (terminated by a new line)
from the input stream and make a null-terminated string out of it.
These are sometimes called line-to-string input function.
gets ()
293
Computer Programming & Data Structures
gets (string_name);
fgets ()
294
Computer Programming & Data Structures
295
Computer Programming & Data Structures
puts ()
296
Computer Programming & Data Structures
puts (string_name);
fputs ()
297
Computer Programming & Data Structures
// output
298
Computer Programming & Data Structures
This function scans a string through the data were coming from a
file. Just like fscanf, it requires a format string to provide the
formatting parameters for the data.
Instead of reading these data from the keyboard, we can also read
from a string stored in memory using sscanf ().
299
Computer Programming & Data Structures
Syntax,
Example,
The string print function is sprintf, follows the rules of fprintf. Rather
than sending the data to a file. however, it simply “writes” them to
a string. When all data have been formatted to the string, a
terminating null character is added to make the result a valid string.
If an error is detected, sprintf returns any negative value or EOF. If
the formatting is successful, it returns number of characters
formatted.
300
Computer Programming & Data Structures
Syntax,
The first argument is the string, which contains the data to written.
The second is the control string consisting of format Specifiers.
Variables, it is a list of variables in to which formatted data is
copied.
Example,
301
Computer Programming & Data Structures
Text File
302
Computer Programming & Data Structures
For example, the data 2345 requires 4 bytes with each character
occupying exactly one byte. A text file cannot contain integers,
floating – point numbers etc. converted to their character –
equivalent formats.
Binary File
A binary file is the one where data is stored on the disk in the same
way as it is represented in the computer memory. The binary files
are not in human readable form and they can be created and read
only by specific programs written for them. The binary data stored
in the file cannot be read using any of the text editors.
For example, the data 2345 takes 2 bytes of memory and is stored
as 0 x 0929 i.e., 0 x 09 is stored as one byte and 0 x 29 is stored as
other byte. The number of characters written / read is same as the
303
Computer Programming & Data Structures
The differences between text file and binary file are as shown in
Table 6.1. The following Figure 6.11 illustrates the storage
difference between text file and binary file.
2. Data is stored as lines of 2. Data is stored on the disk in the same way
characters with each line it is represented in the computer memory.
terminated by / n which may
be translated into carriage
return + line feed.
4. Data can be read using any 4. Data can be read only by specific program
of the text editors. written for them.
to- one relationship between the characters written / read into the file a
the characters written / read those stored on the external devices.
into the file and those stored
on the external devices.
7. The data 2345 requires 4 7. The data 2345 requires 2 bytes and stored
bytes with each character 0x0929. The data 2345 is requiring 2 bytes.
requiring one byte. So, it is
stored as 0x 32, 0x 33, and 0 x
34, 0 x 35 (ASCII values) thus
requiring 4 bytes.
The basic operation is unchanged for binary files-only the mode changes. Different modes of
operation of binary file are illustrated in Table 6.2.
Mode Meaning
305
Computer Programming & Data Structures
mode.
Just like text files, binary files must be closed when they are not
needed anymore using fclose ().
C language uses the block input and output functions to read and
write data to binary files. As we know that data are stored in
memory in the form of 0’s and 1’s. When we read and write the
binary files, the data are transferred just as they are found in
memory and hence there are no format conversions. The block read
function is file read(fread). The block write function is file write
(fwrite).
307
Computer Programming & Data Structures
tell location
rewind file
file seek
Here the return type is long integer because many files have
more than 32,767 bytes. The operation ftell is graphically
shown in Figure 6.14.
308
Computer Programming & Data Structures
n=ftell (fp);
rewind (fp);
309
Computer Programming & Data Structures
Example:
rewind (fp);
n=ftell (fp);
Would assign 0 to n because the file position has been set to the
start of the file by rewind.
310
Computer Programming & Data Structures
Value Meaning
0 beginning of file.
1 Current position.
2 End of file.
Statement Meaning
311
Computer Programming & Data Structures
312
Computer Programming & Data Structures
// contents of input.txt
// output
313
Computer Programming & Data Structures
Device overflow.
n=feof (fp);
314
Computer Programming & Data Structures
if (feof (fp))
n=ferror (fp);
The statement
if(ferror(fp)!=0)
However, that testing for an error not reset the error condition.
Once a file enters the error state. It can only return to a read or
write state by calling clear error function: clearerr.
315
Computer Programming & Data Structures
The first parameter argc stands for the argument count, which is of
integer data type. Its value is the number of arguments in the
command line that was used to execute the program.
#include<stdio.h>
int j;
argument 1 is one
argument 2 is two
argument 3 is three
316
Computer Programming & Data Structures
Exercise Programs
317
Computer Programming & Data Structures
ASSIGNMENT VI
2. What are the file I/O functions in C. Give a brief note about
the task performed by each function?
a) fseek()
b) ftell()
c) rewind()
d) ferror()
e) feof()
4. Write the syntax for opening a file and closing a file. Explain
different modes of operation of a file.
318
Computer Programming & Data Structures
319