Programming-in-C
Programming-in-C
PROGRAMMING IN C
SEMESTER – I
Prepared by
COMPUTER SCIENCE DEPARTMENT
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
1
I INTRODUCTION 03
2
II CONTROL STRUCTURES 16
3
III ARRAYS 24
4
IV FUNCTIONS 29
5
V POINTERS AND FILES 41
1
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
UNIT-I
INTRODUCTION
C DECLARATIONS:-
Every C program consists of one or more modules called functions. One of these
functions is called main. The program begins by executing main function and access other
functions, if any. Functions are written after or before main function separately. A function has
1. heading consists of name with list of arguments ( optional ) enclosed
in parenthesis,
2. argument declaration (if any) and
3. compound statement enclosed in two braces { } such that each
statement ends with a semicolon.
Comments, which are not executable statement, of necessary can be placed in between
/* and */.
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
3. Special characters
4. White spaces
C TOKENS
Individual words and punctuation marks are called tokens.
KEYWORDS AND INDENTIFIERS
Identities are names given to various program elements like variables, arrays and
functions. The name should begin with a letter and other charactErs can be letters and digits and
also can contain underscore character ( _ )
Key words are reserved words in C language. They have predicted meanings and are
used for the intended purpose. Standard keywords are auto, break, case, char, const, continue,
default, do, double, else enum, extern, float, for, goto, if, int, long, register, return, short, signed,
sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while. (Note that these
words should not be used as identities.)
2
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
IDENTIFIERS
A C identifier is a name used to identify a variable, function, or any other user-defined
item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or
more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a
case sensitive programming language. Thus, Manpower and manpower are two different
identifiers in C.
Example:
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
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.
Decimal integers consist of a set of digits, 0 through 9 preceded by an optional – or +
sign. Valid examples of decimal integer constants are:
123 – 321 0 654321 + 78
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:
037 0 0435 0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They
may also include alphabets A through F or a through f. The letter A through F represents the
numbers 10 through 15. Following are the examples of valid hex integers:
Real constants
Numbers containing fractional parts like 17.548 are called real (or floating point)
constants are:
0.0083 – 0.75 435.36 + 247.0
A real number may also be expressed in exponential (or scientific) notation. This notation
floating point form.
0.65e4 12e-2 1.5e+5 3.18E3 -1.2E-1
3
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
DATA TYPES
ANSI C supports three classes of data types:
1. Primary (or fundamental) data types
2. Derived data types
3. User-defined data types
Fig. Primary data types in C
Table Size and Range of Basic Data Types on 16- bit Machines
1.7-308 to 1.7e+308
4
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
Integer Types
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.
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 unsigned 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:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Primary Type Declaration
A variable can be used to store a value of any data type.
The syntax
Data-type v1, v2,….vn ;
v1, v2,…..vn are the names of variables.
For example,
int count ;
int number, total ;
double ratio ;
5
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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.
Static and external (extern) variables are automatically initialized to zero. Automatic
(auto) variables contain undefined values (known as „garbage‟) unless they are initialized
explicitly.
6
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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.
7
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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.
Declaring Variable As Constant
Variables are be declared as constant using the const keyword or the #define preprocessor
directive.
The const keyword
Variables can be declared as constants by using the “const” keyword before the datatype
of the variable. The constant variables can be initialized once only. The default value of constant
variables are zero.
Ex:
const int a;
The #define preprocessor directive
Variables can be declared as constants by using the #define preprocessor directive as it
declares an alias for any value.
Ex:
#define num 25
8
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
ARITHMETIC OPERATORS
C provided all the basic arithmetic operates.
Arithmetic Operators
Operator Meaning
X Multiplication
/ 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 and b are integers, a = 14 and b = 4
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.
The operator % cannot be used with real operands.
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
Relational Operators
We often compare two quantities and depending on their relation, take certain decisions.
An expression such as
A < b 1 < 20
An expression containing a relational operator is termed as a relational expression. The
value of a relational expression is either True of false.
9
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
C supports six relational operators in all. These operators and their meanings are shown in Table
Table Relational Operators
Operator Meaning
== is equal to
!= is not equal to
A simple relation expression contains only one relational operator and takes the
following form:
ae-1 relational operator ae-2
Logical Operators
In addition to the relational operators, C has the following three logical operators.
&& meaning logical AND
|| meaning logical OR
! meaning logical NOT
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.
Some examples of the usage of logical expressions are:
1. if (age > 55 && salary < 1000) if (number < 0 || number > 100)
Assigment Operators
Assignment operators are used to assign the result of an expression to a variable.
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);
Increment And Decrement Operators
C allows two very useful operators increment and decrement operators:
10
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
++ and −−
The operator ++ adds 1 to the operand, while – subtracts 1. Both are unary operators and
takes the following form:
++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;)
Conditional Operator
A ternary operator pair “? :” is available in C to construct conditional expressions of the
form
ecp1 ? exp2 : exp3
Where exp1, exp2, and exo3 are expressions.
The operator? : works as follows: exp 1 is evaluated first. if it is nonzero (true), then the
expression exp2 is evaluated and becomes the value of the expression. If exp 1 is false, exp3 is
evaluated and its value becomes the value of the expression. 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.
Table : Bitwise Operators
Operator Meaning
^ bitwise exclusive OR
Special Operators
C supports some special operators of interest such as comma operator, size of operator,
pointer operators (& and *) and member selection operators (. and −> ).
11
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
12
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
getchar function
It is used to read a single character (char type) from keyboard. The syntax is
char variable name = getchar( );
Example:
char c;
c = getchar( );
For reading an array of characters or a string we can use getchar( ) function.
Example:
#include<stdio.h>
main( )
{
char place[80];
int i;
for(i = 0;( place [i] = getchar( ))! = ‘\n’, ++i);
}
This program reads a line of text.
putchar function
Using these two functions, we can write a very basic program to copy the input, a
character at a time, to the output:
13
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
#include <stdio.h>
/* copy input to output */
main()
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
return 0;
}
scanf function
This function is generally used to read any data type- int, char, double, float, string.
The syntax is
scanf (control string, list of arguments);
The control string consists of group of characters, each group beginning % sign and a
conversion character indicating the data type of the data item. The conversion characters are
c,d,e,f,o,s,u,x indicating the type resp. char decimal integer, floating point value in exponent
form, floating point value with decimal point, octal integer, string, unsigned integer,
hexadecimal integer. ie, “%s”, “%d” etc are such group of characters.
#include<stdio.h>
main( )
{
char name[30], line;
int x;
float y;
………
…….…
scanf(“%s%d%f”, name, &x, &y);
scanf(“%c”,line);
}
NOTE:
1) In the list of arguments, every argument is followed by & (ampersand symbol) except
string variable.
14
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
Example:
char place[80];
…………….
scanf(“%[^\n]”, place);
……………..
with these statements a line of text (until carriage return) can be input the variable
‘place’.
printf function
This is the most commonly used function for outputting a data of any type.
The syntax is
printf(control string, list of arguments)
Here also control string consists of group of characters, each group having %
symbol and conversion characters like c, d, o, f, x etc.
Example:
#include<stdio.h>
` main()
{
int x;
scanf(“%d”,&x);
x*=x;
printf(“The square of the number is %d”,x);
}
Note that in this list of arguments the variable names are without &symbol unlike in the case of
scanf( ) function. In the conversion string one can include the message to be displayed. In the
above example “The square of the number is” is displayed and is followed by the value of x.For
writing a line of text (which include blank spaces) the conversion string is “%s” unlike in scanf
function. (There it is “[^\n]”).
15
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
UNIT – II
CONTROL STRUCTURES
16
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
True False
test
expression
?
True-block False-block
statement statement
statement - x
17
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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 ladder).
When all the n conditions become false, then the final else containing the default statement will
be executed. Fig. 5.9 shows the logic of execution of else if ladder statements.
The Switch Statement
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
The expression is an integer expression or characters. Value-1 value-2…. Are constants
or constant expressions (evaluable to an integral constant) and are known as case labels. Each of
these values should be unique within a switch statement. Block-1. Block-2…. Are statement lists
and may contain zero or more statements. There is no need to put braces around these blocks.
Note that case labels end with a colon (:)
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.
18
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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:
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, expression 2 is evaluated
and its value is returned.
flag = (x < 0) ? 0 : 1;
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
• Be aware of dangling else statements.
• Check the use of = operator in place of the equal operator = =.
• Do not give any spaces between the two symbols of relational operators = =, !=, >= and <=.
• Do not use the same constant in two case labels in a switch statement.
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
19
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
20
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
21
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
Syntax
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.
Flow Diagram
• 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.
(i.e) The do …. while loop will be executed minimum of 1 time.
22
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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); }
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;
The exit()
Function takes an integer value as its argument, Normally zero is used to indicate normal
termination and a nonzero value to indicate termination due to some error or abnormal condition.
The use of exit()
23
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
UNIT – III
ARRAYS
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
One Dimensional Arrays
Arrays are defined like the variables with an exception that each array name must be
accompanied by the size (i.e. the max number of data it can store). For a one-dimensional array
the size is specified in a square bracket immediately after the name of the array.
Declaration of One Dimensional Arrays
The syntax is
data-type array name[size];
So far, we've been declaring simple variables: the declaration
int i;
declares a single variable, named i, of type int. It is also possible to declare an array of several
elements. The declaration
int a[10];
declares an array, named a, consisting of ten elements, each of type int. Simply speaking, an
array is a variable that can hold more than one value. You specify which of the several values
you're referring to at any given time by using a numeric subscript. (Arrays in programming are
similar to vectors or matrices in mathematics.)
eg:
int x[100];
float mark[50];
char name[30];
Note: With the declaration int x[100], computer creates 100 memory cells with name x[0], x[1],
x[2],………,x[99].Here the same identifier x is used but various data are distinguished by the
subscripts inside the square bracket.
Initialization Of One-Dimensional Arrays
Array can be initialized at either of the following stages:
• At compile time
• At run time
Compile Time Initialization
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:
type array-name[size]={list of values};
The values in the list are separated by commas. For example, the statement
24
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
Type arrayname [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A
two-dimensional array can be think as a table which will have x number of rows and y number
of columns. A 2-dimentional array a, which contains three rows and four columns can be shown
as below:
25
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
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
type array_name[s1] [s2] [s3]….[sm];
Where s is the size of the ith dimension. Some example are:
int survey [3] [5] [4] []12; float table [5] [4] [3];
Survey is a three-dimensional array declared to contain 180 integer type elements. Similarly,
table is a four-dimensional array containing 300 elements of floating-point type.
The array survey may represent a survey data of rainfall during the last three years from January
to December in five cities.
CHARACTER ARRAYS AND STRINGS
char string_name[size];
The size determines the number of characters in the string_name. Some examples are:
char city [9] = “ NEW YORK ”; 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:
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()
26
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
Another and more convenient method of reading a string of text containing whitespaces is to use
the library function gets available in the <studio.h> header file. This is a simple function with
one string parameter and called as under;
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.
The printf function with % format is used to print strings to the screen.
For example:
Printf(“%s”, name);
We can use this putchar() function repeatedly to output a string of characters stored in an array
using a loop. Example.
char name[6] = “PARIS” for (i=0, i<5; i++) putchar (name) [1];
putchar (“\n‟);
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.
27
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
Function Action
strcat() concatenates two strings
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 string1. 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.
28
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
UNIT – IV
FUNCTIONS
USER DEFINED FUNCTIONS
Introduction
C functions can be classified into two categories, namely, library functions and
userdefined functions. Main is an example of user-defined functions. Printf and scanf belong to
the category of library functions.
Need For User-Defined Functions
Main is a specially recognized function in C. Every program must have a main function
to indicate where the program has to begin its execution. If a program is divided into functional
parts, then each part may be independently coded and later combined into a single unit. I C, such
subprograms are referred to as „functions‟.
In order to make use of a user-defined function, we need to establish three elements that
are related to functions.
1. Function definition.
2. Function call.
3. Function declaration.
The function definition is an independent program module that is specially written to
implement the requirements of the function. In order to use this function, we need to invoke it at
a required place in the program. This is known as the function call. The program (or a function)
that calls the function is referred to as the calling program or calling function. The calling
program should declare any function (like declaration of a variable) that is to be used later in the
program. This is known as the function declaration or function prototype.
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,
• function header (First three elements); and
• function body (second three elements).
29
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
A general format of a function definition to implement these two parts is given below:
The first line function_type function_name(parameter list) is known as the function header and
the statements within the opening and closing braces constitute the function body, which is a
compound statement.
Function Header
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 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.
Function Body
The function body contains the declarations and statements necessary for performing the
required task.
30
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
The body enclosed in braces, contains three parts, in the order given below:
31
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
32
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
print f (“area - % d” , k ) ;
}
int aos (int s1)
{
int a ;
a = s1*s1;
return (a) ;
}
(e.g) With argument ; with return value factorial
void main ( )
{
int s ;long int k ;
print f (“ enter & value \ n”) ;
scan f (“ % d” , &s) ;
k = fact (s) ;
print f (“ factorial no = % ld” , k)
}
long int fact (int s1)
{
int i ; long int f = 1 ;
for ( i =1 ; i < = n ; i+ +)
{
f=f*i ;
}
return (f) ; }
Recursion
A function calling itself is known as recursion. Recursion must have a terminating condition.
e.g
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
33
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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(int x[] [N], int M, int N)
{
int i, j;
34
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
double sum = 0.0; for (i=0; i<M; i++) for(j=1; j<N; j++)
sum += x[i] [j] ;
return(sum/(M*N)) ;
}
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.
The variables may also be broadly categorized, depending on the place of their
declaration, as internal (local) or external (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( )
35
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
{ 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;
main( )
{
------ ------
} function1( ) }
------
------
} function2( ) {
------
------
}
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 extends 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 external
36
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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 (e.g, loop control
variables) in the register will lead to faster execution of programs. This is done as follows:
register int count;
Storage class Where declared Visibility (Active) Lifetime (Alive)
None Before all functions in a file Entire file plus other Entire program
(may be initialized) files where variable is (Global)
declared with
extern
extern Before all functions in a file Entire file plus other Global
(cannot be initialized) files where variable is
extern and the file where declared
originally declared as
global.
static Before all functions in a file Only in that file Global
None or auto inside a function (or a Only in that function or Until end of
block) block function of block
register inside a function Only in that function or Until end of
block function or block
static Inside a function Only in that function Global
Defining a structure:
In general it is defined with the syntax name struct as follows
Struct structure_name
{
Data type variable1;
Data type variable2;
…
}
37
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
For example
1 Struct account
{
Int accountno;
Char name[50];
Float balance;
}customer[20]
Note :1 here accountno, name and balance are called members of the structure
2 struct date
{
Int month;
Int day;
Int year;
}dateofbirth;
In these examples customer is a structure array of type account and dateofbirth is a structural
type of date.
Within a structure members can be structures. In the following example of biodata structure date
which is a structure is a member.
For example
struct date
{
Int day;
Int month;
Int year;
}
Struct biodata
{
Name char[30];
Int age ;
Date birthdate;
}staff[30];
38
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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 struct keyword to define variables of structure
type. Following is the example to explain usage of structure:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0; }
39
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
When the above code is compiled and executed, it produces the following result:
Book 1 title : C Programming
Book 1 author : Nuha Ali
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
Structure initialisation
Like any other variable or array a structure variable can also be initalised.by using
syntax static
Struct record
{
Char name[30];
Int age;
Int weight;
}
Union var
{
Int m;
Char c;
Float a;
}
Union var x;
Now x is a union containing three members m,c,a. But only one value can be stored
either in x.m, x.c or x.a
40
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
UNIT-V
POINTERS AND FILES
Pointers
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 5048
5000
The variable that contains a pointer value is called a pointer variable. The operator &
immediately preceding a variable returns the address of the variable associated with it. For
example, the statement
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;
41
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
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,
int *p; /* integer pointer */ float *x; / * float pointer */
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:
The fourth line contains the indirection operator*. When the operator* is placed before a pointer
variable in an expression (on the right-hand side of the equal sign), the pointer returns the value
of the variable of which the pointer value is the address.
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.
y = *p1 * *p2; sum = same as (*p1) * (*p2)
sum + *p1;
The function exchange() receives the addresses of the variables x and y and exchanges their
contents. Program
void exchange (int *, int *); /* prototype */
Main()
{
int x,y; x = 100; y = 200;
printf (Before exchange : x = %d y = %d\n\n”, x,x); exchange(&x,&y); /* call */
printf(“After exchange : x = %d y = %d\n\n, x,y);
}
42
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
Output
Before exchange: x = 100 y = 200
After exchange: x = 200 y = 100
File Management in C
A file represents a sequence of bytes, does not matter if it is a text file or binary file.
Opening Files
You can use the fopen( ) function to create a new file or to open an existing file, this call
will initialize an object of the type FILE, which contains all the information necessary to control
the stream. Following is the prototype of this function call:
FILE *fopen( const char * filename, const char * mode );
Here, filename is string literal, which you will use to name your file and access mode can have
one of the following values:
Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing, if it does not exist then a new file is created.
Here your program will start writing content from the beginning of the file.
a Opens a text file for writing in appending mode, if it does not exist then a
new file is created. Here your program will start appending content in the
existing file content.
r+ Opens a text file for reading and writing both.
w+ Opens a text file for reading and writing both. It first truncate the file to zero
length if it exists otherwise create the file if it does not exist.
a+ Opens a text file for reading and writing both. It creates the file if it does not
exist. The reading will start from the beginning but writing can only be
appended
If you are going to handle binary files then you will use below mentioned access modes instead
of the above mentioned:
43
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is:
int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF if there is an error in closing the
file. This function actually, flushes any data still pending in the buffer to the file, closes the file,
and releases any memory used for the file. The EOF is a constant defined in the header file
stdio.h.
There are various functions provide by C standard library to read and write a file
character by character or in the form of a fixed length string.
44