C Notes
C Notes
B.C.A. - I YEAR
DJA1C - PROGRAMMING IN C
(From the academic year 2016-17)
SYLLABUS
Unit I
C Declarations:- Introduction – Character Set – C tokens – Keywords and Identifiers –
Identifiers – Constants – Variables – Data types – Declaration of Variables – Declaration of
Storage Class – Assigning Values to Variables – Defining Symbolic Constants – Declaring
Variable as Constant .
Operators and Expressions:- Introduction – Arithmetic Operators – Relational Operators –
Logical Operators – Assignment Operators – Increment and Decrement Operators –
Conditional Operator – Bitwise Operators – Special Operators – Arithmetic Expressions –
Evaluation of Expressions – Precedence of Arithmetic Expressions.
Unit II.
Managing Input and Output Operations:- getchar( ) – putchar( ) – scanf( ) – printf( ).
Decision Making and Branching:- Introduction – Decision Making with IF Statement –
Simple IF statement – The IF…Else Statement – Nesting of IF…Else Statements – The ELSE
IF ladder – The Switch Statement – The ?: Operator – The GOTO statement.
Decision Making and Looping:- Introduction – The WHILE Statement – The DO Statement
– The FOR statement – Jumps in Loops.
Unit III.
Arrays :- Introduction – One-dimensional arrays – Declaration of One-dimensional arrays –
Initialization of One-dimensional arrays - Two-dimensional arrays – Initialization of Two-
dimensional arrays – Multi-dimensional arrays.
Character Arrays and Strings:- Introduction – Declaring and Initializing String Variables –
Reading Strings from Terminal – Writing Strings to Screen – String Handling Functions.
Unit IV.
User-Defined functions:- Introduction – Need for User-defined functions – Definition of
functions – Return Values and their Types – Function Calls – Function Declaration –
Category of functions – No Arguments and No return values – Arguments but No return
Values – Arguments with return values – No arguments but a return a value – Recursion –
Passing Arrays to functions – The Scope, Visibility and lifetime of a variables.
Structures and Unions:- Introduction – Defining a Structure – Declaring Structure Variables
– Accessing Structure Members – Structure Initialization – Arrays of structures – Structures
and functions – Unions.
Unit V
Pointers:- Introduction – Understanding pointers – Accessing the Address of a Variable –
Declaring Pointer Variables – Accessing a variable through its pointer – Pointer Expressions –
Pointers as function arguments.
File Management in C:- Introduction – Defining and Opening a file – Closing a File –
Input/Output Operations on files – Error Handling During I/O Operating .
Text Book:
Programming in ANSI C – 6th Edition by E Balagurusamy – Tata McGraw Hill
Publishing Company Limited.
Reference Book:
Computer Programming in C – V. Rajaraman-PHI
C-DECLARATIONS
INTRODUCTION
HISTORY OF C
C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories
in 1972. C is highly portable. „This means that C programs written for one computer can be
run on another with little or no modification. Portability is important if we plane to use a new
computer with a different operating system. C language is well structured in terms of function
modules or blocks. This modular structure makes program debugging, testing and
maintenance easier.
There are some variables that are used in more than one function. Such variables are
called global variables and are declared in the global declaration section that is outside of all
the functions. This section also declares all the user-defined functions.
The subprogram section contains all the user-defined functions that are called in the
main function. User-defined functions are generally placed immediately after the main
function, although they may appear in any order.
All sections, except the main function section may be absent when they are not
required.
REVIEW QUESTIONS
CHARACTER SET
The characters that can be used to form words, numbers and expressions form C set.
The characters in C are grouped into the following categories:
1. Letters
2. Digits
C TOKENS
All keywords have fixed meanings and these meanings cannot be changed. All
keywords must be written in lowercase. Identifiers refer to the names of variables, functions
and arrays. These are user-defined names and consist of a sequence of letters and digits, with
a letter as first character.
CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a
program.
Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers,
namely, decimal integer, octal integer and hexadecimal integer.
An octal integer constant consists of any combination of digits from the set 0 through
7, with a leading 0. Some examples of octal integer are:
Manonmaniam Sundaranar University, Directorate of Distance & Continuing Education, Tirunelveli.
4
037 0 0435 0551
Real constants
Numbers containing fractional parts like 17.548 are called real (or floating point)
constants are:
A single character constant (or simply character constant) contains a single character
enclosed within a pair of single quote marks.
String Constants
A string constant is sequence of characters enclosed in double quotes. The characters may be
letters, numbers, special characters and blank space. Examples are:
C supports some special backslashes character constants that are used in output
functions each one of them represents one character, although they consist of two characters.
These characters combinations are known as escape sequences.
Constant Meaning
VARIABLES
DATA TYPES
Table Size and Range of Basic Data Types on 16- bit Machines
Integers are whole numbers with a range of values supported by a particular machine.
Integers occupy one word of storage C has three classes of integer storage, namely short int,
int, and long int, in both signed and unsigned forms. Short int represents fairly small integer
values and requires half the amount of storage as a regular int number uses. Unlike signed
integers, unsigned integers use all the bits for the magnitude of the number and are always
positive. Therefore, for a 16 bit machine, the range of unsigned integer numbers will be from
0 to 65,535.
Floating point (or real) numbers are stored in 32 bits (on all 16 bit and 32 bit
machines), with 6 digits of precision. Floating point numbers are defined in C by the keyword
float. When the accuracy provided by a float number is not sufficient, the type double can be
used to define the number. A double data type number uses 64 bits giving a precision of 14
digits. These are known as double precision numbers. To extend the precision further, we may
use long double which uses 80 bits.
Void Types
The void type has no values. This is usually used to specify the type of functions. The
type of a function is 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 (one byte) to internal storage. The qualifier signed or unsignend may
be explicitly applied to char. While unsigned chars have values between 0 and 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:
The syntax
For example,
int count ;
double ratio ;
Some examples
The enumerated variables v1,v2,…vn can only have one of the values value1,
value2,…valuen.
An example:
week_st = Monday ;
if (week_st == Tuesday)
week_end = Saturday ;
Variables in C can have not only data type but also storage class that provides
information about their location and visibility. The storage class decides the portion of the
program within which the variables are recognized.
C provides a variety of storage class specifies that can be used to declare explicitly the
scope and lifetime of variables. There are four storage class specifies (auto, register, static,
and extern) whose meanings are given in Table 2.10.
Static and external (extern) variables are automatically initialized to zero. Automatic
(auto) variables contain undefined values (known as „garbage‟) unless they are initialized
explicitly.
auto Local variable known only to the function in which it is declared. Default
is auto.
static Local variable which exists and retains its value even after the control is
transferred to the calling function.
Assignment Statement
Variable_name = constant;
Balance = 75.84 ;
Yes = „x‟ ;
Another way of giving values to variables is to input data through keyboard using the
scanf function.
The control sting contains the format of data being received. The ampersand symbol &
before each variable name is an operator that specifies the variable name‟s address.
We often use certain unique constants in a program. These constants may appear
repeatedly in a number of places in the program. One example of such a constant is 3.142,
Valid examples
# define PASS_MARK 50
#define p1 3.14159
Symbolic names are sometimes called constant identifiers. The following rules apply to a
#define statement which define a symbolic constant:
1. Symbolic names have the same form as variable names. (Symbolic names are written
in CAPITALS to visually distinguish them from the normal variable names, which are
written in lowercase letters. This is only a convention, not a rule.
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 between the symbolic name and constant.
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 by using an assignment statement. For example, STRENGTH = 200; is
illegal.
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 (the usual practice is to place them in the beginning of the program).
2.10 DECLARING A VARIABLE AS CONSTANT
We may like value of certain variables to remain constant during the execution
of a program.
Example:
Manonmaniam Sundaranar University, Directorate of Distance & Continuing Education, Tirunelveli.
11
Const int class_size = 40;
Const is a new data type qualifier defined by ANSI standard. This tells the compiler
that the value of the int variable class_size must not be modified by the program.
void main ( )
{
int a, s :
print f ( enter s value \n”);
scanf ( % d”,&s);
print f ( S = % d\ n"" ,s);
a = s * s;
Print f ( area of square = % d\n”, a);
}
2. Area of a triangle
a = ½ bh
Void main ( )
{
int b, h ;
float a ;
print f ( enter b, h value \n”) ;
scan f ( %d% d” , &b, &h) ;
print f ( b = % d h = % d / n” , b, h) ;
a = (0.5) * b * h ;
printf (“area of a triangle = % f \ n” , a );
}
3. Volume of a Cone V = 1/3 r2h
void main ( )
{
int r, h ;
Just Remember
Do not use the underscore as the first character of identifiers (or variable names)
because many of the identifiers in the system library start with underscore.
Use only 31 or less characters for identifiers. This helps ensure portability of
programs.
Do not use keywords or any system library names for identifiers.
Do not give any space between # and define.
Review Questions
Programming Exercises
1. Arithmetic operators
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
Arithmetic Operators
Operator Meaning
/ Division
% Modulo division
Integer division truncates any fractional part. The modulo division operation produces
the remainder of an integer division.
Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression, and the operation is called integer arithmetic.
Integer arithmetic always yields an integer value.
a – b = 10
a + b = 18
a X b = 56
a / b = 3 (decimal part truncated)
a % b = 2 (remainder of division)
Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real
operand any assume values either in decimal or exponential notation.
Mixed-mode Arithmetic
When one of the operands is real and the other is integer, the expression is called a
mixed-mode arithmetic expression. If either operand is of the real type the result is always a
real number.
15/10.0 = 1.5
We often compare two quantities and depending on their relation, take certain
decisions. An expression such as
A < b 1 < 20
C supports six relational operators in all. These operators and their meanings are
shown in Table
Operator Meaning
== is equal to
!= is not equal to
A simple relation expression contains only one relational operator and takes the following
form:
In addition to the relational operators, C has the following three logical operators.
|| meaning logical OR
The logical operators && and || are used when we want to test more than one condition and
make decisions.
An expression of this kind, which combines two or more relational expressions, is termed as a
logical expression or a compound relational expression.
ASSIGMENT OPERATORS
v op= exp;
Where V us a variable, exp is an expression and op is a C binary arithmetic operator.
The operator op= is known as the shorthand assignment operator.
An example
x += y+1;
This is same as the statement
x = x + (y+1);
For example
a = 10;
b = 15;
x = (a > b) ? a : b;
BITWISE OPERATORS
C has special operators known as bitwise operators for manipulation of data at bit level.
These operators are used for testing the its, r shifting them right or left. Bitwise operators
may not be applied to float or double.
Operator Meaning
│ bitwise OR
^ bitwise exclusive OR
SPECIAL OPERATORS
The comma operator can be used to link the related expressions together.
The sizeof is a compile time operator and, when used with an operand, it returns the
number of bytes the operand occupies. The operand may be a variable, a constant or a data
type qualifier.
ARITHMETIC EXPRESSIONS
EVALUATION OF EXPRESSISSONS
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.
Examples:
x = a * b – c;
z = a – b / c + d;
An arithmetic expression without parentheses will be evaluated from left to right using
the rules of precedence of operators. There are two distinct priority levels of arithmetic
operators in C:
High priority * / %
Low priority + −
The basic evaluation procedure includes „two‟ left-to-right passes through the
expression. During the first pass, the high priority operators (if any) are applied as they are
encountered. During the second pass, the low priority operators (if any) are applied as they are
encountered.
Example:
x = a-b/3 + c*2−1
9−12/(3+3)*(2−1)
Whenever, parentheses are used, the expressions within parentheses assume highest
priority, if two or more sets of parentheses appear one after another as shown above, the
expression contained in the left-most set is evaluated first and the right-most in the last.
Answer is 7
Precedence rules decides the order in which different operators are applied
Associability rule decides the order in which multiple occurrences of the same level
operator are applied.
WRITING A CHARACTER
Like getchar, there is an analogous function putchar for writing characters one
at a time to the terminal
Putchar (variable_name);
Answer = „y‟;
Putchar (answer);
Putchar („/n‟);
Would cause the cursor on the screen to move to the beginning of the next line.
FORMATTED INPUT
Formatted input refers to an input data that has been arranged in a particular
format. 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 specify the address of locations where the data
is stored. Control string and arguments are separated by commas.
Manonmaniam Sundaranar University, Directorate of Distance & Continuing Education, Tirunelveli.
24
Control string (also known as format string) contains field specifications,
which direct the interpretation of input data. It may include:
Field (or format) specifications, consisting of the conversion character %, a
data type character (or type specifier), and an optional number, specifying the
field width.
Blanks, tabs, or newlines.
Blanks, tabs and newlines are ignored. The data type character indicates the type of
data that is to be assigned to the variable associated with the corresponding argument.
The field width specifier is optional.
%[characters]
%[^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. The reading of the string
will be terminated at the encounter of one of these characters.
Code Meaning
The following letters may be used as prefix for contain conversion characters.
FORMATTED OUTPUT
The printf statement provides certain features that can be effectively exploited
to control the alignment and spacing of print-outs on the terminals. The general form of printf
statement is:
The control string indicates how many arguments follow and what their types are. The
arguments arg1, arg2, ….., argn are the variables whose values are formatted and printed
according to the specifications of the control string. The arguments should match in number,
order and type with the format specifications.
Just Remember
While using getchar function, care should be exercised to clear any unwanted
characters in the input stream.
Review Questions
(a) The purpose of the header file <studio.h> is to store the programs created by the users.
(b) A the input list in a scannf statement can contain one or more variables.
(c) When an input stream contains more data items than the number of specifications in a
scanf statement, the unused items will be used by the next scanf call in the program.
(d) The print list in a printf statement can contain function calls.
Wrote a program to read three integers from the keyboard using one scanf statement and
output them on one line using:
1. If statement
2. Switch statement
3. Conditional operator statement
4. Goto statement
if (test expression)
1.Simple if statement
2. if…..else statement
4. else if ladder.
if (test expression)
Statement-block;
Statement-x;
The if….. else statement is an extension of the simple if statement. The general form is
if the test expression is true, then the true-block statement(s), immediately following the if
statements are executed; otherwise, the false-block statement(s), immediately following the if
statements are executed; otherwise, the false-block statement(s) are executed. In either case,
either true-block of false-block will be executed, not both.
True False
test
expression
?
?n
True-block False-block
statement statement
statement
statement - x
When a series of decisions are involved, we may have to use more than one if…else
statement in nested form if the condition-1 is false, the statement-s will be executed;
otherwise it continues to perform the second test. If the condition-2 is true,
A multipath decision is a chain of ifs in which the statement associated with each else
is an if.
This construct is known as the else if ladder. The conditions are evaluated from the top
(of the ladder), downwards. As soon as a true condition is found, the statement associated
with it is executed and the control is transferred to the statement-x (skipping the rest of the
C has a built-in multiway decision statement known as a switch. The switch statement
tests the value of a given variable (or expression) against a list of case values and when a
match is found, a block of statements associated with that case is executed. The general form
of the switch statement is as shown below:
Switch (expression)
Case value-1 :
Block-1
Break;
Case value-2 :
block-2
break;
…..
…..
Default:
Default-block
break;
Statement-x
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 statement, transferring the control to the statement-x
following the switch.
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.
THE ? : OPERATOR
The C language has an operator, useful for making two-way decisions. This operator is
a combination of? and :, and takes three operands. This operator is popularly known as the
conditional operator. The general form of use of the conditional operator is as follows:
flag = (x < 0) ? 0 : 1;
C supports the goto statement to branch unconditionally from one point to another in
the program there may be occasions when the use of go to might be desirable.
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. The general forms of
goto and label statements are shown below:
Just Remember
Programming Exercises
Write a program to determine whether a given number is „odd‟ or „even‟ and less than 200
that are divisible by 7
Write a program to find the number of and sum of all integers greater than 100 and less than
200 that are divisible by 7
INTRODUCTION
LOOP
Syntax
i) For
{
body of loop
}
ii) While
while (condition)
{
Manonmaniam Sundaranar University, Directorate of Distance & Continuing Education, Tirunelveli.
33
body of loop
}
iii) do while
do
{
body of loop
} while (condition) ;
Examples
Area of Square :
For
include < stdio.h >
include < conio.h >
Void main ( )
{
int a, s, i, n ;
clr scr ( ) ;
Print f ( enter no. of times \ n” ) ;
scan f ( % d” , & n) ;
for ( i = o ; i < n ;i = i + 1)
{
print f ( enter s value \n” ) ;
scanf ( % d”, &s) ;
a=s*s;
Print f ( area = % d” , a ) ;
}
}
while
void main ( )
{
int a, s, n, i;
Manonmaniam Sundaranar University, Directorate of Distance & Continuing Education, Tirunelveli.
34
Print f ( enter no of times \ n ) ;
scan f ( % d”, & n) ;
i = o; / * initial condtion * /
while i < n / terminating condition * /
{
scan ( % d”, &s)
a = s * s;
print f ( area = % d” , s );
i = i + 1; /* increment condition* /
}
}
do … while
void main ( )
{
int a, s, i, n;
printf ( enter no of times \ n”)
scanf ( % d” , & n) ;
i = o;
do
{
scanf ( % d” , & s ) ;
a = s * s;
printf ( area = % d”,a) ;
i = i + l;
} while (i < n) ;
}
While loop is executed only if the condition is true. If the condition is false, the loop
will not be executed at all.
Do while loop is executed then the condition is checked. If the condition is true, the
loop will be executed again. If the condition is false, the loop will not be executed.
Manonmaniam Sundaranar University, Directorate of Distance & Continuing Education, Tirunelveli.
35
(i.e)
Sum of digits
Void main ( )
{
long int n;
int n1, s = 0 ;
clr scr ( ) ;
print f ( enter digit \n” ) ;
scanf ( % ld”,& n);
print f ( % ld” , n) ;
while (n ! = 0)
{
n1 = n% 10 ;
s = s + n1 ;
n = n/10 ;
}
Print f ( sum of digits = % d \ n”,s);
NOTE :
The entry-controlled and exit-controlleld loops are also known as pre-test and post-test loops
respectively.
Sentionel Loops
Based on the nature of control variable and the kind of value assigned to it for testing
the control expression, the loops may be classified into two general categories:
1. Counter-controlled loops
2. Sentinel-controlled loops
An early exit from a loop can be accomplished by using the break statement or the
goto statement. When a break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following the loop. When
the loops are nested, the break would only exit from the loop containing it. That is, the break
will exit only a single loop.
During the loop operations, it may be necessary to skip a part of the body of the loop
under certain conditions. Like the break statement, C supports another similar statement.
However, unlike the break which causes the loop to be terminated, the continue, as the name
implies, causes the loop to be continued with the next iteration after skipping any statements
in between. The continue statement tells the compiler, “SKIP THE FOLLOWING
STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”. The format of the
continue statement is simply.
continue;
We can jump out of a loop using either the break statement or goto statement. In a
similar way, we can jump out of a program by using the library function exit().
The exit()
Void main ( )
{
long int n, s = o ;
int n1 ;
print f ( enter the no\n”) ;
scan f ( % ld” , & n) ;
print f ( % ld” , n) ;
while (n ! = 0)
{
n1 = n % 10;
S = S * 10 + n1;
n = n / 10 ;
}
print f (“reversed no. = % ld” , s) ;
}
Nested Loop
A loop within another loop is known as nested loop.
Syntax
For initial; terminating ; increment /
condition condition decrement
{
For ( i c ; t c ; in / de)
{
body of loop
}
eg. :
void main ( )
{
int i , j ;
For ( i = 0 ; i < 3 ; i + +)
{
for ( j = 0 ; i < 2 ; i ++)
{
print f ( Hello \n”) ;
}
}
}
Just Remember
Review Questions
(a) The do…while statement first executes the loop body and then evaluate the loop control
expression.
(b) The number of times a control variable is updated always equals the number of loop
iterations.
(a) In an exit-controlled loop, if the body is executed n times, the test condition is evaluated
……….. times.
(d) In a counter-controlled loop, variable known as …… is used to count the loop operations.
Use of goto should be avoided. Explain a typical example where we find the application of
goto becomes necessary.
Programming Exercises
Given a number, write a program using while loop to reverse the digits of the number. F or
example, the number
12345
Should be written as
54321
(Hint: Use modulus operator to extract the last digit and the integer division by 10 to get the
n-1 digit number from the n digit number.)
The factorial of an integer m is the product of consecutive integers from 1 to m. That is,
factorial m = m! = m x (m-1) x ….. x 1.
Write a program to compute the sum of the digits of a given integer number.
ARRAYS
Arrays
declaration
eg.
Types of Arrays
1. 1-d array :
2. 2-d array :
void main ( )
for ( i = 0 ; i < n ; i + +)
scanf ( % d” , &a[i] ) ;
Addition of 2 matrices
Void main ( )
for ( i = o ; i < p ; i + +)
for ( i = o ; i < p ; i + +)
print f ( \ n”) ;
print f ( \n”) ;
print f ( \ n”) ;
At compile time
At run time
We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared. The general form of initialization of arrays is:
The values in the list are separated by commas. For example, the statement
An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays.
if I < 50
else
sum[i] = 1.0;
MULTI-DIMENSIONAL ARRAYS
C allows arrays of three or more dimensions. The exact limit is determined by the
compiler. The general form of a multi-dimensional array is
The array survey may represent a survey data of rainfall during the last three years
from January to December in five cities.
We need to specify three things, namely, name, type and size, when we declare an
array.
Always remember that subscripts begin at 0 (not 1) and end at size -1.
Be aware of the difference between the “kth element” and the “element k”. The kth
element has a subscript k-1, whereas the element k has a subscript of k itself.
Referring a two-dimensional array element like x[I,j] instead of x[i][j] is a compile
time error.
During initialization of multi-dimensional arrays, it is an error to omit the array size
for any dimension other than the first.
Review Questions
(a) The variable used as a subscript in an array is popularly known as …………. Variable.
(c) An array created using malloc function at run time is referred to as ……….array.
main ( )
float y [ ] ;
……
INTRODUCTION
A string is a sequence of characters that is treated as a single data item. Any group of
characters (excepted double quote sign) defined between double quotation marks is a string
constant. Example:
Character strings are often used to build meaningful and readable programs. The
common operations performed on character strings include:
C does not support strings as a data type. However, it allows us to represent strings as
character arrays.
char string_name[size];
char city[10];
char name[30;]
char city [9]={„N‟, „E‟, „W‟, „ „, „Y‟, „0‟, „R‟, „K‟, „/0‟};
The familiar input function scanf can be used %s format specification to read in a string of
characters. Example:
char address[10]
scanf(“%s”, address);
The problem with the scanf function is that it terminates its input on the first white
space it finds. A white space includes blanks, tabs, carriage returns, form feeds, and new lines.
The scanf function automatically terminates the string that is read with a null character
and therefore the character array should be large enough to hold the input string plus the null
character.
gets()
gets(str);
str is variable declared properly. It reads characters into str from the keyboard until a
new-line character is encountered and then appends a null character to the string.
gets (line);
The printf function with % format is used to print strings to the screen.
For example:
Printf(“%s”, name);
We can use this putcher() function repeatedly to output a string of characters stored in an
array using a loop. Example.
more convenient way of printing string values is to use the function puts declared in the
header file (stdio.h). This is a one parameter function and invoked as under:
puts ( str );
Where str is a variable containing a string value. This prints the value of the string variable str
and then moves the cursor to the beginning of the next line on the screen. For example, the
program segment.
char line [80];
gets (line);
puts (line);
Reads a line of text from the keyboard and displays it on the screen.
STRING-HANDLING FUNCTIONS
The C library supports a large number of string-handling functions that can be used to
carry out many of the string manipulations the most commonly used string handling
functions.
The strcat function joins two strings together. It takes the following form
strcat(string1, string2);
String1 and string2 are character arrays. When the functions strcat is executed, string2 is
appended to string1. It does so removing the null character at the end of string1 and placing
string2 from there. The string at string2 remains unchanged.
The strcmp 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. It takes the form:
Strcmp(string1, string2);
The strcpy function works almost like a string-assignment operator. It takes the form:
strcpy(string1, string2);
And assigns the contents of string2 to sting1. String2 may be a character array variable of a
string constant.
This function counts and returns the number of characters in a string. It takes the form
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.
Character constants are enclosed in single quotes and string constants are enclosed in
double quotes.
Using a string variable name on the left of the assignment operator is illegal.
Do not forget to append the null character to the target string when the number of
characters copied is less than or equal to the source string.
Be aware the return values when using the functions strcmp and strncmp for
comparing strings.
The header file <string.h> is required when using string manipulation functions.
Review Questions
a) When initializing a string variable during its declaration, we must include the null
character as part of the string constant, like “Good/0”.
b) The gets function automatically appends the null character at the end of the string read
from the keyboard.
c) String variables cannot be used with the assignment operator.
d) The ASCII character set consists of 128 district characters.
e) The input function gets has one string parameter.
Write a program which will read a text and count all occurrences of a particular word.
INDRODUCTION
C functions can be classified into two categories, namely, library functions and user-
defined functions. Main is an example of user-defined functions. Printf and scanf belong to
the category of library functions.
1. Function definition.
2. Function call.
3. Function declaration.
DEFINITION OF FUNCTIONS
A function definition, also known as function implementation shall include the following
elements:
1. Function name;
2. Function type;
3. List of parameters;
4. Local variable declarations;
5. Function statements; and
6. A return statement.
All the six elements are grouped into two parts, namely,
A general format of a function definition to implement these two parts is given below:
The function header consists of three parts: the function type (also known as return
type), the function name and the formal parameter list. Note that a semicolon is not used at the
end of the function header.
The function type specifies the type of value (like float or double) 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. Remember, void is one of the fundamental
data types in C. It is a good programming practice to code explicitly the return type, even
when it is an integer. The value returned is the output produced by the functions.
The function name is any valid C identifier and therefore must follow the same rules
of formation as other variable names in C. The name should be appropriate to the task
performed by the function. However, care, must be exercised to avoid duplicating library
routine names or operating system commands.
The parameter list declares the variables that will receive the data sent by the calling
program. They serve as input data to the function to carry out the specified task. Since they
represent actual input values, they are often referred to as formal parameters. These
parameters can also be used to send values to the calling programs.
Function Body
The function body contains the declarations and statements necessary for performing
the required task.
The body enclosed in braces, contains three parts, in the order given below:
FUNCTION
Function is a self contained program performing a task. It has all qualities of a program. It is
executed / called by main (or) another function, by calling the function name. It is also known
as sub-program.
Syntax
Function body
CATEGORIES OF FUNCTIONS
Eg : Area of square
void main ( )
{
aos ( ) ;
}
void aos ( )
{
Recursion
eg.
void main ( )
{
int n ; long int k ;
scan f ( % d” , & n) ;
k = fact (n) ;
print f ( factorial of % d is = % ld” ,n, k) ;
}
long int fact (int nl)
{
long int f = 1;
if (n 1< = 1) / * terminating condition * /
return (1) ;
else
return (n1 * fact (n1 – 1)) ;
note :
One-Dimensional Arrays
It is sufficient to list the name of the array, without any subscripts, and the size of the
array as arguments. For example, the call
Manonmaniam Sundaranar University, Directorate of Distance & Continuing Education, Tirunelveli.
58
largest(a,n)
main( )
{
float largest(float a[ ], int n);
float value[4] = {2.5, -4.75, 1.2,3.67};
printf(“%f\n”, largest(value, 4)) ;
}
float largest( (float a[]), int n)
{
int ;
float max;
max = a[0] ;
for(I = 1; 1 < n; i++)
if(max < a[i])
max = a[i] ;
return(max) ;
}
Three Rules to Pass an Array to a Function
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
Like simple arrays, we can also pass multi-dimensional arrays to functions. The rules are
simple.
double average(iny x[] [N], int M, int N)
{
int i, j;
double sum = 0.0;
for (i=0; i<M; i++)
for(j=1; j<N; j++)
main( )
{
int M=3, N=2;
double average(int [ ], [N], int, int);
double mean;
int mamtrix {M} [N] =
{
{1,2},
{3,4},
{5,6}
};
mean = average(matrix, M, N) ;
......
......
}
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.
We shall briefly discuss the scope, visibility and longevity of each of the above class
of variables. The scope of variable determines over what region of the program a variable
is actually available for use („active‟). Longevity refers to the period during which a
variable retains a given value during execution of a program („alive‟). So longevity has a
direct effect on the utility of a given variable. The visibility refers to the accessibility of a
variable from the memory.
(global). Internal variables are those which are declared within a particular function, while
external variables are declared outside or any function.
Automatic variables
Automatic variables 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 therefore private (or local) to the
function in which they are declared. Because of this property, automatic variables are also
referred to as local or internal variables.
main( )
{
int number;
-----
-----
}
We may also use the keyword auto to declare automatic variables explicitly.
main( )
{
auto int number;
-----
-----
}
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. For example, the external declaration of integer number and float length
might appear as.
int number;
float length = 7.5;
Static Variables
As the name suggests, the value of static variables persists until the end of the
program. A variable can be declared static using the keyword static like
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 a function. The scope of
internal static variables extend up to the function in which they are defined. Therefore,
internal static variables are similar to auto variables, except that they remain in existence
(alive) throughout the remainder of the program. Therefore, internal static variables can be
used to retain values between function calls.
An external static variable is declared outside of all functions and is available to all the
functions in that program. The difference between a static external variable and a simple
Manonmaniam Sundaranar University, Directorate of Distance & Continuing Education, Tirunelveli.
62
external variable is that the static external variable is available only within the file where it is
defined while the simple external variable can be accessed by other files.
Register variables
We can tell the compiler that a variable should be kept in one the machine‟s registers,
instead of keeping in the memory (where normal variables are stored). Since a register access
is much faster than a memory access, keeping the frequently accessed variables (eg., loop
control variables) in the register will lead to faster execution of programs. This is done as
follows:
None Before all functions in a Entire file plus other Entire program
file (may be initialized) files where variable (Global)
is declared with
extern
None or auto inside a function (or a Only in that function Until end of function
block) or block of block
It is a logic error if the parameters in the function call are placed in the wrong order.
Using void as return type when the function is expected to return a value is an error.
A return statement is required if the return type is anything other than void.
Placing a semicolon at the end of header line is illegal.
Defining a function within the body of another function is not allowed.
Review Questions
a) C functions can return only one value under their function name.
b) A function in C should have at least one argument.
c) A function can be defined and placed before the main function
d) Only a void type function can have void as its argument.
Programming Exercises
Write a function exchange to interchange the values of two variables, say x and y. Illustrate
the use of this function, in a calling function. Assume that x and y are defined as global
variables.
Program
struct stores
{
char name[20] ;
float price ;
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
item = update(item, p_increment, q_increment) ;
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
printf(updated values of item\n\n”) ;
printf(“Name : %s\n”, item. name) ;
printf(price : %f\n, item. price);
printf(Quantity : %d\n”, item. quantity);
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - */
value = mul (item)
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --*/
printf(“nvalue of the item = %\n”‟ value);
}
struct store update(struct stores product, float p, int q)
{
product. Price += p;
product.quantity += q;
return(product);
}
float mul (struct stores stock)
Structures
Syntax
member 2 ;
member n ;
};
Template (OR)
Struct
member 2 ;
member n ;
Note :
Var 1, Var 2 … varn are known as structure variables. Only through structure variables
, structure members can be accessed.
Declaration :
When tagname is given & structure variables are not declared along with template,
structure variables must be declared explicitly.
eg.
Struct student
int regno ;
int total ;
};
struct student s1 ;
Struct student S1 { “Joe”, 7572, 115}; structure members can be initialized according to
the data types, while declaring the structure variable.
e.g.
Struct Student
int total ;
float avg ;
};
void main ( )
2) S1
The above program accepts the name, register number, 3 subject marks of a student
through keyboard calculates total & average, displays the same.
Array of structures
eg.
struct student
void main ( )
int i, n ;
scanf ( % d” &n);
& s1[i]. regno, &s1[i]. m1, & s1[i]. m2, & s1[i]. m3) ;
The above program accepts the input of name, register number and 3 subject marks, all
the „n‟ no. of students. Then total & average of „n‟ no. of students are calculated & finally the
marks of „n‟ no. of students are displayed.
UNIONS
Unions follow the same syntax as structures. There is major distinction between them
in terms of storage. In structures, each member has its own storage location, whereas all the
members of a union is the same location. This implies that, although a union may contain
many members of different types, it can handle only one member at t time.
union item
int m;
float x;
char c;
code;
} code;
This declares a variable code of type union item. The union contains three members,
each with a different data type. However, we can use only one of them at a time.
The compiler allocates a piece of storage that is large enough to hold the largest
variable type in the union.
code.m
code.x
code.c
Are all valid member variables. During accessing, we should make sure that we are
accessing the member whose value is currently stored. For example, the statements such as
code.m = 379;
code.x = 7859.36;
printf(“%d”, code.m) ;
is valid.
Just Remember
Review Questions
(a) The ……………. Can be used to create a synonym for a previously defined data type.
(b) A ………………… is a collection of data items under one name in which the items
share the same storage.
(c) The name of a structure is referred to as ……………………..
POINTERS
Introduction
Pointer is derived data type in C pointers contain memory addresses as their values.
Pointers can be used to access and manipulate data stored in the memory. Whenever we
declare a variable, the system allocates, somewhere in the memory, an appropriate location to
hold the value of the variables. Consider the following statement
This statement instructs the system of find a location for the integer variable quantity
and puts the value 179 in that location. Let us 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. Since memory addresses are simply numbers, they can
be assigned to some variables that can be stored in memory, like any other variable. Such
variables that hold memory addresses are called pointer variables. A pointer variable is,
therefore, nothing but a variable that contains an address, which is a location of another
variable in memory.
quantity 5000
179
P 5000 5048
p = &quantity;
would assign the address 5000 (the location of quantity) to the variable p. The & operator can
be remembered as „address o‟.
In C, every variable must be declared for its must be declared for its type. The declaration of a
pointer variable takes the following form:
data_type *pt_name;
This tells the compiler three things about the variable 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.
For example,
Once a pointer has been assigned the address of a variable, the question remains as to how to
access the value of the variable using the pointer? This is one by using another unary operator
* (asterisk), usually known as the indirection operator. Another name for the indirection
operator is the dereferencing operator. Consider the following statements:
quantity = 179;
p = &quantity;
n = *p;
Like other variables, pointer variables can be used in expressions, For example, if p1
and p2 are properly declared and initialized pointers, then the following statements are valid.
When we pass addresses to a function, the parameters receiving the addresses should
be pointers. The process of calling a function using pointers to pass the addresses of variables
is known as „call by reference‟
The function exchange() receives the addresses of the variables x and y and exchanges their
contents.
Program
Main()
int x,y;
x = 100;
y = 200;
int t;
*b = t; /* put t into b */
Output
Just Remember
Review Questions
FILE MANAGEMENT IN C
INTRODUCTION
A file is a place on the disk where a group of related data is stored.Basic file
operations.
Naming a file,
Opening a file,
Reading data from a file,
Writing data to a file, and
Closing a file.
To store data in a file in the secondary memory, we must specify certain things about the file,
to the operating system. They include:
1. Filename.
2. Date structure.
3. Purpose.
Filename is a string of characters that make up a valid filename for the operating system.
It contain two parts primary name an optional period with the extension.
Examples:
input.data
Student.c
Data structure of a file is defined as FILE in the library of standard I/O function
definitions. FILE is a defined data type.
FILE *FP;
fp = fopen(“filename‟, “mode”) ;
The first statement declares the variable fp as a “pointer to the data type FILE”, The
second statement opens the file named filename and assigns an identifier to the FILE type
pointer fp. This pointer, which contains all the information about the file is subsequently used
as a communication link between the system and the program. Mode can be one of the
following:
p2 = fopen(“results”, “w”);
r+ The existing file is opened to the beginning for both reading and writing
CLOSING A FILE
fclose(file_pointer);
p1 = FOPEN(“INPUT”, “w”);
p2 = fopen(“OUTPUT”, “r”);
fclose(p1);
fclose(p2);
The simplest file I/O functions are getc and putc. These are analogous to getchar and
putchar functions and handle one character at a time. Assume that a file is opened with mode
w and file pointer fp1. Then, the statement
putc(c, fp1);
Writes the character contained in the character variable c to the file associated with
FILE pointer fp1. Similarly, getc is used to read a character from a file that has been opened
in read mode. For example, the statement
c = getc(fp2);
Manonmaniam Sundaranar University, Directorate of Distance & Continuing Education, Tirunelveli.
81
Would read character from the file whose file pointer is fp2.
The file pointer moves by one character position for every operation of getc or putc.
The getc will return an end-of-file marker EOF, when end of the file has been reached.
Therefore, the reading should be terminated when EOF is encountered.
The getw and putw are integner-oriented functions. They are similar to the getc
and putc functions and are used to read and write integer values. These functions would be
useful when we deal with only integer data.a The general forms of getw and putw are:
putw(integer,fp);
getw(fp) ;
The functions fprintf and fscanf perform I/O operations on files. The first argument of
these functions is a file pointer which specifies the file to be used.
This statement would cause the reading of the items in the list from the file specified
by fp, according to the specifications contained in the control string.
This statement would cause the writing of the items in the list from the file specified
by fp, according to the specifications contained in the control string.
Extend the program to read this data from the file INVENTORY and display as the
inventory table with the value of each item.
Program
#include <stdio.h>
main( )
{
File *fp;
int number, quantity, I;
float price, value;
char item[10], filename[10];
It is possible that an error may occur during I/O operations on a file. Typical error
situations include:
We have two status-inquiry library functions; feof and ferrror that can help us detect I/O
errors in the files. The feof function 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 that has just been opened for reading, then the statement
if(feof(fp))
printf(“End of data.\n”);
if(ferror(fp) != 0
Program
#include <stdio.h>
struct invent_record
char name[10];
int number;
flooat price;
int quantity;
};
main ( )
char filename[10];
int reponse;
long n;
printf(“Type filename:”);
scanf(“%s”, filename);
fp = fopen(filename, “a+”);
do
append(&item, fp);
scanf(“%d”, &response);
fclose(fp);
printf(“Item name:”)
scanf(“”%s”, product->name);
printf(“Item number:”);
scanf(“%d”, &product->number);
printf(“Item price:”);
scanf(“%f”, &product->quantityt);
product->name,
product->number,
product->price,
product->quantity);
Output
Item name:XXX
Item number:444
Quantity: 34
Quanitity:45
Just Remember
(a) The mode ………………….. is used for opening a file for updating
(b) The function ……………… may be used to position a file at the beginning
(c) The function ……………….. gives the current position in the file.
(d) The function……………… is used to write data to randomly accessed file.
Programming Exercises
Write a program to create a sequential file that could store details about five products. Details
include product code, cost and number of items available and are provided through keyboard.
Prepared by
Dr. V. JOSEPH PETER
Associate Professor of Computer Science
Kamaraj College, Thoothukudi.