0% found this document useful (0 votes)
5 views

Programming-in-C

The document is a study material for B.Sc. Computer Science focusing on Programming in C for Semester I of the academic year 2022-2023. It covers various topics including C declarations, control structures, arrays, functions, pointers, and files, providing detailed explanations and examples. The content is structured into units with specific page numbers for easy navigation.

Uploaded by

gundaganivishnu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Programming-in-C

The document is a study material for B.Sc. Computer Science focusing on Programming in C for Semester I of the academic year 2022-2023. It covers various topics including C declarations, control structures, arrays, functions, pointers, and files, providing detailed explanations and examples. The content is structured into units with specific page numbers for easy navigation.

Uploaded by

gundaganivishnu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

KAMARAJ COLLEGE

SELF FINANCING COURSES


(Reaccredited with “A+” Grade by NAAC)
(Affiliated to Manonmaniam Sundaranar University, Tirunelveli.)
THOOTHUKUDI – 628003.

STUDY MATERIAL FOR B.SC. COMPUTER SCIENCE

PROGRAMMING IN C

SEMESTER – I

Academic Year 2022-2023

Prepared by
COMPUTER SCIENCE DEPARTMENT
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023

S.NO UNIT CONTENT PAGE NO

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 ( _ )

Example: area, average, x12 , name_of_place etc………

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

Rules for Identifiers


1. First character must be an alphabet (or underscore).
2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. Cannot use a keyword.
5. Must not contain white space.

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

Single Character Constants


A single character constant (or simply character constant) contains a single character
enclosed within a pair of single quote marks.
„5‟ „X‟‟ „;‟ „‟
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:
Helo!” “1987” “WELL DONE” “?...!” “5+3” “x”
Backslash character Constants
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.
Table : Backslash character Constants
Constant Meaning
„\f‟ Form feed
„\n‟ New line
„\t‟ Horizontal tab
VARIABLES

A variable is a data name that may be used to store a data value.

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

Data type Range of values

Char -128 to 127

Int -32,768 to 32,767

Float double 3.4e-38 to 3e+e38

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.

We declare long and unsigned integers to increase the range of values.

Floating Point Types


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 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

User-Defined Type Declaration


C supports a feature known as “type definition” that allows users to define an identifier
that would represent an existing data type. The user-defined data type identifier can later be used
to declare variables. It takes the general form:
typedef type identifier:
Some examples
typedef int units ;
typedef float marks ;
Another “identifier” is a user-defined data type is enumerated data type provided by
ANSI standard. It is defined as follows:
enum identifier {value1, value2,…value n};
The “identifier” is a user-defined enumerated data type which can be used to declare
variables that can have one of the values enclosed within the braces (known as enumeration
constants). After this definition, we can declare variables to be of this „new‟ type as below:
enum identifier v1, v2,…vn;
The enumerated variables v1,v2,…vn can only have one of the values value1,
value2,…value n.
An example:
enum day {Monday, Tuesday, Sunday} ;
enum day week_st, week_end ;
week_st = Monday ;
if (week_st == Tuesday) week_end = Saturday ;

DECLARATION OF STORAGE CLASS

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

Table : Storage classes and their Meaning

Storage class Meaning

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.

extern Global variable known to all functions in the file.


register Local variable which is stored in the register.

ASSIGNING VALUES TO VARIABLES


Assignment Statement
Values can be assigned to variables using the assignment operator = as follows:
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.
Scanf(“control string”, &variable1,&variable2,….);
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.
Defining Symbolic Constants
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,
representing the value of the mathematical constant “pi”. Another example is the total number
of students whose mark-sheets are analyzed by a „test analysis program‟.
A constant is defined as follows:
#define symbolic-name value of constant
Valid examples
#define STRENGTH 100
# 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:

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

OPTERATORS AND EXPRESSIONS

C SUPPORTS A RICH SET OF BUILT-IN OPEPRATORS


An operator is symbol used to manipulate
C operators can be classified into a number of categories. They include:
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

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

+ Addition or unary plus

- Subtraction or unary minus

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 less than


<= is less than or equal to

> is greater than


>= is greater than or equal to

== 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 AND


│ bitwise OR

