Basic C
Basic C
PREPARED BY
[Link],
ASST PROFESSOR, DEPARTMENT OF CS
SCAJC11- Fundamentals of Computer & C Programming - I BCA : I Semester
Reading and Writing a Character – Formatted Input, Output - Decision Making & Branching: if
statement – if else statement – nesting of if else statement – else if ladder – switch statement –
?: operator – Goto statement – the while statement – do statement – the for statement – jumps in
loops.
Unit-III: ARRAYS
Need – Multi-function programs – elements of user defined functions – definition – return values
and their types – function calls, declaration, category – all types of arguments and return values –
nesting of functions – recursion – passing arrays, strings to functions – scope visibility and life
time of variables, Structures and Unions: Defining a Structure - declaring a structure variable –
accessing structure members – initialization – copying and comparing – operation on individual
members – array of structures – arrays within structures – structures within structures –
structures and functions – unions – size of structures – bit fields.
Unit-V: POINTERS
PROGRAMMING IN C – SCSJC11
Unit-I:
OVERVIEW OF C
HISTORY OF „C‟
1. Root of the modern language is ALGOL introduced in the early 1960. It‟s first
computer language to use a block structure. It gave concept of structured programming.
2. In 1967, Martin Richards developed a language, BCPL (Basic Combined Programming
Language)
3. In 1970, by Ken Thompson created a language called as „B‟. It used to create early
version of Unix operating system.
4. In 1972, by Dennis Ritchie introduced new language called as „C‟ .
Traditional C
The C language was created in the early 1970s and, over the next decade or so, grew and evolved
substantially, until finally being standardized in 1989. Prior to 1989, the original language
reference was defined by the first edition of The C Programming Language by Kernighan and
Ritchie in 1978. This version is now called
“Classic C” or “K&R C”.
Standard C
3
During 1990‟s, C++ extends C to include support for Object Oriented Programming and other
features that facilitate large software development projects. During the same period, Sun
Microsystems of USA created a new language java modelled on C and C++.
Features of „C‟
Documentation Section: It has set of comment lines giving the name of program, author details.
Link Section: It provides instructions to the compiler to link function from the system library.
# include Directive
To access the functions which are stored in the library, it is necessary to tell the compiler, about
the file to be accessed.
4
Syntax
#include<stdio.h>
The first line of the program #include <stdio.h> is a preprocessor command, which tells a C
compiler to include stdio.h file before going to actual compilation.
Global Declaration Section: Some variables that are used in more than on function, such
variables (global variables) declared in the global declaration section that is outside of all the
functions. It also declares all the user-defined function.
Main() function section: Every „C‟ program must have one main() function section. It contains
two parts
1. Declaration part: It declares all variables used in the executable part.
2. Executable part: It has atleast one statement.
3. Every C program should have a pair of curly braces ({, }). The left braces indicates the
beginning of the main ( ) function and the right braces indicates the end of the main ( )
function. All statements in the declaration and executable parts end with a semicolon (;).
Sub Program Section: A subprogram is a function and these functions are written by the user
are called user defined functions. These functions are performed by user specific tasks and this
5
also contains set of program statements. They may be written after a main () function and called
within main () function.
Example Program
/* print hello*/
#include<stdio.h> /* link section*/
void main() /* execution of program*/
{
print(“hello world”); /*executable statement*/
}
Output
hello world
********
How to run (executing) a „C‟ program
Executing a program written in C involves a series of steps. These are
1. Creating the program
2. Compiling the program
3. Linking the program with functions that are needed from the C library
4. Executing the program
The compiled and linked program is called the executable object code and is stored automatically
in another file named [Link].
6
The command [Link] would load the
executable object code into the
computer memory and execute the
instructions. During execution, the
program may request for some data to be
entered through the keyboard.
Sometimes the program code does not
produce the desired result. Then it
would be necessary to correct the source
program or the data. In case the program
is modified, the entire process of
compiling, linking and executing the program should be repeated.
Programming language is designed to help process certain kinds of data consisting of numbers,
characters and strings and to provide useful output known as information. The task of processing
of data is accomplished by executing a sequence of precise instructions called a program. These
instructions are formed using certain symbols and words according to some rigid rules known as
syntax rules.
Character set
1. Letters - Uppercase A…Z; Lowercase a…z;
2. Digits - All decimal digits 0…9;
3. Special Characters: - . : ; ? “ „ / ~ ` ! @ # $ % ^ & * ( ) { } [ ] –
4. White spaces , [Link] space, [Link] tab, [Link] return, [Link], 5. Form feed.
Trigraph characters
Many non-English keyboards do not support all the characters. For that C introduces the concept
of “TRIGRAPH” sequences to provide a way to enter certain characters that are not available on
some keyboards. Each TRIGRAPH sequence consists of three characters (two question mark
followed by another character).
7
C TOKENS
In a passage of text, individual words and punctuation marks are called tokens. The smallest
individual units are known as C tokens.
Keywords (eg: int, while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: “total”, “hello”),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)
Identifiers refer to the names of variable, functions and arrays. These are user defined names and
consist of sequence of letters and digits. Both uppercase and lowercase letters are permitted. But
uppercase and lowercase letters are not having same meaning e.g. RAM & ram are not same.
The underscore character (_) can also be included and is considered to be a letter.
Rules
1. First character must be alphabet.
2. Consist of letters, digits, underscore
3. Only first 31 characters are significant
8
4. Cannot use a keyword
5. Must not contain white space
Constants
Constant in C refers to fixed values that do not change during the execution of a program. C
supports four types of constants.
Integer constant
An integer constant refers to a sequence of digits. There are three types of integers, namely,
decimal, octal and hexadecimal.
Decimal: Decimal integer constant can consist of any combination of digits taken from the set 0
through 9, proceded by an optional - or + sign.
Example: 123, -87, 0, +56 valid
$1000, 15 750, (20,000) Invalid
Octal: An octal integer constant can consist of any combination of digits taken from the set 0
through 7, with a leading 0.
Example: 075, 051 are octal
Hexadecimal: A hexadecimal integer constant must begin with either 0x or 0x. It can then be
followed by any combination of digits taken from the sets 0 through 9 and the letters A through F
represent the numbers 10 through 15 respectively.
Example: 0x2, 0x3A, 0Xe5 are hexadecimal numbers.
The largest integer value that can be stored is machine dependent. It is 32767 on 16-bit machines
and 2147483647 on 32-bit machines. It is also possible to store larger integer constants on these
machines by appending qualifiers such as U, L and UL to the constants.
For example
56789U (unsigned integer),
876543217UL (unsigned long integer),
9765467L (Long integer)
Real Constants
Real Constants consists of a fractional part in their representation. Integer constants are
inadequate to represent quantities that vary continuously. These quantities are represented by
numbers containing fractional parts like 26.083. Example
9
0.0026, -0.97, 435.29, +487.0
Real Numbers can also be represented by exponential notation. The general form for exponential
notation is mantissa exponent. The mantissa is either a real number expressed in decimal
notation or an integer. The exponent is an integer number with an optional plus or minus sign.
Example
0.65e4, 12e-2, -1.2e-1
String Constants
String constant is a set of characters enclosed in double quotation marks. The characters in a
string constant sequence may be an alphabet, number, special character and blank space.
Example
“hello!” , “1986”, “Hi well done”, “a”
Variables
A variable is data name that may be used to store a data value. Each variable has a specific
storage location in memory where its value is stored.
1. Every variable has a name, a type, a size and a value
2. Whenever a new value is placed into a variable, it replaces (and destroys) the previous
value
10
3. Reading variables from memory does not change them
Rules
1. They must begin with a letter
2. ANSI standard recognizes a length of 31 characters. However, the length
should not be normally more than eight characters, since only first eight characters are
treated as significant by many compilers.
3. The uppercase & lowercase letters are different e.g., Marry, MARRY, marry
are different variables names.
4. Variable name should not be a keyword.
5. No special characters, such as period, comma, semicolon, blanks are
permitted in variable names.
Data Types
C language is rich in its data types. Storage representations and machine instructions to handle
constants differ from machine to machine. The variety of data types available allows the
programmer to select the type appropriate to the needs of the application as well as the machine.
C language data types can be broadly classified as
a) Primary data type
b) Derived data type
c) User-defined data type
Basically C supports five Primary data types :-integer (int) , character (char), floating point
(float) , double precision floating point (double) and void.
11
Integer Types
1. Integers are whole numbers with a range of values, range of values are machine
dependent.
2. Generally an integer occupies 2 bytes memory space and its value range limited to -
32768 to +32767 (that is, -215 to +215-1).
3. A signed integer use one bit for storing sign and rest 15 bits for number.
4. To control the range of numbers and storage space, C has three classes of integer storage
namely short int, int and long int.
5. All three data types have signed and unsigned forms.
6. A short int requires half the amount of storage than normal integer.
7. Unlike signed integer, unsigned integers are always positive and use all the bits for the
magnitude of the number.
8. Therefore, the range of an unsigned integer will be from 0 to 65535.
9. The long integers are used to declare a longer range of values and it occupies 4 bytes of
storage space.
12
3. A double data type number uses 64 bits giving a precision of 14 digits. These are known
as double precision numbers.
4. To extend the precision further we can use long double which uses 80 bits.
Void Types
The void has no values. This is usually used to specify the type of functions. The type of a
function said to be void when it does not return any value to the calling function.
Character Types
A single character can be defined as a character (char) type data. Characters are usually stored in
8 bits of internal storage. While unsigned chars have values between 0 to 255, signed chars have
values from -128 to 127.
Declaration of Variables
After designing suitable variable names, we must declare them to the compiler. Declaration does
two things
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable will hold
The declaration of variables must be done before they are used in the program.
13
Declaration of variables is usually done immediately after the opening brace of the program. The
variable can also declared outside of the main function.
Example
main()
{
int count;
int number,total;
double ratio;
}
Syntax
Variable_name=constant;
Example
initial_value=0;
final_value=100;
balance=75.84;
yes=‟x‟;
1. C permits multiple assignments in one line. Example
initial_value=0; final_value=100;
2. An assignment statement implies that the value of the variable on the left of the equal
sign is set equal to the value of the quantity on the right. Example
Year=year+1;
This means that the new value of year is equal to the old value of the year plus 1.
3. C converts the type of value on the right hand side to the type on the left. This may
involve truncation when real value is converted to an integer.
4. It is also possible to assign a value to a variable at the time the variable is declared.
Syntax
14
data-type variable_name=constant;
Example
int final_value=100;
double balance=75.84;
char yes=‟x‟;
The process of giving initial values to variable is called initialization.
5. C permits initialization of more than one variable in one statement using multiple
assignment operators.
Example
p=q=s=0;
x=y=z=max;
15
Here by default Enumeration constant Mon is assigned 1, Tuesday assigned 2, and so on.
The definition and declaration of enumerated variables can be combined in one statement.
Example
enum day{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday}week_st, week_end;
Modifiability
We may like to change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of
calculations. We will have to search throughout the program and explicitly change the value of
the constant wherever it has been used. If any value is left unchanged, the program may produce
invalid outputs.
Understandability
When a numeric value appears in a program, its use is not always clear, especially when the
same value means different things in different places. #define statement is a preprocessor
compiler directive and is much more powerful.
A constant can be defined as follows:
#define symbolic-name value of constant
Example
#define PI 3.14159
#define MAX 100
Symbolic names are sometimes called constant identifiers.
Rules Apply to #define
1. Symbolic name have the same form as variable names.
2. No blank space between the pound sign‟#‟ and the word define is permitted.
3. ‟#‟ must be the first character in the line.
4. A blank space is required between #define and symbolic name and between the symbolic
name and value.
5. .#define statements must not end with a semicolon.
6. After definition, the symbolic name should not be assigned any other value within the
program using an assignment statement.
7. Symbolic names are NOT declared for data types. Its data type depends on the type of
constant.
8. #define statements may appear anywhere in the program but before it is referenced in the
program.
16
DECLARING A VARIABLE AS CONSTANT
We may like the value of certain variables to remain constant during the execution of a program.
We can achieve this by declaring the variable with the qualifier const at the time of initialization.
Example
const int class_size = 40;
This tells the compiler that the value of the int variable class_size must not be modified by the
program.
VARIABLE AS VOLATILE
The qualifier volatile is used to tell explicitly the compiler that a variable‟s value may be
changed at any time by some external sources (from outside the program).
volatile int date;
The value of date may be altered by some external factors. When we declare a variable as
volatile, the compiler will examine the value of the variable each time it is encountered to see
whether any external alternation has changed the value.
The value of a variable declared as volatile can be modified by its own program as well. If we
wish that the value must not be modified by the program while it may be altered by some other
process, we may declare the variable as both const and volatile. Example
volatile const int location=100;
OVERFLOW OF DATA
Problem of data overflow occurs when the value of a variable is either too big or too small for
the data type to hold. The largest value that a variable can hold also depends on the machine.
Since floating-point values are rounded off to the number of significant digits allowed, an
overflow normally results in the largest possible real value, whereas an underflow results in zero.
Integers are always exact within the limits of the range of the integral data types used. An
overflow is a serious problem may occur if the data type does not match the value of the
constant. C compiler does not provide any warning or indication of integer overflow. It simply
gives incorrect result. Programmer must take care for the type and range of input possible
-------
17
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
Arithmetic Operators
C provides all the basic arithmetic operators. The operator +,-,* and / all work same way as in
other languages. These can operate on any built-in data type allowed in C.
Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers, the expression
is called the integer expression, and the operation is called as integer arithmetic. Integer
arithmetic always results in an integer value. The largest integer value depends on the machine.
During integer division, if both the operands are of the same, the result is truncated towards zero.
If one of them is negative then the direction of truncation is implementation dependent.
6/7=0 and -6/-7=0
But -6/7 may be 0 or -1
18
Real Arithmetic
An arithmetic involving only real operands is called real arithmetic. A real operand may assume
values either in decimal notation or in exponent notation. Since floating point values are rounded
to the number of significant digits permissible, the final value is an approximation of the correct
result.
Example x,y and z are floats
x=6.0/7.0 = 0.857143
y=1.0/3.0 = 0.333333
z=-2.0/3.0= -0.666667
The operator modulo (%) cannot be used with real operands.
Mixed-mode Arithmetic
When one operand is real and the other is integer, the expression is called a mixed-mode
arithmetic expression. If either operand is of real type, then only the real operation is performed
and the result is always a real number.
Example
15 / 10.0 = 1.5
Where as,
15 / 10 = 1
Relational Operators
We often compare two quantities and depending on their relation, take certain decisions. These
comparisons can be done with the help of relational operators.
Example
a<b or 1<20
it Containing a relational operator is termed as a relational expression. The value of relational
expression is either true (non-zero) or false (zero) value.
10>20 is true
20<10 is false
C supports six relational operators
Syntax
ae-1 Relational_operator ae-2
19
ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables are
combination of them.
4.5 <= 10 TRUE
4.5 < -10 FALSE
10 < 7+5 TRUE
a+b=c+d TRUE only if the sum of a and b is equal to the sum of c and d.
When arithmetic expressions are used on either side of a relational operator, the arithmetic
operators have a higher priority over relational operators.
Logical Operators
C has the following 3 logical operators.
Logical Operators are used when we want to test more than one condition and make decisions. It
combines two or more relational expressions, is termed as a logical expression or compound
relational compression.
Example
a>b && x==10
This expression is true only if a>b is true and x==10 is true
20
Example
if (age>50 && salary<1000)
if (number<0 || number>100)
Assignment operators
Assignment operators are used to assign the result of an expression to a variable. Assignment
operator is „=„.
Syntax
v op = exp; or v = v op (exp);
where v is a variable, exp is an expression and op is a C binary arithmetic operator. The operator
op= is known as the shorthand assignment operator. Example
x+=y+1;
This is same as
x=x+ (y+1);
The shorthand operator += means „add y+1 to x‟ or increment x by y+1. For x=5 and y=2 means
x=5+(2+1);
x=5+3;
x=8;
Advantages
1. What appears on the left-hand side need not be repeated and therefore it becomes easier
to write
2. The statement is more concise and easier to read.
3. The statement is more efficient
21
Increment and decrement operators
The operator ++ adds 1 to the operand While -- subtracts 1 to the operand. Example
++m; or m++;
--m; or m--;
++m is equivalent to m=m+1; or m+=1;
--m is equivalent to m=m-1; or m-=1;
While ++m and m++ means the same thing when they form statements independently, they
behave differently when they are used in expressions on the right-hand side of an assignment
statement.
m=5;
y=m++;
The value of y and m are 6
m=5;
y=m++;
then, the value of y is 5 and m is 6.
Prefix Operator: It first adds 1 to the operand and then the result is assigned to the variable on
left.
Postfix Operator: It first assigns 1 the value to the variable on left and then increments the
operand.
The increment and decrement operators can be used in complex statements.
m=n++ -j+10;
n is incremented after the evaluation.
Rules
1. Increment and decrement operators are unary operators and they require variable as their
operands.
2. When postfix ++ (or --) is used with a variable in an expression, the expression is
evaluated first using the original value of the variable and then the variable is
incremented for decremented by one.
3. When prefix ++ (or --) is used in an expression, the variable is incremented or
decremented first and then the expression is evaluated using the new value of the
variable.
22
4. The precedence and associatively of ++ and – operators are the same as those unary +
and unary -.
Conditional operator
A ternary operator “? :” is available in C to construct expressions.
SYNTAX
Exp1? Exp2: Exp3;
Where exp1, exp2 and exp3 are expressions.
Exp1 is evaluated first. If it is non-zero (true) then, exp2 is evaluated and becomes the value
of the expression.
If exp1 is false, exp3 is evaluated and becomes the value of the expression.
a=10;
b=15;
x = (a>b) ? a : b ;
In Simple way,
if (a>b)
x = a;
else
x = b;
Bitwise operators
C has a distinction of supporting special operators known as bitwise operators for manipulation
of data at bit level. These operators are used for testing the bits, or shifting them right or left.
Bitwise may not be applied to float or double.
Operator Meaning
Special operators
C supports some special operators such as comma, size of, pointer operators (& and *) and
member selection operators (. and ->).
Comma Operator
Comma-linked list of expressions are evaluated left to right…and the value of right most
expression is the value of the combined expression. Example
Value = (x=10, y=5, x+y);
x will get 10 then y will get 5 then expression x+y is evaluated as 15.
sizeof operator
The sizeof is a compile time operator and, when used with operand, it returns the no. of bytes the
operand occupies. The operand may be a variable, a constant or a data type qualifier.
23
The sizeof operator normally used to determines the length of entities, arrays and structures
when their sizes are not known to the programmer. It is also use to allocate size of memory
dynamically during execution of the program.
Example
main( )
{
int sum;
float f;
printf( "The size of f %d\n The size of sum%d" ,size of(f), size of (sum) );
}
Output
The size of f 4
The size of sum 2
Arithmetic expression
An arithmetic expression is a combination of variables, constants, operators arranged as per the
syntax of the language. C can handle any complex mathematical expressions.
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable=expression;
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and the result then replaces the previous value of the variable on the left-hand
side. All variables used in the expression must be assigned values before evaluation is attempted.
x=a*b-c;
y=b/c*a;
z=a-b/c+d;
24
Precedence of arithmetic operators
An arithmetic operation without parentheses will be evaluated from left to right using the rules of
precedence of operators.
High priority * / %
Low priority + -
The basic evaluation includes left to right passes. During first pass higher priority operators are
applied as they encountered. During second pass from left to right the low priority operators are
applied as they are encountered.
x=a-b/3+c*2-1
when a=9, b=12 and c=3, the statement becomes
x=9-12/3+3*2-1
and is evaluated as follows
x = 9-12/3+3*2-1;
pass 1:
x = 9 – 4 + 3*2 –1;
x = 9 – 4 + 6 –1;
Pass 2:
x= 5 +6 –1;
x=11-1;
x=10;
Thus, when parentheses are used, the expressions within parenthesis assume highest priority.
x= 9 – 12 / (3+3) *(2-1)
Pass 0:
x=9 – 12 / 6 * (2-1)
x=9 – 12 / 6 * 1;
Pass 1:
x=9 – 2 * 1;
25
x=9 – 2;
Pass 2:
x=7;
Parentheses may be nested, and in such cases, evaluation of the expression will proceed outward
from the innermost set of parentheses. Example
x= 9 – (12 / (3+3) *)2-1=4
Rules
1. First, parenthesized sub expressions from left to right are evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub-expression
3. The precedence rule is applied in determining the order of application of operators in
evaluating sub-expressions.
4. The associativity rule is applied when two or more operators of the same precedence
level appear in the sub-expression.
5. Arithmetic expressions are evaluated from left to right using the rules of precedence.
6. When parentheses are used, the expressions within parentheses assume highest priority.
Type Conversions
There are two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit Type Conversion
C permits mixing of constants and different variables of different types of expression. C
automatically converts any intermediate values to the proper type so that the expression can be
evaluated without loosing any significance. The automatic conversion is known as implicit type
conversion.
If the operands are of difference types, the „lower type‟ is automatically converted to the „higher‟
type before the operation proceeds. The result is of the higher type. Example process
int i,x;
float f;
double d;
long int 1;
x = 1 / i + i *f - d
long float
long float
int float
float double double
26
Rules
All short and char are automatically converted to int; then
1. If one of the operands is long double, the other will be converted to long double and the
result will be long double.
2. Else, if one of the operands is double, the other will be converted to double and the result
will be double.
3. else, if one of the operands is float, the other will be converted to float and the result will
be float.
4. else, if one of the operands is unsigned long int, the other will be converted to unsigned
long int and the result will be unsigned long int.
5. else, if one of the operands is long int and the is unsigned int then
a. If unsigned int can be converted to long int, the unassigned int operand will be
converted as such and the result will be long int.
b. Else, both operands will be converted to unsigned long int and the result will be
unsigned long int
6. else, if one of the operands is long int, the other will be converted to long int and the
result will be long int.
7. else, if one of the operands is unsigned int, the other will be converted to unsigned int and
the result will be unsigned int.
C uses rule that, in all expressions except assignments, any implicit type conversions are made
from a lower size type to a higher size type.
Long double
Double
Conversion Hierarchy
float
Long int
Unsigned int
int
short char
The final result of an expression is converted to the type of the variable on the left of the
assignment sign before assigning the value to it.
1. float to int causes truncation of the fractional part
2. double to float causes rounding of digits
27
3. long int to int causes dropping of the excess higher order bits.
Explicit Conversion
The value of an expression can be converted to a different data type if desired. The process of
such a local conversion is known as explicit conversion or casting a value.
(type-name) expression
where, type-name is one of the standard C data types. Expression may be a constant, variable or
an expression.
Example
i=( int ) 7.5 Means, 7.5 is converted to integer by truncation.
i=( int )21.3/ ( int )4.5 Means, Evaluated as 21/4 and result would be 5.
x = (int) (y+0.5);
if y = 27.6 then,
y+0.5=28.1 and on casting the result becomes 28.
28
Example
if(x==10+15 && y<10)
The addition operator has a higher priority than the logical operator (&&) and the relational
operators (== and <). Therefore the addition is executed first. This is equivalent to
if(x==25 && y<10)
The next step is to determine whether x==25 and y<10. The operator < enjoys a higher priority
compared to ==, so y<10 is tester
Finally we get
if(FALSE && TRUE)
Rules
1. Precedence rules decide the order in which different operations are applied
2. Associativity rule decides the order in which multiple occurrences of the same level
operator are applied.
Mathematical Functions
There are more than twenty mathematical functions declared in <math. h>; here are some of the
more frequently used. Each takes one or two double arguments and returns a double.
Function Meaning
Trigonometric
acos(x) Arc cosine of x
asin(x) Arc sine of x
atan(x) Arc tangent of x
atan2(x,y) Arc tangent of x/y
cos(x) cosine of x
sin(x) sine of x
tan(x) tangent of x
Hyperbolic
cosh(x) Hyperbolic cosine of x
29
sinh(x) Hyperbolic sine of x
tanh(x) Hyperbolic tangent of x
Other functions
ceil(x) x rounded up to the nearest integer
exp(x) e to the x power (ex)
fabs(x) Absolute value of x
floor(x) x rounded down to the nearest integer
fmod(x) Remainder of x/y
log(x) Natural log of x,x>0
log10(x) Base 10 log of x,x>0
pow(x,y) X to the power y (xy)
sqrt(x) Square root of x,x>=0
30
Unit-II:
Reading and Writing a Character – Formatted Input, Output - Decision Making & Branching: if
statement – if else statement – nesting of if else statement – else if ladder – switch statement –
the ?: operator – goto statement – the while statement – do statement – the for statement – jumps
in loops.
Reading, processing and writing of data are three essential functions of a computer
program. Most programs take some data as input and display the processed data or result as
output. So, we need some methods that can read input and write output on a suitable input/output
medium.
Thus far we have seen two methods for providing data to the program variables. One is to
assign values to variables through the assignment statements such as x = 5; and so on. Another
method is to use input function scanf which can read data from a terminal and for outputting the
results we have used the function printf which sends the results out to a terminal.
All input/output operations are carried out through functions called as printf and scanf.
There exist several functions that have become standard for input and output operations in C.
These functions are collectively known as standard i/o library. Each program that uses standard
I/O function must contain the statement
#include<stdio.h>
READING A CHARACTER
The simplest of all input/output operations is reading a character from the standard input
and writing it to the standard output unit. Reading a single character can also be done by using
the function getchar().
The getchar() function is used to read a single character from the standard input unit. It
takes the following form:
variable_name = getchar();
Variable_name is a valid C name that has been declared as char type. When this
statement is encountered, the computer waits until a key is pressed and then assigns this
character as a value to the getchar() function.
31
Example
Since getchar is used on the right-hand side of an assignment statement, the character
value of getchar is assigned to the variable name on the left side.
For example:
char name;
name = getchar();
Will assign the character „H‟ to the variable name when we press the key A on the keyboard.
Here, We will assign the character „H‟ to the variable name when we press the key A on the
keyboard.
The getchar() function may be called successively to read the characters contained in a
line of text. The getchar() function returns any character keyed in. this include RETURN and
TAB also.
Other functions
We can also determine whether the character typed from the keyboard is a letter or digit.
These tests can be done with the help of the following functions:
isalpha(character)
isdigit(character)
These all character functions are contained in the file ctype.h and therefore the statement
#include<ctype.h>
Must be included in the program. There are many other similar functions contained in this file.
Writing a character
32
Like getchar, there is an analogous function putchar for writing characters one at a time
to the terminal. It takes the following form:
putchar(variable_name);
Example:
putchar(answer);
It will display the character Y on the screen. The statement putchar(„\n‟); would cause the
cursor on the screen to move to the beginning of the next line.
Example
#include<stdio.h>
#include<ctype.h>
main()
{
char alphabet;
printf(“Enter an alphabet”);
alphabet=getchar();
if(islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
}
Output
Enter an alphabet
Enter an alphabet
33
FORMATTED INPUT
Formatted input refers to an input data that has been arranged in a particular format. The
formatted data can be read with the help of scanf function. The general form of scanf is
scanf(“control string”,arg1,arg2….argn);
The control string specifies the field format in which the data is to be entered and the
arguments arg1,arg2...argn specifies the address of locations where the data are stored. Control
strings and arguments are separated by commas.
Control string contains field specification which directs the interpretation of input data.
Example
The field (or format) specifications, consisting of the conversion character %, a data type
character(or type specifier), and an optional number, specifying the field width.
Example
main()
{
int a, ,b, c, x, y, z;
int p, q, r;
printf(“Enter three integer numbers \n”);
scanf(“%d %*d %d”,&a, &b, &c);
printf(“%d %d %d \n \n”,a, b, c);
printf(“Enter two 4-digit numbers \n”);
scanf(“%2d %4d ”,&x, &y);
printf(“%d %d \n \n”,x, y);
printf(“%d %d \n \n”,x, y);
}
OUTPUT
Enter three integer numbers
123
1 3 –3577
34
Enter two 4-digit numbers
6789
4321
67
89
Unlike integer numbers, the field width of real numbers is not to be specified and
therefore scanf reads real numbers using simple specification %f for both the notations, namely,
decimal point notation and exponential notation.
If the number to be read is of double type, then the specification should be %lf instead of simple
%f.
Single character can be read from the terminal using getchar function. The same can be
achieved using the scanf function also. In addition, a scanf can input strings containing more
than one character.
%ws or %wc
%wc used to read a single character while %ws terminates the reading at the encounter of blank
space.
Some versions of scanf support the following conversion specifications for strings:
%[characters] and %[^characters]
The specification %[characters] means that only the characters specified within the
brackets are permissible in the input string. If the input string contains any other character, the
string will be terminated at the first encounter of such a character. The specification %
[^characters] does exactly the reverse. That is, the characters specified after the circumflex (^)
are not permitted in the input string.
35
It is possible to use one scanf statement to input a data line containing mixed mode data.
In such cases, it should be ensured that the input data items match the control specifications in
order and type.
Code Meaning
%c Read a single character
%d Read a decimal integer
%e Read a floating point value
%f Read a floating point value
%g Read a floating point value
%h Read a short integer
%i Read a decimal, hexadecimal,
or octal integer
%o Read an octal integer
%s Read a string
%u Read an unsigned decimal
%x integer
%[..] Read a hexa decimal integer
Read a string of word(s)
36
FORMATTED OUTPUT
It is highly desirable that the outputs are produced in such a way that they are
understandable and are in an easy-to-use form. It is therefore necessary for the programmer to
give careful consideration to the appearance and clarity of the output produced by program.
The printf statement provides certain features that can be effectively exploited to control
the alignment and spacing of print-outs on the [Link] general form of printf statement is
%wd
Format Output
Printf(“%d”,9876)
9 8 7 6
9 8 7 6
Printf(“%6d”,9876)
9 8 7 6
Printf(“%2d”,9876)
37
Output of Real Numbers
The output of real numbers may be displayed in decimal notation using the following
format specification: %w.p f
The integer w indicates the minimum number of positions that are to be used for the
display of the value and the integer p indicates the number of digits to be displayed after the
decimal point.
Format Output
Printf(“%7.4f”,y)
9 8 . 7 6 5 4
Printf(“%7.2f”,y) 9 8 . 7 7
9 8 . 7 7
Printf(“%- 7.2f”,y)
Printf(“%f”,y) 9 8 . 7 6 5 4
We can also display real numbers in exponential notation by using the specification
%w.p e
A single character can be displayed in a desired position using the format %wc
The character will be displayed right-justified in the field of w columns. We can make the
display left-justified by placing a minus sign before the integer w. The default value for w is 1.
Printing of Strings
38
To print string “NEW DELHI 110001”, containing 16 characters. %20s.
1 10 20
%20s
N E W D E L H I 1 1 0 0 0 1
%20.10s
N E W D E L H I
Ex:
Flag Meaning
- Output is left-justified with in the field. Remaining field will be blank
+ + or – will precede the signed numeric item
0 Causes leading zeros to appear
#(with o or x) Causes octal and hex items to be preceded by O and Ox
#(with e ,f or g) Causes a decimal point to be present in all floating point numbers, even
if it is whole number. Also prevents the truncation of trailing zeros in g-
type version
Computer outputs are used as information for analysing certain relationships between
variables and for making decisions. While the correctness depends on the solution procedure, the
clarity depends on the way the output is presented.
39
SCAJC11- Fundamentals of Computer & C Programming - I BCA : I Semester
Example
printf(“\n Output\n”);
C program is a set of statements which are normally executed sequentially in the order in
which they appear. We have a number of situations where we may have to change the order of
execution of statements based on the certain conditions or repeat a group of statements until
certain specified conditions are met.
a) If Statements
b) If-else statements
c) Else-if ladder Statements
d) Switch-case statements
If Statements
Syntax Entry
If(test expression)
True
{ Test
expression
Statement-block;
40
Next Statement
be skipped and the execution will jump to the statement-x.
Example
void main()
int n;
scanf(“%d”,&n);
if (n>10)
Output:
Enter a number:12
Number is greater
If – Else Statements
Syntax
If(test expression)
} True-block Statement;
41
else
False-block Statement;
If the test expression is true, then the true-block statements are executed. Otherwise the false-
block statements are executed. In either case, either true-block or false-block will be executed,
not both.
Entry
True False
Test
expression
True
False
Statement-
Statement-
block
block
Statement-x
Example
void main()
int n;
42
If (n%2==0)
else
printf(“odd number”); }
Output:
enter a number:121
odd number
Nested If Statements
When a series of decisions are involved, we may have to use more than one if….else
Syntax
43
If the condition-1 is false, the statement-3 will be executed; otherwise it continuous to perform
the second test. If the condition-2 is true, statement-1 will be executed; otherwise statement-2
will be executed and the control is transferred to the statement-x.
Example
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
printf("Enter three integers to check\n");
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("a is big");
}
else
44
{
printf("c is big");
}
}
else
{
if(b>c)
{
printf("b is big");
}
else
{
printf("c is big");
}
}
getch();
}
Output
Enter three integers to check
33 67 2
b is big
Else - If Ladder
When multiple decisions are involved, chain of if statement associated with each else. This
construct is known as else… if ladder.
if(condition 1)
statement1;
else if (condition2)
statement 2;
else if (condition 3)
statement 3;
else if (condition n)
statement n;
45
else
Default-statement
statement x;
The conditions are evaluated from the top downwards. As soon as a true condition is
found, the statement associated with it is executed with it is executed and the control is
transferred to the statement-x. When all the n conditions become false, then the final else
containing the default-statement will be executed.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i;
float marks[10], per=0, total=0;
clrscr();
printf("Enter number of subject: ");
46
scanf("%d",&n);
printf("Enter marks of %d subject: ",n);
for(i=0; i<n; i++)
{
scanf("%f",&marks[i]);
total=total+marks[i];
}
per=total/n;
printf("Percentage: %f % \n",per);
if(per>=85)
{
printf("A grade");
}
else if(per>=75 && per<85)
{
printf("B grade");
}
else if(per>=50 && per<75)
{
printf("C grade");
}
else if(per>=35 && per<50)
{
printf("D grade");
}
else
{
printf("Fail");
}
getch();
}
OUTPUT
47
Switch statement
Switch statement is used for complex programs when the number of alternatives
increases. The switch statement tests the value of the given variable against the list of case values
and when a match is found, a block of statements associated with that case is executed.
Syntax
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
…….
…….
default:
default-block;
break;
}
statement- x;
Rules
48
3. Block-1,block-2…. are statement lists and may contain zero or more statements.
4. Case labels end with a colon (:)
5. When the switch is executed, the value of the expression is successfully compared against
the values value-1, value-2,… If a case is found whose value matches with the value of
the expression, then the block of statements that follows the case are executed.
6. The break statement transfers the control out of the switch statement. That is two or more
case labels may belong to the same statements.
7. The default is an optional case. When present, it will be executed if the value of the
expression does not match with any of the case values. If not present, no action takes
place if all matches fail and the control goes to the statement-x.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
char choice;
int a,b,res=0;
clrscr();
printf("\n ADD:+\n SUB:-\n MUL:*\n DIV:/\n");
printf("\n Enter Operator: ");
scanf("%c",&choice);
printf("Enter First value: ");
scanf("%d",&a);
printf("\n Enter Second value: ");
scanf("%d",&b);
switch(choice)
{
case '+':
res=a+b;
printf("Addition: %d",res);
break;
case '-':
res=a-b;
printf("Subtraction: %d",res);
break;
case '*':
res=a*b;
printf("Multiplication: %d",res);
break;
49
case '/':
res=a/b;
printf("Division: %d",res);
break;
default:
printf("Enter Valid Operator!!");
}
getch();
}
OUTPUT
The ?: operator
The operator is a combination of ? and : and takes three operands. This operator is popularly
known as the conditional operator.
Syntax
Conditional expression?expression1:expression2
The conditional expression is evaluated first. If the result is non-zero expression1 is
evaluated and is returned as the value of the conditional expression. Otherwise, expression2 is
evaluated and its value is returned.
Example
#include <stdio.h>
int main()
{
int num;
printf("Enter the value ");
scanf("%d",&num);
((num%2)==0) ? printf("%d is even.",num) : printf("%d is odd.",num);
return 0;
}
50
Output
5 is odd
C supports the goto statement to branch unconditionally from one point of the program to
another. The goto requires a label in order to identify the place where the branch is to be made. A
label is any valid variable name and must be followed by a colon. The label is placed
immediately before the statement where the control is to be transferred.
Syntax
Forward jump: If the label: is placed after the goto label; some statements will be skipped and
the jump is known as a forward jump.
goto label;
label:
statement;
Backward Jump: If the label: is placed before the goto label; a loop will be formed and some
statements will be executed repeatedly and the jump is known as a backward jump.
label;
statement;
goto label:
Example
main()
{
51
double x,y;
read;
scanf(“%f”,&x);
if(x<0) goto read;
y=sqrt(x);
printf(“%f%f”,x,y);
goto read;
}
DECISION MAKING AND LOOPING
Depending on the position of the control statements in the loop, a control structure may
be classified either as an entry-controlled loop or as the exit-controlled [Link]-controlled
loop: The control statements are tested before the start of the loop execution. If the conditions
are not satisfied, then the body of the loop will not be executed.
Exit-controlled loop: The test is performed at the end of the loop and therefore the body is
executed unconditionally for the first time
52
Entry Entry
Test False
condition
Body of the loop
True
condition
True
The while is an entry–controlled loop statement. The test-condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test-
condition is once again evaluated and if it is true, the body is executed once again. This process
of repeated execution of the body continues until the test-condition finally becomes false and the
control is transferred out of the loop.
Syntax
while(test condition)
53
}
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int s=0,a,n;
clrscr();
printf("Enter the number");
scanf("%d",&n);
while(n>0)
{
a=n%10;
s=s+a;
n=n/10;
}
printf("\nSum of digits: %d\t",s);
getch();
}
Output
The do statement
In while loop the body of the loop may not be executed at all if the condition is not
satisfied at the very first attempt. On some occasions it might be necessary to execute the body of
the loop before the test is performed. Such situations can be handled with the help of the do
statement.
Syntax
do
54
{
body of the loop
}
while(test condition);
The program proceeds to evaluate the body of the loop first. At the end of the loop, the
test condition in the while statement is evaluated. If the condition is true, the program continues
to evaluate the body of the loop once again. This process continues as long as the condition is
true. When the condition becomes false, the loop will be terminated and control goes to after the
while statement.
Since the test-condition is evaluated at the bottom of the loop, the do…..while construct
provides an exit-controlled loop and therefore the body of the loop is always executed at least
once.
Example
#include<stdio.h>
void main()
{
int i=1;
do
{
printf("%d\n",i);
i++;
}
while(i<=5);
}
Output
1
2
3
4
5
The for loop is another entry-controlled loop that provides a more consist loop control structure.
55
Syntax
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,a = -1,b= 1,c;
clrscr();
printf("Enter the number\t");
scanf("%d",&n);
printf(“\n Fibonacci Series \n”)
for(i=0;i<n;i++)
{
c=a+b;
printf("%d\n",c);
a=b;
b=c;
56
}
getch();
}
Output
More than one variable can be initialized at a time and it can be separated by comma.
for(i=0,n=0;n<17;n++)
The multiple arguments in the increment section are possible and separated by commas.
for(n=1,m=50;n<=m;n++,m--)
The test condition may have any compound relation and the testing need not be limited
only to the loop control variable.
for(i=1;i<20 && sum<100;i++)
To use expressions in the assignment statements of initialization and increment sections
for(x=(m+n)/2;x>0;x=x/2)
Nesting of loops, that is, one for statement within another for statement, is allowed in C.
for(i=1;i<10;i++)
-----------
57
-----------
for(j=1;j!=5;j++)
-----------
-----------
-----------
-----------
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],i,j,n,temp;
clrscr();
printf("Enter the array boundary\n");
scanf("%d",&n);
printf("Enter %d array element\n",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Sorted Array\n");
for(i=1;i<=n;i++)
printf("%d\n",a[i]);
getch();
}
58
OUTPUT
59
Unit-III:
ARRAYS
ARRAYS
The fundamental data types (char, int, float and double) are very useful, they are
constrained by the fact that a variable of these types can store only one value at any given time.
Therefore, they can be used only to handle limited amounts of data. In many applications, we
need to handle large volume of data in terms of reading, processing and printing. To process such
large amounts of data, we need a powerful data type that would facilitate efficient storing,
accessing and manipulation of data items. C supports a derived data type known as array that can
be used for such applications.
Example
Definition
Example
Salary [10]
A list of items can be given one variable name using only one subscript and such a variable is
called a single-subscripted variable or a one dimensional array. The subscripts of an array can be
integer constants.
60
Example
If we want to represent a set of five numbers, say (35,40,20,57,19), by an array variable number,
then we may declare the variable number as follows
int number[5];
Number[0]
Number[1]
Number[2]
Number[3]
Number[4]
Number[0]=35;
Number[1]=40;
Number[2]=20;
Number[3]=57;
Number[4]=19;
Declaration of one-dimensional arrays
Arrays, must be declared before they are used so that the compiler can allocate space for
them in memory.
Syntax
type variable-name[size];
Where type can be any valid C data type, variable-name will be a valid C identifier and size
indicates the maximum number of elements that can be stored inside the array.
float height[50];
The C language treats character strings simply as arrays of characters. The size in a character
string represents the maximum number of characters that the string can hold.
Example
char name[10];
61
declares the name as a character array (string) variable can hold a maximum of 10 characters.
Suppose the value of name is “WELL DONE”, then the each character of the string is treated as
an element of the array name and is stored in the memory as follows:
„W‟
„E‟
„L‟
„L‟
„D‟
„O‟
„N‟
„E‟
„\0‟
When the compiler sees a character string, it terminates it with an additional null character. Thus,
the element name[10] holds the null character „\0‟
After an array is declared, its elements must be initialized. Otherwise, they will contain
“garbage”. An array can be initialized at either of the following stage:
1. At compile time
Syntax
Example
int number[3]={0,0,0};
will declare the variable number as an array of size 3 and will assign zero to each element. If the
number of values in the list is less than the number of elements, then only that many elements
will be initialized. The remaining elements will be set to zero automatically.
62
float total[5]={0.0,15.75,-10}
will initialize the first 3 elements to 0.0,15.75 and -10.0 and the remaining 2 elements to zero.
declares the name to be an array of five characters, initialized with the string “John” ending with
the null character.
An array can be explicitly initialized at run time. We can use the function scanf() to initialize an
array.
Example
int x[3];
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],i,j,n,temp;
clrscr();
printf("Enter the array boundary\n");
scanf("%d",&n);
printf("Enter %d array element\n",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Sorted Array\n");
63
for(i=1;i<=n;i++)
printf("%d\n",a[i]);
getch();
}
OUTPUT
TWO-DIMENSIONAL ARRAYS
The array which is used to represent and store data in a tabular form is called as 'two
dimensional array.' Such type of array specially used to represent data in a matrix form. A two
dimensional array can be think as a matrix consisting of number of rows and number of columns.
Syntax
type array-name[row-size][column-size];
Example
64
Column 1 Column 2 Column 3
Two-dimensional arrays may be initialized by following their declaration with a list of initial
values enclosed in braces.
int table[2][3]={0,0,0,1,1,1};
int table[2][3]= {
{0, 0, 0},
{1, 1, 1}
};
If the values are missing in an initialize, they are automatically set to zero.
Example
PROGRAM
#include<stdio.h>
#include<conio.h>
void main()
65
{
int a[10][10],b[10][10],d[10][10],r,c,i,j;
clrscr();
printf(“Enter the row and column\t”);
scanf(“%d%d”,&r,&c);
printf(“Enter the first matrix \n”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the second matrix\n”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&b[i][j]);
}
}
printf(“The Result matrix\n”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
d[i][j]=a[i][j]+b[i][j];
printf(“%d\t”,d[i][j]);
}
printf(“\n”);
}
getch();
}
66
OUTPUT
MULTIDIMENSIONAL ARRAY
C allows arrays of three or more dimensions. The exact limit is determined by the
compiler.
Syntax
Type array_name[s1][s2][s3]…s[m];
Example
int survey[3][5][12];
float table[5][4][5][3];
A string is a sequence of characters that is treated as a single data item. Any group of
characters defined between double quotation marks is a string constant.
67
Example
“well done”
Character strings are often used to build meaningful and readable programs. Common
operations on strings
1. Reading and Writing strings
2. Combining strings together
3. Copying one string to another
4. Comparing strings for equality
5. Extracting a position of a string
G O O D \0 \0 \0 \0 \0 \0
68
The scanf function automatically terminates the string that is read with a null characters
and therefore the character array should be large enough to hold the input string plus the null
character.
We can also specify the field width using the form %ws in the scanf statement for reading
a specified number of characters from the input string.
scanf(“%ws”,name);
Problems in this method
1. The width w is equal to or greater than the number of characters typed in. The entire
string will be stored in the string variables.
2. The width w is less than the number of characters in the string. The excess characters will
be truncated and left unread.
char name[10];
scanf(“%5s”,name);
The input string KRISHNA will be stored as
K R I S H \0 ? ? ?
69
Writing strings to screen
We have used extensively the printf function with %s format to print strings to the screen. The
format %s can be used to display an array of characters that is terminated by the null character.
printf(“%s”,name);
Features of %s specifications
1. When the field width is less than the length of the string, the entire string is printed.
2. The integer value on the right side of the decimal point specifies the number of characters
to be printed.
3. When the number of characters to be printed is specified as zero, nothing is printed.
4. The minus sign in the specification causes the string to be printed left-justified.
5. The specification %.ns prints the first n character of the string.
Example
main()
{
char country[15];
printf(“*123456789*”);
printf(“---------------“);
printf(“Enter the string”);
scanf(“%d”,country);
printf(“%15s”,country);
printf(“%5s”,country);
printf(“%15.6s”,country);
printf(“%-15.6s”,country);
printf(“%15.0s”,country);
printf(“%.3s”,country);
printf(“%s”,country);
}
Output
*123456789*
---------------
Enter the string United kingdom
United kingdom
United kingdom
United
United
United
Uni
70
United kingdom
strcmp() This function compares two strings identified by the arguments and has a value 0 if
they are equal. If they are not, it has the numeric difference between the first nonmatching
characters in the strings.
strcmp(string1,string2);
string1 and string2 may be string variables or string constants.
strcpy() The strcpy function works almost like a string-assignment operator and assigns the
contents of string2 to string1.
strcpy(string1,string2);
strlen() This function counts and returns the number of characters in a string.
n=strlen(string);
where n is an integer variable, which receives the value of the length of the string. The argument
may be a string constant. The counting ends at the first null character.
Example
71
#include <stdio.h>
#include<conio.h>
#include <string.h>
void main( )
{
char s1[30]="Hello";
char s2[30]="Welcome";
char s3[30];
clrscr();
printf("The first string:%s",s1);
printf("\nThe second string:%s",s2);
strcat(s1,s2);
printf( "\nString Concatenation = %s",s1);
printf( "\nString Length = %d",strlen(s1));
printf("\n String Comparison:");
if(strcmp(s1,s2) ==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
strcpy(s3,s2);
printf( "\nString Copy = %s",s3);
getch();
}
OUTPUT
72
strncpy(s1,s2,5);
This statement copies the first 5 characters of the source string s2 into the target string s1.
strncat() This is another concatenation function that takes three parameters. This will
concatenates the left-most n characters of s2 to the end of s1.
strncat(s1,s2,n);
strchr() This function locates the first occurrences of the character „m‟ in the string s1.
strchr(s1,‟m‟);
strrchr() This function locates the last occurrences of the character „m‟ in the string s1.
strrchr(s1,‟m‟);
73
Unit-IV:
USER-DEFINED FUNCTIONS
Need – Multi-function programs – elements of user defined functions – definition – return values
and their types – function calls, declaration, category – all types of arguments and return values –
nesting of functions – recursion – passing arrays, strings to functions – scope visibility and life
time of variables, Structures and Unions: Defining a Structure - declaring a structure variable –
accessing structure members – initialization – copying and comparing – operation on individual
members – array of structures – arrays within structures – structures within structures –
structures and functions – unions – size of structures – bit fields.
USER-DEFINED FUNCTIONS
C function can be classified into two categories, namely, library functions and user-
defined functions. main is an example of user-defined functions. printf and scanf are example of
user-defined function. The main difference between these two categories is that library functions
are not required to be written by us whereas a user-defined function has to be developed by the
user at the time of writing a program.
Every program must have a main function to indicate where the program has to begin its
execution. The program may become too large and complex and as a result the task of
debugging, testing and maintaining becomes difficult.
If a program is divided into functional parts, then each part may be independently coded
and later combined into a single unit. These independently coded programs are called
subprograms. In C such subprograms are referred to as Functions.
Advantages
1. In top-down modular programming style, the high level logic of the overall problem is
solved first while the details of each lower-level function are addressed later.
2. The length of a source program can be reduced by using functions at appropriate places.
3. It is easy to debug.
4. A function may be used by many other programs.
1. Function definition
2. Function call
3. Function declaration
74
Function Definition
A function definition, also known as function implementation shall including the following
elements:
1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements
6. A return statement
All the six elements are grouped into two parts, namely
Syntax
Function-name(argument list)
executable statement-1;
executable statement-2;
………
………
return(expression);
Function Header
Function header consists of three parts: the function type, the function name and the formal
parameter list.
The function Type: Specifies the type of value that the function is expected to return to
the program calling the function. If the return type is not explicitly specified, C will
assume that it is an integer type. If the function is not returning anything, then we need to
specify the return type as void
75
The function name: Any C identifier and therefore must allow the same rules of
formation as other variable names in C.
The parameter list declares the variable that will receive the data sent by the calling program.
They serve as input data to the function to carry out the specified task. They represent actual
input values they are referred to as formal parameters.
Example
int factorial(int n)
-----
----
Function Body
The function body contains the declarations and statements necessary for performing the
required task.
Example
76
or
return(expression); It returns the value of the expression
Function Calls
A function can be called by simply using the function name followed by a list of actual
parameters, if any, enclosed in parentheses.
Void main()
int a,b,c;
printf(“%d”,c);
Function Declaration
All functions in a C program must be declared, before they are invoked. A function declaration
consist of four parts.
1. Function type
2. Function name
3. Parameter list
4. Terminating semicolon
Syntax
Rules
77
8. when the declared types don‟t match with the types in the function definition, compiler
will produce an error.
Category of functions
When a function has no arguments, it does not receive any data from the calling function.
Similarly, it doesn‟t return any value. The calling function doesn‟t receive any data from the
called function. So, there is no communication between calling and called functions.
--------
Function 2()
--------- }
} No output
Example
#include<stdio.h>
#include<conio.h>
void add();
void main()
add();
78
getch();
void add()
int a, b, c;
Scanf(“%d%d”,&a,&b);
c=a+b;
printf(“%d”,c);
Sample output
25 20
45
The nature of data communication between the calling function and the called function with
arguments but no return value.
--------
Function 2(a)
--------- }
} No return
value
79
Example
#include<stdio.h>
#include<conio.h>
void main()
int a, b;
scanf(“%d%d”,&a,&b);
add(a,b);
getch();
int c;
c=x+y;
printf(“%d”,c);
Output
25 20
45
80
Arguments with return values
The function should receives a predefined form of inputs and outputs a desired value. Such
functions will have two way data communication between the calling and called functions.
--------
Function 2(a)
--------- }
} Function
result
Example
#include<stdio.h>
#include<conio.h>
void main()
int a, b, c;
Scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“%d”,c);
getch();
81
{
int c;
c=x+y;
return(c);
Output
25 20
45
There could be occasions where we may need to design functions that may not take any
arguments but return a value to the calling function.
--------
Function 2(a)
--------- }
} Function
result
Example
#include<stdio.h>
#include<conio.h>
void add();
void main()
82
{
c=add();
printf(“%d”,c);
getch();
void add()
int c;
int a, b, c;
scanf(“%d%d”,&x,&y);
c=x+y;
return(c);
Output
25 20
45
Nesting of function
C permits nesting of functions freely. main can call function1, which calls function2, which calls
function3,…. and so on. There is in principle no limit as to how deeply functions can be nested.
Example
#include<stdio.h>
#include<conio.h>
void fun1();
83
void fun2();
void main()
fun1();
getch();
void fun1()
printf(“Hai\t”);
fun2();
void fun2()
printf(“Welcome”);
Output
Hai welcome
RECURSION
A function that calls itself is known as recursive function and the process of calling
function itself is known as recursion in C programming.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,res;
84
clrscr();
printf("Enter the number\n");
scanf("%d",&n);
res=fact(n);
printf("The factorial of %d is %d",n,res);
getch();
}
int fact(int n)
{
int f;
if(n==1)
return(1);
else
f=n*fact(n-1);
}
Output
Recursive functions can be effectively used to solve problems where solution is expressed in
terms of successively applying the same solution to subsets of the problem.
To pass a one-dimensional an array to a called function, it is sufficient to list the name of the
array, without any subscripts, and the size of the array as arguments.
Function Declaration:
The function largest is defined to take two arguments, the array name and size of the array to
specify the number of elements in the array.
Function call: It will pass the whole array to the called function.
largest(a,n)
85
Example
main()
float value[4]={2.5,-4.75,1.2,3.67};
printf(“%f”,largest(value,4));
int i;
float max;
max=a[0];
for(i=1;i<n;i++)
if(max<a[i])
max=a[i];
return(max);
Output
-4.75
1.2
2.5
3.67
86
Rules
1. The function must be called by passing only the name of the array
2. In the function definition, the formal parameter must be an array type; the size of the
array does not need to be specified.
3. The function prototype must show that the argument is an array
Two-Dimensional Arrays
Example
int i,j;
double sum=0.0;
for(i=0;i<m;i++)
for(j=1;j<n;j++)
sum+=x[i][j];
return(sum/m*n);
The strings are treated as character arrays in C and therefore the rules for passing strings to
functions are very similar to those for passing arrays to functions.
Rules
1. The string to be passed must be declared as a formal argument of the function when it is
defined.
87
void display(char item_name)
---------
---------
3. A call to the function must have a string array name without subscripts as its actual
argument.
display(names);
The technique is used to pass data from one function to another is known as parameter passing
can be done in two ways
pass by value
pass by reference
Pass by Value: The values of actual parameters are copied to the variables in the parameter list
of the called function. The called function works on the copy and not on the original values of
the actual parameters. This ensures that the original data in the calling function cannot be
changed accidentally.
Pass by Pointers: The memory addresses of the variables rather than the copies of values are
sent to the called function. The called function directly works on the data in the calling function
and the changed values are available in the calling function for its use.
Pass by pointers method is often used when manipulating arrays and strings. This method is also
used when we require multiple values to be returned by the called function.
Example program
#include<stdio.h>
88
#include<conio.h>
void main()
int a, b, c;
Scanf(“%d%d”,&a,&b);
c=add(a,b);
add(int x, int y)
{ int z;
z=x+y;
return(z);
Sample output
25 20
In C not only do all variables have a data type, they also have a storage class. There are four
types of storage classes.
1. Automatic variables
2. External variables
3. Static variable
4. Register variable
Scope: It determines over what region of the program a variable is actually available for use.
89
Lifetime: It refers to the period during which a variable retains a given value during
execution of the program.
Automatic variable
Automatic variable are declared inside a function in which they are to be utilized. They are
created when the function is called and destroyed automatically when the function is exited,
hence the name automatic. Automatic variables are local to the function in which they are
declared. It is also known as local or internal variables.
A variable declared inside a function without storage class specifications is, by default, an
automatic variable.
Example
void function1(void);
void function2(void);
main()
int m=1000;
function2();
printf(“%d\n”,m);
void function1(void)
int m=10;
printf(“%d\n”,m);
void function2(void)
int m=100;
90
function1();
printf(“%d\n”,m);
Output
10
100
1000
External Variables
Variables that are both alive and active throughout the entire program are known as external
variables. They are also known as global variables. Unlike local variables, global variables can
be accessed by any function in the program. External variables are declared outside a function.
Example
int fun1(void);
int fun2(void);
int fun3(void);
int x;
main()
int x=10;
printf(“x=%d\n”,x);
printf(“x=%d\n”,fun1());
printf(“x=%d\n”, fun2());
printf(“x=%d\n”, fun3());
fun1(void)
91
x=x+10;
int fun2(void)
int x;
x=1;
return(x);
fun3(void)
x=x+10;
Output
x=10
x=20
x=1
x=30
Since all the functions in a program source file can access global variables, they can be used for
passing values between the functions.
Problems
The values of global variables which are sent to the called function may be changed
inadvertently by the called function.
Functions are supposed to be independent and isolated modules. This character is lost, if
they use global variables.
It is not immediately apparent to the reader which values are being sent to the called
function.
A function that uses global variables suffers from reusability.
This problem can be solved by declaring the variable with the storage class extern.
92
Example
main()
extern int y;
-------------
------------
func1()
extern int y;
-------------
------------
int y;
The external declaration of y inside the functions informs the compiler that y is an integer
somewhere else in the program.
Static variables
The value of the static variables persists until the end of the program. A variable can be declared
static using the keyword static
static int x;
static float y;
A static variable may be either an internal type or an external type depending on the place of
declaration.
Internal static variables are those which are declared inside the a function. The scope of internal
static variables extend up to the end of the function in which they are defined. Therefore, internal
static variables are similar to auto variables, except that they remain in existence throughout the
remainder of the program. Therefore, internal static variables can be used to retain values
93
between function calls. A static variable is initialized only once, when the program is compiled.
It is never initialized again.
Example
void stat(void)
main()
int i;
for(i=1;i<=3;i++)
stat();
void stat(void)
x=x+1;
printf(“x=%d”,x);
Output
x=1
x=2
x=3
Register Variable
We can tell the compiler that a variable should be kept in one of the machine‟s registers, instead
are keeping in the memory. Since a register access is much faster than a memory access, keeping
frequently accessed variables in the register will lead to faster execution of programs.
94
register int count;
ANSI standard does not restrict its applications to any particular data type, most compilers allow
only int or char variables to be placed in the register.
STRUCTURES
Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine data
items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member. The format of the struct statement is as follows −
95
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that
we wish to access. You would use the keyword struct to define variables of structure type. The
following example shows how to use a structure in a program −
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
96
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( [Link], "C Programming");
strcpy( [Link], "Nuha Ali");
strcpy( [Link], "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( [Link], "Telecom Billing");
strcpy( [Link], "Zara Ali");
strcpy( [Link], "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following result −
97
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Structures as Function Arguments
You can pass a structure as a function argument in the same way as you pass any other variable
or pointer.
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( ) {
/* book 1 specification */
strcpy( [Link], "C Programming");
strcpy( [Link], "Nuha Ali");
strcpy( [Link], "C Programming Tutorial");
Book1.book_id = 6495407;
98
/* book 2 specification */
strcpy( [Link], "Telecom Billing");
strcpy( [Link], "Zara Ali");
strcpy( [Link], "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the →
operator as follows −
struct_pointer->title;
Let us re-write the above example using structure pointer.
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( ) {
/* book 1 specification */
strcpy( [Link], "C Programming");
strcpy( [Link], "Nuha Ali");
100
strcpy( [Link], "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( [Link], "Telecom Billing");
strcpy( [Link], "Zara Ali");
strcpy( [Link], "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
Packing several objects into a machine word. e.g. 1 bit flags can be compacted.
Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers.
C allows us to do this in a structure definition by putting :bit length after the variable. For
example −
struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and a 9-bit
my_int.
C automatically packs the above bit fields as compactly as possible, provided that the maximum
length of the field is less than or equal to the integer word length of the computer. If this is not
the case, then some compilers may allow memory overlap for the fields while others would store
the next field in the next word.
102
UNION
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain
a value at any given time. Unions provide an efficient way of using the same memory location
for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union −
103
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
return 0;
}
When the above code is compiled and executed, it produces the following result −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
104
int main( ) {
data.i = 10;
data.f = 220.5;
strcpy( [Link], "C Programming");
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
[Link] : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the
value of str member is getting printed very well.
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.f = 220.5;
printf( "data.f : %f\n", data.f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
[Link] : C Programming
106
Unit-V:
POINTERS
POINTERS
A pointer is a derived data type in C. It is built from one of the fundamental data types available
in C.
Pointers contain memory addresses as their values. Memory addresses are the locations in the
computer memory where the program instructions and data are stored, pointers can be used to
access and manipulate data stored in the memory.
Benefits of Pointers:
1. Pointers are more efficient in handling arrays and data tables.
2. Pointers can be used to return multiple values from a function via function arguments.
3. Pointers permit reference to functions and thereby facilitating passing of functions as
arguments to other functions.
4. The use of pointer arrays two character strings result in saving of data space in memory.
5. Pointers allow C to support dynamic memory management.
6. Pointers provide an efficient tool for manipulating dynamic data structures such as
structures, linked list, queue, stacks and trees.
7. Pointers reduce length and complexity of programs.
8. They also increase the execution speed and reduce the program execution time.
The computer‟s memory is a sequential collection of storage cells. Each cell, commonly known
as a byte, has a number called address associated with it. Typically, the addresses are numbered
consequently, starting from zero. The last address depends on the memory size. A computer
system having 64K memory will have its last address as 65,535.
Memory cell
Memory Address
0
1
2
3
4
107
5
6
.
.
.
65535
This statement instructs the system to find a location for the integer variable quantity and
puts the value 179 in that location. Assume that the system has chosen the address location 5000
for quantity.
During execution of the program, the system always associates the name quantity with
the address 5000. To access the value 179 we use either the name quantity or the address 5000.
Since memory addresses are simply numbers, they can be assigned to some variables which can
be stored in memory, like any other variable. Such variables that hold memory addresses are
called pointers. A pointer is, therefore, nothing but a variable that contains an address which is a
location of another variable in memory.
Quantity Variable
Value
5000 Address
Since a pointer is a variable, its value is also stored in the memory in another location.
Suppose, we assign the address of quantity to a variable p.
Variable Address
Quantity 5000
108
P 5048
Pointer variable
Since the value of the variable p is the address of the variable quantity, we may access the
value of quantity by using the value of p and therefore, we say that the variable p „points‟ to the
variable quantity. Thus, p gets the name „pointer‟.
The actual location of a variable in the memory is system dependent and therefore, the address of
a variable is not known to us immediately. This can be done with the help of the operator &
available in C. The operator & immediately preceding a variable returns the address of the
variable associated with it.
Example
p=&quantity;
In C every variable must be declared for its type. Since pointer variable contain addresses that
belong to a separate data type, they must be declared as pointers before we use them.
Syntax
data-type *pt_name;
1. The asterisk (*) tells that the variable pt_name is a pointer variable
2. pt_name needs a memory location
3. pt_name points to a variable of type data_type
Example
int *p;
float *x;
Declaration styles
This (*) symbol can appear anywhere between the type name and the printer variable name.
int* p;
int *p;
int * p;
109
Initialization of pointer variables
The process of assigning the address of a variable to a pointer variable is known as initialization.
Once a pointer variable has been declared we can use the assignment operator to initialize the
variable.
Example
int quantity;
int *p;
p=&quantity;
It is also possible to combine the declaration of data variable, the declaration of pointer variable
and the initialization of the pointer variable in one step.
int x,*p=&x;
To access the value of the variable using the pointer is done by using another unary operator *
(asterisk), it is known as the indirection operator or dereferencing operator.
quantity=179;
p=&quantity;
n=*p;
When the operator * is placed before a pointer variable in an expression, the pointer returns the
value of the variable of which the pointer value is the address. *p returns the value of the
variable quantity, because p is the address of quantity.
Chain of pointers
p1 p2 p3
Here, the pointer variable p2 contains the address of the pointer variable p1, which points to the
location that contains the desired value. This is known as multiple indirections.
110
A variable that is a pointer to a pointer must be declared using additional indirection operator
symbols in front of the name.
int **p2;
This declaration tells the compiler that p2 is a pointer to a pointer of int type.
Pointer expression
Pointer variable can be used in expressions.
Example
y=*p1 * *p2;
sum=sum + *p1;
Example
void main()
{
int a,b,*p1,*p2,x;
a=12;
b=4;
p1=&a;
p2=&b;
x=*p1 * *p2 – 6;
printf(“a=%d, b=%d\n”,a,b);
printf(“x=%d\n”,x);
}
Output
a=12, b=4
x=42
111
POINTERS AND ARRAYS
When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of array in contiguous memory location. The base address is
the location of the first element (index 0) of the array. The compiler also defines the array name
as a constant pointer to the first element. Suppose we declare an array x as follows:
Suppose the base address of x is 1000 and assuming that each integer requires two bytes, the five
elements will be stored as follows:
The name x is defined as a constant pointer pointing to the first element x[0] and
therefore value of x is 1000, the location where x[0] is stored . That is, x = &x[0] =1000
*(*(a+i)+j) or *(*(p+i)+j)
The base address of the array a is &a[0][0] and starting at this address, the compiler allocates
contiguous space for all the elements, row-wise. That is, the first element of the second row is
placed immediately after the last element of the first row, and so on.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,sum=0,i,n;
int a[10];
clrscr();
printf("Enter the number of element");
scanf("%d",&n);
112
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
p=a;
for(i=0;i<n;i++)
{
sum=sum+*p;
p++;
}
printf("The sum is %d",sum);
getch();
}
g o O d \0
str
Example
main()
{
char *name;
int length;
char *cptr=name;
name=”DELHI”
printf(“%s”,name);
while(*cptr !=‟\0‟)
{
printf(“%c”,*cptr);
cptr++;
113
}
length=cptr-name;
printf(“Length of the string= %d”,length);
}
Output
DELHI
Length of the string=5
Arrays of pointer
One important use of pointers is in handling of a table of strings.
char name[3[25];
This says that the name is a table containing three names, each with maximum length of 25
characters. The total storage requirements for the name are 75 bytes.
114
exchange(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
Output
Before Exchange x=100 y=200
After Exchange x=200 y=100
Output
20
FILE MANAGEMENT IN C
115
A file is a place on the disk where a group of related data is stored.
Basic File Operation
1. Naming a file
2. Opening a file
3. Reading data from a file
4. Writing data to a file
5. Closing a file
There are two distinct ways to perform file operations in C
1. Low-level I/O and uses UNIX system calls
2. High-level I/O operation and uses functions in C‟s standard I/O library.
High Level I/O Functions
1. fopen() – Creates a new file, opens an existing file.
2. fclose() – Closes a file which has been opened.
3. getc() – Reads a character from a file.
4. putc() – Writes a character to a file.
5. fprintf() – Writes s set of data values to a file.
6. fscanf() – Reads a set of data values from a file.
7. getw() – Reads an integer from a file.
8. putw() – Writes an integer to a file.
9. fseek() – Sets the position to a desired point in a file.
10. ftell() – Gives the current position in the file.
11. rewind() – Sets the position to the beginning of a file.
When trying to open a file, one of the following things may happen:
1. When the mode is „writing‟, a file with the specified name is created if the file does not
exist. The contents are deleted, if the file already exists.
2. When the purpose is „appending‟, the file is opened with the current contents safe. A file
with the specified name is created if the file does not exist.
3. If the purpose is „reading‟, and if it exists, then the file is opened with the current
contents safe otherwise an error occurs.
FILE *p1,*p2;
p1=fopen(“data”,”r”);
p2=fopen(“odd”,”w”);
Closing a file
A file must be closed as soon as all operations on it have been completed. This ensures that all
outstanding information associated with the file is flushed out from the buffers and all links to
the file are broken. There is a limit to the number of files that can be kept open simultaneously,
closing of unwanted files might help open the required files and also the file has been reopen in a
different mode.
fclose(file_pointer);
117
Input/Output operations on files
1. getc() is used to read a character into a file.
Syntax
character_variable=getc(file_ptr);
Example
c=getc(fp2)
2. putc() is used to write a character into a file
Syntax
puts(character-var,file-ptr);
Example
putc(c,fp1);
3. getw() is used for reading a string from the file
Syntax
getw(file_ptr);
Example
getw(fp)
4. putw() is used to writing a character to a file
Syntax
putw(integer,file_ptr);
Example
putw(integer,fp);
Example
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1,*f2,*f3;
int number,i;
clrscr();
printf("Contents of DATA File\n");
f1=fopen("DATA","w");
for(i=1;i<=30;i++)
{
scanf("%d",&number);
if(number==-1)
118
break;
putw(number,f1);
}
fclose(f1);
f1=fopen("DATA","r");
f2=fopen("ODD","w");
f3=fopen("EVEN","w");
while((number=getw(f1))!=EOF)
{
if(number%2==0)
putw(number,f2);
else
putw(number,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("ODD","r");
f3=fopen("EVEN","r");
printf("Contents of ODD file\n");
while((number=getw(f2))!=EOF)
printf("%d\n",number);
printf("Contents of EVEN file\n");
while((number=getw(f3))!=EOF)
printf("%d\n",number);
fclose(f2);
fclose(f3);
getch();
}
OUTPUT
119
fscanf() and fprintf()
5. fprinf() is used to write a string to a file.
Syntax
fprintf(fp,”control string”,list);
Example
fprintf(f1,”%s%d”,name,age);
Example
void main()
{
FILE *fp;
char choice= „y‟;
char name[20];
int age;
float basic;
fp=fopen (“[Link]”, “w”);
if(fp= =NULL)
{
puts(“Cannot open file”);
exit();
}
while (choice = = „y‟)
{
printf(“\n” Enter name, age and basic salary \n”);
scanf(“\ %s%d %f,” name, &age, & basic);
fprintf(fp,”%s %d %f \n”,name, &age, &basic );
printf(“Another details(y/n)”);
fflush(stdin);
ch= getch() ;
}
fclose (fp);
}
120
5. fscanf() is used to read a string from the file.
Syntax
fscanf(fp,”control string”,list);
Example
fscanf(f1,”%s%d”,&name,&age);
Example
void main()
{
FILE* fp;
char name (40);
int age;
float basic;
fp=fopen(“[Link]”, “r”);
if (fp = = NULL)
{
puts(“Cannot open file”);
exit ();
}
while (fscanf(fp, “%s %d %f”, name, &age, &basic)!=EOF)
printf(“\n %s %d %f”, name,&age, &basic);
fclose(fp);
}
Error Handling During I/O operations
It is possible that an error may occur during I/O operations on a file. Typical error situation
include
1. Trying to read beyond the EOF mark.
2. Device overflow.
3. Trying to use a file that has not been opened. Trying to perform an operation on a file
when the file is opened for another type of operation.
4. Opening a file with an invalid filename.
5. Attempting to write to a write-protected file.
If we fail to check such read and write errors, a program may behave abnormally when an error
occurs.
121
feof() It can be used to test for an end of file condition. It takes a FILE pointer as its only
argument and returns a nonzero integer value if all of the data from the specified file has been
read, and returns zero otherwise. If fp is a pointer to file that has just been opened for reading,
then the statement
if(feof(fP)
printf(“End of data”);
would display the message “End of Data” on reaching the end of file condition.
ferror() ferror function reports the status of the file indicated. It also takes a FILE pointer as
its argument and returns nonzero integer if an error has been detected up to point, during
processing otherwise it returns zero.
if(ferror(fp)!=0)
printf(“An error has occurred”);
would print the error message, if the reading in not successful.
Example
void main()
{
char *filename;
FILE *fp1,*fp2;
int i,number;
fp1=fopen(“TEST”,”w”);
for(i=10;i<=100;i++)
putw(I,fp1);
fclose(fp2);
printf(“Input filename”);
open_file;
scanf(“%s”,filename);
if((fp2=fopen(filename,”r”)==NULL)
{
printf(“cannot open the file”);
printf(“Type filename again”);
goto open_file;
}
else
{
for(i=1;i<=20;i++)
{
number=getw(fp2);
if(feof(fp2))
122
{
printf(“Ran out of data”);
break;
}
else
printf(“%d”,number);
}
}
fclose(fp2);
}
Output
Input filename
TETS
Cannot open the file
Type filename again
TEST
10
20
30
40
50
60
70
80
90
100
Ran out of data.
ftell() It takes a file pointer and return a number of type long, that corresponds to the current
position. This function is useful in saving the current position of a file, which can be used later in
the program.
n=ftell(fp);
n would give the relative offset(in bytes) of the current position.
frewind() It takes a file pointer and resets the position to the start of the file.
123
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. This
function helps us in reading a file more than once, without having to close and open the file.
feek() it is used to move the file position to a desired location within the file.
fseek(file_ptr,offset,position);
file_ptr is a pointer to the file concerned, offset is a number or variable of long type, and position
is an integer number. The offset specifies the number of positions to be moved from the location
specified by position. The Position can take one of the three values
value meaning
0 Beginning of file
1 Current position
2 End of file
The offset is positive- move forward
The offset is negative- move backward
Operations of fseek()
Statement Meaning
fseek(fp,0L,0); Go to the beginning (like rewind)
fseek(fp,0L,1); Stay at the current position
fseek(fp,0L,2); Go to the end of the file, past the last character of the
file
fseek(fp,m,0); Move to (m+1) byte in the file
fseek(fp,m,1); Go forward by m bytes
fseek(fp,-m,1); Go backward by m bytes from the current position
fseek(fp,-m,2); Go backward by m bytes from the end.
Example
void main()
{
FILE *fp;
long n;
char c;
fp=fopen(“RANDOM”,”w”);
while((c=getchar())!=EOF)
putc(c,fp);
pritnf(“No of caharacters entered=%d”,ftell(fp));
fclose(fp);
fp=fopen(“RANDOM”,”r”);
n=0L;
124
while(feof(fp)==0)
{
fseek(fp,n,0);
printf(“position of %c is %d”,getc(fp),ftell(fp));
n=n+5L;
}
putchar(„\n‟);
fseek(fp,-1L,2);
do
{
putchar(getc(fp));
}
while(!fseek(fp,-2L,1));
fclose(fp);
}
Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ^Z
No of characters entered=26
Position of A is 0
Position of F is 5
Position of K is 10
Position of P is 15
Position of U is 20
Position of Z is 25
Position of is 30
ZYXWVUTSRQPONMLKJIHGFEDCBA
125
argv It is an argument vector and represents an array of character pointers that point to the
command line arguments.
The size of the array will be equal to the value of argc.
argv[0]PROGRAM; argv[1]X_FILE; argv[2]Y_FILE
Example
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
void main(int argc, char *argv[])
{
double deg_f, deg_c;
if (argc < 2)
{
printf("Usage: ftoc temperature\n");
exit(1);
}
deg_f = atof(argv[1]);
deg_c = (5. / 9.) * (deg_f - 32.);
printf("%f degrees Fahrenheit equals %f degrees Celsius\n", deg_f, deg_c);
getch();
}}
Output
50.00
50.00 degrees Fahrenheit equals 10.00 degrees Celsius
126