^ bitwise exclusive OR

<< shift left


>> shift right

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

The comma Operator


The comma operator can be used to link the related expressions together.

The size of Operator


The size of 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
An arithmetic expression is a combination of variables, constants, and operators
arranged as per the syntax of the language.
Evaluation Of Expressions
Expressions are evaluated using an assignment statement of the form:
variable = expression;
Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and the result then replaces the previous value of the variable on the
left-hand side.
Examples:
x = a * b – c;
z = a – b / c + d;
Precedence Of Arithmetic Expressions
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
When a = 9, b = 12, and c = 3, the statement becomes
x = 9−12/3 + 3*2−1 Answer is 10
However, the order of evaluation can be changed by introducing parentheses into an
expression. Consider the same expression with parentheses as shown below:
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 .

12
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023

Managing Input And Output Operators


For inputting and outputting data we use library function .the important of these functions
are getch( ), putchar( ), scanf( ), printf( ), gets( ), puts( ). For using these functions in a C-program
there should be a preprocessor statement #include<stdio.h>.

[A preprocessor statement is a statement before the main program, which


begins with # symbol.]
stdio.h is a header file that contains the built-in program of these standard input output
function.

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

It is used to display single character. The syntax is putchar(char c);


Example:
char c;
c = ‘a’;
putchar(c);

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.

An example of reading a data:

#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

2) s-type conversion applied to a string is terminated by a blank space character. So string


having blank space like “Govt. Victoria College” cannot be read in this manner. For reading
such a string constant we use the conversion string as “%[^\n]” in place of “%s”.

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

Decision Making And Branching


C language possesses such decision-making capabilities by supporting the following
statements:
1. If statement
2. Switch statement
3. Conditional operator statement
4. Goto statement
Decision Making With If Statement
The if statement is a powerful decision-making statement and is used to control the flow
of execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression. It takes the following form
if (test expression)
The if statement may be implemented in different forms depending on the complexity
of conditions to be tested. The different forms is
1. Simple if statement
2. if…..else statement
3. Nested if….else statement
4. else if ladder.
Simple If Statement
The general form of a simple if statement is
if (test expression)
{
Statement-block;
}
Statement-x;
The „statement-block‟ may be a single statement or a group of statements. If the test
expression is true, the statement-block will be executed; otherwise the statement-block will be
skipped and the execution will jump to the statement-x. Remember, when the condition is true
both the statement-block and the statement-x are executed in sequence. This is illustrated in Fig.
The if …. Else statement
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.

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

Nesting Of If….Else Statements


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,

The Else If Ladder


A multipath decision is a chain of ifs in which the statement associated with each else is
an if.

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:

conditional expression? expression1: expression2

The conditional expression is evaluated first. If the result is non-zero, expression1 is evaluated
and is returned as the value of the conditional expression. Otherwise, expression 2 is evaluated
and its value is returned.

flag = (x < 0) ? 0 : 1;

The Goto Statement


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
• 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

Decision Making And Looping


Loop
Loop is a set of statements which is executed repeatedly.
Three types of Loop in C
i) For loop (finite no. of times)
ii) While Loop (entry controlled Loop)

19
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023

iii) do while (exit controlled loop)


i) For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
1. The init step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here, as long
as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control jumps to the
next statement just after the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement
can be left blank, as long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the for loop terminates.
Flow Diagram

20
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023

ii) While Loop


A while loop statement in C programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax:
while(condition)
{
statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition


may be any expression, and true is any nonzero value. The loop iterates while the condition is
true.
When the condition becomes false, program control passes to the line immediately
following the loop.
Flow Diagram

21
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023

iii) Do While Loop


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.

Syntax

The syntax of a do...while loop in C programming language is:


do
{
statement(s);
}while( condition );

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

Difference between while and do….while


• 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.
(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); }

Jumping out of a Loop


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;

Jumping out of the program


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()
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

int number [3] = { 0,0,0 };


Will declare the variable number as an array of size 3 and will assign zero to each
element.
Float total[5] = {0,0,15,75,-10}:
An array can be explicitly initialized at run time. This approach is usually applied for initializing
large arrays.
for (I = 0; I < 100; I = i+1)
{
if I < 50 sum [i] = 0.0; /* assignment statement */
else sum[i] = 1.0;
}
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional
integer array of size x, y you would write something as follows:

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:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ],


where a is the name of the array, and i and j are the subscripts that uniquely identify each element
in a.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */ };

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

Declaring And Initializing String Variables


C does not support strings as a data type. However, it allows us to represent strings as
character arrays.

char string_name[size];
The size determines the number of characters in the string_name. Some examples are:

char city[10]; char name[30;]


Character arrays may be initialized when they are declared.

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:

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()

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.

char line [80]; gets (line); printf (“%s”, line);

Writing Strings To Screen

The printf function with % format is used to print strings to the screen.

For example:

Printf(“%s”, name);

Can be used to display the entire contents of the array name.

Using putchar and puts Function

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

strcmp() compares two strings

strcpy() copies one string over another


strlen() finds the length of a string

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:

function_type function_name(parameter list)


{ local variable declaration; executable statement1; executable statement2;
. ....
.....
return statement;

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.

Name and Type


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.

Formal Parameter List


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.

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:

1. Local declarations that specify the variables needed by the function.


2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.
If a function does not return any value (like the printline function), we can omit the return
statement. However, note that its return type should be specified as void. Again, it is nice to have
a return statement even for void functions.
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 return data type fn. name (optional arguments)
function heading
{
Function body
}
function definition = function heading + fn. body)
Categories Of Functions
1. No argument, No return values
2. No argument, with return values
3. With argument, No return values
4. With argument, with return values

1. No arguments, No return values

E.g. : Area of square


void main ( )
{
aos ( ) ;
}
void aos ( )
{
int a, s scan f (“ % d”, & s) ;
a=s*s
print f (“ a = % d” ; a) ;
}

31
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023

No arguments, with return values :


void main ( )
{
int k;
k = aos( ) ;
print f (“ area = % d” , k) ;
}
int aos ( )
{
int s, a ;
scan f (" % d” , & S) ;
a = s * s;
return (a) ;
}
2. With argument No return type
Void main ( )
{
int s ;
print f (“ enter S value\n”) ;
scan f (“ % d” , &s) ;
actual
aos (s) ; argument
}
formal (or) dummy argument

void aos (int s1)


{
int a ;
a = s1*s1;
print f (“area = % d” , a) ;
}

4. With argument with return type


void main ( )
{
int s, k ;
print f (“enter s value\ n”);
scanf (“% d” , & s) ;
k = aos (s) ;

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

return (n1 * fact (n1 – 1)) ; }


note :
The default return data type of a function is int.
Passing Arrays To Functions
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
largest(a,n)

will pass the whole array a to the called function.

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) ;
......
......
}

Scope, Visibility And Life Time Of Variables

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

Structures And Unions

Structures are Used Defined Datatype used to represent a record.

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];

Here staff is an array of structure of type biodata


Note: we can declare other variables also of biodata type structure as follows.
Struct biodata customer[20]; , Struct biodata student; etc

38
STUDY MATERIAL FOR B.SC COMPUTER SCIENCE
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-2023

Accessing Structure Members

To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use 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;
}

Static struct record student1={“rajan”, 18, 62}


Here student1 is of record structure and the name,age and weight are initialised as
“rajan”, 18 and 62 respectively.
Unions
Union is a concept similar to a structure with the major difference in terms of storage. In
the case of structures each member has its own storage location, but a union may contain many
members of different types but can handle only one at a time. Union is also defined as a structure
is done but using the syntax union.

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

int quantity = 179;

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.

Variable Value Address

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:

int quantity, *p, m; quantity = 179; p = &quantity; n = *p;

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;

z = 5* - *p2/ *p1; same as (5 * (- (*p2)))/(*p1)


*p2 = *p2 + 10;

Pointers As Function Arguments


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
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

exchange (int *a, int *b)


{
int t;
t = *a; /*Assign the value at address a to t */
*a = *b; /* put b into a */
*b = t; /* put t into b */
}

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

"rb", "wb", "ab", "ab+", "a+b", "wb+", "w+b", "ab+", "a+b"

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

You might also like