0% found this document useful (0 votes)
23 views91 pages

UNIT 2-5 PST-NOTES

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)
23 views91 pages

UNIT 2-5 PST-NOTES

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

MODULE 1

INTRODUCTION
Objective
● To understand the basic components of C Programming Language.
● To learn the primitive data types.
● To learn the various operators
● To understand the library functions
Outcome
● Able to understand the structure of C program
● Able to write the programming expressions.
● Able to write executable expression to solve the problem

Introduction

The basics of any programming language is knowing the letters and symbols used in it. The
next level is forming the statements from the character set with proper grammar. The
grammar in programming language is said to be a syntax. The ordered sequence of
syntactically correct statement forms an executable program. All the above related to the C
programming language is covered in this module.

1. C Fundamentals

C is a procedural oriented high-level programming language used to write an instruction. It


was developed by Dennis Ritche in 1972 to develop an Operating System. Further many
other Operating systems like Windows, LINUX, MacOS were also developed using C
programming language. The instruction in the C program can be written in simple English
with key terms and program syntax. As it is a high-level language, the system needs a
translator to convert high level language into low level language. There are two type of
translators:
Compiler : Translate the entire program and summarize the syntax errors.
Interpreter : Translate one line at a time and move to the next line only after the
successful translation of the previous line. It is a line-by-line translator.

The translators of other high-level programming languages such as PHP, PYTHON, PERL were
also developed using C programming language.

1.1 Features

● Syntax of the C programming language is very simple and easy to understand.


● The C language can also be used to write both system programs and application
programs.
● The language provides a rich set of reusable library functions.
● It can be used to solve problems in a top-down approach.
● The instructions of the language are case sensitive.
● The language can handle memory using the pointer concept which makes the
execution efficient and fast.

1
1.2 Character Set

The language needs a set of letters and symbols to form an instruction. The C language
supports following set to of character
• Alphabets : A-Z, a-z
• Numbers : 0-9
• Special characters :

, < > . _
( ) ; $ :
% [ ] # ?
' & { } "
^ ! * / |
- \ ~ + (space)

The character can be used separately or combined with other characters to form a
syntactically and semantically correct instruction.

1.3 Keywords

Keywords are predefined reserved words. Each keyword is associated with a specific feature.
These are used as part of syntax with other characters and symbols provided. All the
keywords in the C program are in lower case. There are totally 32 keywords supported here.
These words can be used as user defined identifiers.

doub
auto int struct
le
break else long switch
enu regist
case typedef
m er
exter
char return union
n
contin signe
for void
ue d
do if static while
default goto sizeof volatile
unsign
const float short
ed

1.4 Identifiers
Identifier is an entity used to denote values and functions in a program. The name of
identifiers is case sensitive. Few examples of identifiers are Name, Mark. Not the first letter

2
of each identifier is given in capital letters. Denoting identifier ‘mark’ will be different from
‘Mark’, because these two differ in case. The rules must be followed while naming the
identifiers.

• Identifier can have all the characters (upper case and lower case) in the alphabet.
• Identifier can have all the numbers but not as the first letter of the identifier.
• No special character other than underscore (_) is allowed.
• Underscore can be in any position of identifier.
• No space is allowed in the identifier.
• No keyword can be identifier

Valid Identifiers Invalid Identifiers


• Name • 1name
• amount • Amount+
• StudentName • Student Name
• Student_Name • auto
• _Value
• Amount1
• autoNumber

1.5 Program Structure

The C programming language includes various components in program structure. The


efficient structure enables the programmers to write logically good and semantically correct
programs. The figure shows the components of C program.

Fig 1.1: Program Structure

3
Documentation Section
Documenting is a very good quality practice that should be followed in all the programs. The
documentation given on top of the program is used to give the description of the program.
It is a non-executable section. The documentation can also be done in other parts of the
program wherever it is necessary. Documentation is incorporated using a comment
statement.
Comment statements are non-executable statements. There are two types of comment
statements.
• Single Line Comment: Line preceded by double forward slash (//).
• Multiline Comment: More than one lines covered using /*…….*/

Linking / Header Section

The component used to include built-in library files. The library functions are grouped under
the header file. The file with extension (.h). The line preceded by hash (#) and uses the
keyword ‘include’.

Syntax
# include <headerfile.h>

Example
# include <stdio.h>

Pre-processor Directives

The pre-processor directive session used to define the symbolic constants. The programming
statements referring to these constants are processed in the first phase of program
compilation. The directive line preceded by hash symbol (#) and uses the keyword ‘define’.

Syntax
# define ConstantIdentifier value

Example
# define PI 3.14

The constant PI defined in the pre-processor directive can be used anywhere in the program.

Global declaration
The identifiers required for all the modules/functions of the program can be declared in this
section. The declaration is similar to the identifier declaration in the program module.

User Function Declaration


Group of programming statements are called functions. The syntax / protype of the function
is specified in this section. The detail includes the return type, function name and the type
of values by the function. The function declaration statement has to be terminated by
semicolon (;).

4
Syntax
ReturnType FunctionName (Parameters);

main() Function
The main() function is the statement from where the execution of the program begins. Each
executable C program should have one main function. The function can receive and return
a value.

Syntax
ReturnType main() // Without parameter
{

ReturnType main(int argc, char *argv[]) // With parameter


{

}
The first argument is about the number of values passed and the second parameter is an
array type to collect all the values passed.

Internal structure of main() function

The identifiers used in the function have to be declared in the beginning of the module. It is
applicable to all the functions in the C program. The function can have other programming
statements next to the identifier declaration.
ReturnType main()
{
Identifier Declaration;

Programming Statements

User defined Function


The definition for the user functions are given in this component. The group of executable
program statements under one name are called function definition. This includes function
header and function body. Function header is prototype of function. The functions defined
in this section have to be declared in the ‘User Function Declaration’ section. The prototype
of function declaration and function header in function definition should match.

Syntax
ReturnType FunctionName (Parameter) // Function Header
{

5
Programming Statements (Function Body)
}

The user function declaration and function definition can be combined, in such cases the
definition of the function can be given in the user function declaration section itself.

1.6 Data Types


The compiler of the programming language has to be given a detail about values used in
program. These details are used to allocate memory while executing the program. The C
programming language allow to use numerical and string values. There is different datatype
to handle numeric value. Each type maintains is lower and upper limit of value. Specifying
the type of value based on the range used will save the memory. Each type is associated with
format specifier contains percentage and one or two characters (%). The format specifier is
used to read or write the value of particular type either in console or in file. The figure gives
the different data type supported in C Programming language.

Figure 1.2: Data Types

Void Type
Void means nothing. The Void data type is used when no value is specified. It is mostly used
in return type of function and in pointers which can be given a type later. The keyword is
‘void’.
Basic Data Types
Basic data type is used to allocate the memory and to represent the single values of
Numerical and Character type of data.

Figure 1.3: Primitive Data Types


Character Type

6
The character type is used to handle single character values. The value should be covered
within single quotes(‘a’). The character value will be given 1 Byte memory. The character
value is associated with the ASCII value. So, the character identifier can be given a respective
character or can be given a corresponding ASCII character.

Data Type Keyword Rang Format


e Specifier
Character char -127 %c
to
+128

Integer Type
The whole number is represented using Integer data type. It is allowed to have both negative
and positive values. Four Bytes of memory is allocated to integer values in the latest version
of C. In the early version it was only 2 Bytes.

Data Type Keywor Range Format


d Specifier
Integer int -2,147,483,648 %d
to
2,147,483,647

Short Type
Short type is used to store the shorter range of integer values. It has been allocated only 2
bytes of memory.

Data Type Keyword Range of Format


Value Specifier
Short Integer short int -32,768 to %hd
32,767

Float Type
The float type is used to handle the real numbers. Four Bytes of memory is allocated to it.
Data Type Keywor Format
d Specifier
Float float %f

Double Type

7
The double type is also to store positive and negative real numbers. Eight bytes of memory
is allocated to it. It is double the size of float type.
Data Type Keywor Format
d Specifier
Double double %lf

Long Type
Long type is used to increase the range of values allowed and also to increase the memory
allocated. Long is combined with Integer and Double data type. Long Integer is allocated 4
Bytes of memory and Long Double is allocated 16 bytes of memory.
Data Type Keyword Format Specifier

Long Integer long int %ld

Long Long long long int %lld


Integer
Long Double long double %Ld

Signed and Unsigned Type


All the data types will accept both positive and negative types of values by default. That can
be specified explicitly using Signed type. In order to restrict the values only with positive
values the unsigned type is specified.

Data Type Keyword Format


Specifier
Unsigned Short Integer unsigned short int %hu

Unsigned Integer unsigned int %u

Unsigned Long Integer unsigned long int %lu

Derived data type


The data types are extended versions of basic data types. They are used to store more than
one value of the same type. Figure shows the derived data types.

8
Figure 1.4: Derived Data type
Array is a collection of values of homogeneous data type. All the values are stored in a
continuous location in memory. The values are accessed using the index position.
The pointer is an address of location stores value of basic data type or user defined data
type. These two data types are discussed more in later modules.

User defined data type


The programmer can create own data type to store corrections of basic data type values.
Figure shows user defined data type. The concept of Union and Structure are discussed in
later modules.

Figure 1.5: User defined data type


Enumerate is a collection of more than one constant. The keyword ‘enum’ is used to define
the enumerate data type. Default value of the first constant is 0. Value of further constants
is the continuation of the first constant value. Along with new value can be assigned to any
of the constants.
Syntax
enum Enumerate_Name{Const1, Const2…}; // Value as 0,1…
enum Enumerate_Name{Const1=10, Const2…}; // Value as 10,11

1.7 Constants
Constant is an identifier used to refer to fixed value. The value of the constant identifier has
to be given while declaring that it cannot be assigned a new value. The keyword ‘const’ is
used to denote the constant identifier.
Syntax
Keyword DataType IdentifierName = value;
Example
const int Mark = 97; // Constant definition

9
Assigning a new value to the constant identifier is an error, in another way that the
assignment operator can not be applied on a constant other than the definition statement.
Mark = 100; // Error, cannot assign new value to constant
More than one constant of the same type can be defined in a single statement. In this
identifier are separated by commas. All the constant identifiers must be given a value then
and there.
Syntax
Keyword DataType IdentifierName1 = Value1, IdentifierName2 = Value2;
Example
const int Rate = 10, Code = 5; // Two constants of type integer

1.8 Variables
Variable is an identifier used to refer to a value which can be assigned a new value anywhere
is the programming statement. The variable declared in the declaration statement can be
assigned an initial value or it may be given a value later anywhere in the program.
Syntax
DataType VariableName; // single variable
DataType VariableName = 10; // Variable with initial value
Example
int Amt;
int Mark=97;
The variables of the same type can be declared in a single declaration statement in which
the identifiers are separated by comma (,) operator. Here also the variable may be given a
value if needed.
Syntax
DataType Variable1, Variable2=10; // Multiple variable declaration
Example
int Amt=400, Mark;

1.9 Expression
The evaluable programming statements are called expressions. It contains operators and
operands. The operands may be a constant or variable. Expressions are classified based on

10
the type of value it returns as result of evaluation and types of operators involved in it. The
figure shows all types of expressions.

Figure 1.6: Types of Expressions


Constant Expression
Constant expression operates on constants, that is all the operands of expression will be
constant. The constant may be an Integer constant or Character constant.
Example
10 + 5
10 + ‘a’
Integer Expression
The expression that returns an Integer type of result is called an Integer expression. The
operands of expression may be constant or variable.
Example
x * y + 20
Floating Expression
The Expression produces float type value as result is called as Floating Expression. Expression
may have mixed type of operands.
Example
10 + 20.5
Arithmetic Expression
The expression performs an arithmetic operation and produces the result is called arithmetic
expression.
Example
10 + 20 – 5 *2

11
Relational Expression
The expression with relational operators and produces Boolean value as result is called
Relational Expression. There are two values in Boolean type, that are True and False. The
True indicates Boolean value 1 and False indicates Boolean value 0.
Example
10 > 20 // False, Returns 0

Logical Expression
The expression containing logical operator(s) and produces Boolean results is called a Logical
expression. The expression may contain more than one relational expression
Example
40 > 3 && 5<2 // && is logical operator
Pointer Expression
Pointer is a concept in C programming language to access memory location directly. There
are operators (&, *) associated with it. The expression with the pointer operators is called
pointer expression.
Example
int x;
int *a = &x; // Pointer operators
Bitwise Expression
Expression with Bitwise operators and works on bit level of value is called Bitwise operators.
Example
10 << 4 //Left shift bit values of 10 by 4 times

1.10 Statements
Executable part of the program. Each statement is associated with some semantics based on
the operation it performs and the result it produces.
Types
o Declaration Statement
o Input Statement
o Output Statement
o Condition Statement
o Loop Statement
o Evaluation Statement
Declaration Statement

12
The statement declaring the identifier or function is called a declaration statement.
The declaration statement should be terminated with semicolon (;).
Input Statement
The user can give a value during an execution of the program. The statement used to
receive value from the user is called an input statement. Some of the library functions are
used in C programs to get user input. The functions are
o getch()
o getche()
o gets()
o scanf()
Output Statement
The execution result of the program must be shown to the user. The statement used
to display the result of evaluation is called an output statement. The in-built library functions
are used to display the result. The functions are
o printf()
o puts()
Conditional Statement
The statements used to check the condition are called conditional statements. The
statement combines relational expression, conditional expression and in some criteria
arithmetic expression.
Loop Statement
The statement(s) that evaluate the expression and execute the statement(s) repeatedly is
called as loop statement. The number of iterations is depending on the conditional
statement checked either in the beginning or end of the loop statement.
Evaluation statement
The calculatetable expressions are called evaluation statements. All the expressions fall
under the category of evaluation statement.

1.11 Operators
Operators are symbols used to perform some evaluation on values. Based on the number of
operands evaluated the operators are classified as
● Unary operators: operate on one operand
● Binary Operators: operate on two operands
● Ternary Operators: operate on three operands

Based on the type of operations performed by the operators name as


● Sign Operators

13
● Increment Operator
● Decrement Operator
● Assignment Operator
● Arithmetic operators
● Arithmetic Assignment Operator
● Relational Operators
● Logical Operators
● Bitwise Operators
● Conditional Operator

Sign Operators
The operator is used to assign a sign value. There two are unary operators.
Operator Example Description

+ +10 Positive sign. The


operator always
appears before
the operand

- -30 Denote the


negative sign. It
appears before
the operand

Increment operator
The operator used to increase the value of operand by 1. It is a unary operator. There are
two types of increment, that are post increment and pre-increment
Operator Example Description
++ A = 10; Pre-increment operator. The value of A is
B = ++A; incremented by one and assigned to B.
After the execution value of A is 11 and value of B is
also 11.
A = 10; Post increment operation. The value of A is assigned
B = A++; to B before incrementing. Then the value of A is
increased. After evaluation value of A is 11, B is 10

Decrement Operator
The operator used to decrease the value of operand by 1. It is a unary operator. There are
two types of decrement, that are post decrement and pre-decrement
Operator Example Description
-- A = 10; Pre-decrement operator. The value of A is decreased
B = --A; by one and assigned to B.

14
After the execution value of A is 9 and value of B is
also 9.
A = 10; Post decrement operation. The value of A is assigned
B = A--; to B before decrementing. Then the value of A is
decreased. After evaluation value of A is 9, B is 10

Assignment operator
The operator used to assign the value to the identifier. It is a binary operator. The value on
the right of the operator is assigned to the identifier on the left.
A = 10;
The compound assignment is allowed. That is, more than one assignment operation can be
combined in a single statement.
int A=10;
int B, C;
B=C=A; //Compound Assignment

Arithmetic operator
The operators used to perform mathematical calculations are called arithmetic operators.
All the arithmetic operators are binary operators. It performs an operation on two operands.
Operator Example Description
+ C = 10 +20; Addition operation
- C = 20 -30; Subtraction Operation
* C = 10 * 20; Multiplication operation
/ C = 30 / 10; Division operation
% C = 30 % 4; Modulus operation, it returns the reminder
of an operation

Arithmetic Assignment Operator


The operator used to combine the arithmetic operation and assignment operation. The
evaluation result of arithmetic operation is assigned to the operand on the left of the
operator. So, the operand on the left of the operator also should be a variable.

Operator Example Description


+= C=10; Add value 20 with C and assign the result 30 to
C += 20; C itself.
-= C = 30; The value 20 is subtracted from C and result 10
C -= 20; is assigned to C.

15
*= C = 10; Value of C is multiplied with 20 and the result
C *= 20; 200 assigned to C.
/= C= 30; The value of C is divided by 10 and result 3 is
C /= 10; assigned to C.
%= C = 30; The value of C is divided by 4 and reminder 2 is
C %= 4; assigned to C

Relational Operators
The relational operator is used to compare two values. It is a binary operator. The operator
returns Boolean value as the result of compression.
Operator Example Description
== 10 == 10 Equal to operator. Return true (1) if both the
operands are equal else return false (0).
> 20 > 30 Greater than operator. Returns true (1) if the
first operand is greater than second operand
or else it returns false(0).
< 20 < 30 Less than operator. Returns true (1) if the first
operand is less than the second operand or
else it returns false (0).
>= 30>=40 Greater than or equal. Returns true (1) if the
first operand is greater or equal to the second
operand or else it returns false(0).
<= 30<=40 Less than or equal. Returns true (1) if the first
operand is less than or equal to the second
operand or else it returns false (0).
!= 30 != 40 Not equal. Returns true when both the
operands are not equal. Returns false when
both the operands are equal.

Logical Operators
The logical operators are used to compare two relational expressions. That is to check the
compound condition.
Operator Number of Example Description
Operators
&& Binary Operator (10 > 20) && (4 < 70) AND operator. Returns true
when both the relational
expression returns true. It
returns false when at least
one of the relational
expressions is false.
|| Binary Operator (10 > 20) || (4 < 70) OR operator. Returns true
when at least one of the
relational expressions

16
returns true. It returns false
when both the relational
expressions are false.
! Unary Operator ! (10>20) NOT operator. Returns the
negation of the result of
relational expression.

Bitwise Operators
The operator works on bit values of operand. The value of operands is converted into binary
format internally and applies to the operator. The result of the expression can be received
in any of the basic data types.
Operator Number of Example Description
Operators
& Binary Ans = 1 & 2; Bitwise AND. The binary of 1 is 001, binary of
2 is 010. The AND operation (001 & 010). So,
the result is 000. Final value in Ans is 0.
| Binary Ans = 1 | 2; Bitwise OR. The binary of 1 is 001, binary of
2 is 010. The AND operation (001 | 010). So,
the result is 011. Final value in Ans is 3.
^ Binary Ans = 1 ^ 2; Bitwise XOR. The binary of 1 is 001, binary of
2 is 010. The AND operation (01 | 10). So, the
result is 011. Final value in Ans is 3.
~ Unary Ans = ~5; Bitwise negation. The binary value of 5 is
010. Negated value is 101. Final value in Ans
is 6.
>> Binary Ans = 5 >> 2; Bitwise Right shift. The value in the left of
the operator is shifted to the right by the
number of times given in the right of the
operator.
<< Binary Ans = 5 << 2; Bitwise Left shift. The value in the left of the
operator is shifted to the left by the number
of times given in the right of the operator.

Conditional Operator
The operator used to check the condition. It operates on three operands so it is a ternary
operator. It consists of three components: one is condition, second is true part and third is
false part.
Operator Example Description

17
? : (10>20) ? Conditional operator
printf(“true”) : evaluates the conditional
printf(“false”); expression. If the result of
conditional expression is
True it executes the True
part or else it executes the
false part.

1.12 Operator Precedence


The order of execution of operators in expression is called as Precedence Rule. Single
expression can have any number of operators. The evaluation of operators is based on the
Precedence of operators. The operator having highest precedence will be evaluated first and
so on. The unary operators have highest precedence (except not operator) than binary
operators. The table below shows the operators from highest to lowest precedence.
The operators in one cell have the same precedence level. The operator of same level in
expression evaluated from left to right.

Operators Explanation

(expression), The expression covered in (), [] , {} have highest precedence


[expression] among all the operators
, {expression},

+a, -a, ~a Unary minus, unary plus, bitwise Not. All these are unary
operators.

*, / , % Multiplication, Division, floor division, modulus

+,- Addition and Subtraction

<< , >> Left and right shift

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

<, >, <=. >=. ==, All comparison operators


!=

! Not operator. It is unary but have


precedence lower than some binary operators.

18
&& Logical AND operator

|| Logical OR operator

= Assignment operator

Example

int X=3, Y=4, Z=9;


Ans = X + Y * Z;
Among the operators in above example the operator multiplication ( * ) have higher
precedence, so Y * Z computed first and the resulted is added with the value of X. So, the
value of Ans will be 39. To give higher precedence for addition ( + ) than the multiplication (
* ) the respective arithmetic expression has to be covered in parenthesis. The below example
shows that.
Example
int X=3, Y=4, Z=9;
Ans = (X + Y) * Z

The value of Ans after the expression is 63.

1.12 Library function


The predefined function provided by C Programming is called a library function. The
functions are grouped in different files. Those files are called library functions. The respective
header file has to be included in the program Link/Header file section in-order to make use
of the function. Some of the header files are listed here.
Header file Description Functions
stdio.h Standard Input / Output printf()
functions scanf()
getc()
putc()
fopen()
fclose()
remove()
fflush()
math.h Mathematics functions acos()

acosh()

asin()

19
ceil()

exp()

floor()

log()
ctype.h Character type functions isalnum()

isalpha()

isdigit()

islower()

isspace()

isupper()

tolower()

toupper()
string.h String handling functions strcat()

strcmp()

strcpy()

strlen()
time.h Date time functions setdate()
getdate()
clock()
time()
difftime()

Key Points
The character is set in the C programming language.
The keywords are reserved words.
Expression: Type of expressions,
Executable statements: Syntactically correct and executable statements.
Data Types: Primitive data types, user defined, derived data types.
Operators: Unary operators, binary operators, ternary operators, arithmetic operators,
relational, conditional operators.

20
The inbuilt functions in a header file.

Self Assessment

I.Multiple Choice Questions


1. C is _______ type of programming language.?
a) Object Oriented
b) Procedural
c) Bit level language
d) Functional

2. What is the output of this statement "printf("%d", (a++))"?


a) The value of (a + 1)
b) The current value of a
c) Error message
d) Garbage
3. Which of the following is not a valid variable name declaration?
a)int__a3;
b)int__3a;
c)int__A3;
d) None of the mentioned
4. All keywords in C are in ____________
a)LowerCase letters
b)UpperCase letters
c)CamelCase letters
d) None of the mentioned
5. Which keyword is used to prevent any changes in the variable within a C program?
a)immutable
b)mutable
c)const
d) volatile
6. What is the precedence of arithmetic operators (from highest to lowest)?
a) %,*,/,+,–
b) %,+,/,*,–
c) +,-,%,*,/
d) %, +, -, *, /
7. Which of the following is not an arithmetic operation?
a) a*=10;
b) a/=10;
c) a!=10;

21
d) a % = 10;
8. Which of the following data type will throw an error on modulus operation(%)?
a) char
b) short
c)int
d) float
9. What is the result of logical or relational expression in C?
a) True or False
b) 0 or 1
c) 0 if an expression is false and any positive number if an expression is true
d) None of the mentioned

10. Which among the following is NOT a logical or relational operator?


a) !=
b) ==
c)||
d) =
11. What will be the final values of a and c in the following C statement? (Initial values:
a = 2, c = 1)
c = (c) ? a = 0 : 2;
a) a=0,c=0;
b) a=2,c=2;
c) a=2,c=2;
d) a = 1, c = 2;
12. Operation “a = a * b + a” can also be written as ___________
a) a*=b+1;
b)(c=a*b)!=(a=c+a);
c)a=(b+1)*a;
d) All of the mentioned
13. Which of the following is an invalid assignment operator?
a)a%=10;
b)a/=10;
c)a|=10;
d) None of the mentioned

14. What is the Priority of C Logical Operators.? NOT (!), AND (&&) and OR (||)
a) NOT (!) > AND (&&) > OR (||)
b) NOT (!) > AND (&&) = OR (||)
c) AND (&&) > OR (||) > NOT (!)
d) AND (&&) = OR (||) > NOT (!)

22
15. What is the output of C program?
int main()
{
int a=9, b=6;
if(a==9 && b==6)
{
printf("Hockey");
}
else
{
printf("Cricket");
}
return 0;
}
a) Cricket Football
b) Hockey Football
c) Football
d) Compiler error

II.Descriptive

1. What is the preprocessor directive?


2. What is the use of #define?
3. Define Token
4. Define Variable?
5. Give a syntax of identifier declaration.
6. Differentiate variable and constant
7. How void data type can be used in a program?
8. Discuss in detail about data types
9. Discuss the benefit of short and long data types.

Answer : Self Assessment - MCQ

23
1. B
2. B
3. D
4. A
5. C
6. A
7. C
8. D
9. B
10. D
11. A
12. D
13. D
14. A
15. B

Summary
This module deals with the basic characters of C programming, constants, variables, different
types of expressions, operators and data types. Each of the above mentioned topics are
given with examples and explanations. The built-in header files and the method of including
the built-in functions are also explained. the program structure to write an executable
program also explained.

24
MODULE 2
OVERVIEW PROGRAMMING IN C
Objective
● To learn the simple program
● To learn the control structure.
● To learn the loop statements.
● To learn to write iterative programming statements.
Outcome
● Able to write interactive program
● Able to write a program with selection statements.
● Able to write a program to execute statement iteratively.
● Able to apply the conditional operators and relational operators to iterate statements.

Introduction

This module deals with primitive data types supported by the C programming language along
with the syntax to define the variables and constants of each type. The execution flow of the
program and the selection statements to change the program flow are also discussed in this
module. The repeated execution of programming statements are accomplished using the
looping statements. The loop statements of the C programming are discussed.

2.1 Data Input

Getting value from the user is called input. The program will be interactive only when it
interacts with the user by getting value from the user and giving results to them. The
program can work on instant values instead of working on a fixed set of values, this is another
advantage of getting the value during the program execution. The programming statement
used to receive the input is called input statement.

The function scanf() is used to get any type of value from the user. It is available in the stdio.h
header file. The value received using this function is assigned to the variable given. This value
can be used further anywhere in the program. The input can be received using this function
at any required point. The execution flow of the program waits until receiving value from
the user.

The scanf() function contains two components one is to specify the format specifier of value
type and other one is to give an identifier. Single scanf() function can be used to get more
than one value. The default delimiter of the value is space ( ). Another delimiter is also
allowed. The variable in scanf() should be preceded by a pointer operator (& - Address of
Operator). It indicates to store the value received in memory location assigned for variable
identifier.

Syntax

25
scanf(“FormatSpecifier”, &VariableName); // To get one value
scanf(“FormatSpecifier1 FormatSpecifier2”, &Variable1, &Variable2); //To get two values

Example 1

int Mark;
scanf(“%d”, &Mark);

The above scanf() receives one value of type integer. So, the format specifier %d has been
specified.

Example 2

int Mark;
float Rate;
scanf(“%d%f”, &Mark, &Rate);

There are many other functions available in C programming to get an input. The respective
header file must be included in the linker/header section of the program to make use of
these functions.

Function Name Header File Description


getchar() stdio.h Read a single character.
getch() conio.h Read single character and does not echo on the
screen
getche() conio.h Read single character and echoes on the screen
gets() stdio.h Reads more than one character, that is string

2.2 Data Output

The in-built printf() function available in the stdio.h header file is used to display value on
standard output devices. It takes 1 or more parameters. The parameters are separated using
comma (,). It is used to print string, result of expression and value of identifier.

Syntax
printf(“ ”); //print the content given in double codes

printf(“FormatSpecifier”, Identifier); //Displays the value of identifier

Example 1

printf(“First Output”);

Example 2

26
int a=10;
print(“%d”, a);

Example 3

int a=10;
float f=4.7;
printf("Value 1: %d \nValue 2: %f", a, f);

The output of above printf() will be


Value 1:10
Value 2:4.70000

2.3 Simple Program

The simple program given here is to calculate a total of given 5 subject marks. The necessary
identifier is declared in the beginning of the main () function. The scanf() function used to
write the input statement through which the mark of 5 subjects are received. The total of
subject marks is evaluated using arithmetic expression. The output of the program has been
displayed using the output statement. The program used two in-built functions scanf() and
printf(), which are available in the stdio.h header file, that has been included in the header
file section of program structure.

The necessary documentation is done throughout the program using comment statements.

Example
//Program to find Total of 5 subject marks
#include<stdio.h> //Header file

void main ()
{
int M1, M2, M3, M4, M5; // Variable declaration
int Total;
printf("Enter 5 Subject Marks (Leave space between)"); // Output Statement
scanf("%d%d%d%d%d", &M1, &M2, &M3, &M4, &M5); //Input Statement
Total= M1 + M2 + M3 + M4 + M5; // Arithmetic Expression - Integer Expression
printf("Total :%d", Total); //Output Statement

Output of the above program will be

Enter 5 Subject Marks (Leave space between)98 78 89 90 93

27
Total :448

2.4 Flow Control

Control structure determines the flow control of a program. Flow control of a program is that
in what order or sequence, the program statements are executed. The control structure
contains a block of statement which is executed based on the control statement. The control
statement is a statement which contains a control or condition that yields either true or false
after evaluate the condition.
In programming languages, there are four types of flow controls such as
2. Sequential control
3. Selective control
4. Iterative control and
5. Jump control

Sequential control

In sequence control structure, the statements are executed line by line in the order they
appear. Most simple programs are following the sequence control program. These programs
executed starting from first line, then executed next line and finished at the last line without
any omission of lines.

Figure 2.1: Sequential Flow of Execution

Selection Control

The selection control executes any one block of statements based on the control statement’s
result. The other block of statement is not executed. Most languages support the control
statement with the Logical Expression.

28
Figure 2.2: Selection Statement Flow

A selection control statement is used to execute the selective part of the program. The
selection process of the statement is based on the result produced in the Logical and
Relational expression given in the conditional statement. The selection control statement is
implemented in three different structures. These statements are also referred to as decision
statements.
1. if statement
2. if.. else statement
3. if… else if…else statement
4. switch…case Statement

Iterative Control
The iterative control statement executes a block statement repeatedly. The repetition of
blocks is based on the condition in the control statement.

Figure 2.3: Iterative Statement Flow


The iterative concept is being implement using
1. while loop

29
2. do…while loop
3. for loop
Jump Control
The jump control transfers the flow control of execution from one place to another place of
the program without any condition. The unconditional jump has been implemented using
the ‘goto’ statement in C programming Language.

2.5 if Statement
The if statement evaluates the Boolean expression given. If the result is true, the block of
statements is executed; otherwise (in case of False) the next statement after the if statement
block will be executed.

Syntax
if (Conditional Statement)
{
Statement(s) //True Block
}

Figure 2.4: If Statement Flow


Example
// Check given number is Even
#include <stdio.h>
int main()
{
int num;
printf(“Enter an integer: “);
scanf(“%d”, &num);

// true if num is divisible by 2

30
if(num % 2 == 0)
printf(“%d is even.”, num); // True block statement

printf(“\nEnd of Program”);

return 0;
}
2.6 if… else statement
The if…else statement evaluates the conditional statement. If the result is true, the block of
statement(s) will be executed; otherwise (in case of False) the else part block will be
executed.
Syntax
if (Conditional Statement)
{
Statement (s) //True Block
}
else
{
Statement(s) //False Block
}

Figure 2.5: If..Else statement flow


Example
// Check whether given number is EVEN or ODD
#include <stdio.h>
int main()
{

31
int num;
printf(“Enter an integer: “);
scanf(“%d”, &num);

// true if num is divisible by 2


if(num % 2 == 0)
printf(“%d is even.”, num);
else
printf(“%d is odd.”, num);

return 0;
}

2.7 if…else if ….else Statement


In nested structure, If contains another ‘if’ statement either in the true part or in the false
part. Another condition is being checked using the ‘else if’ statement. The final ‘else’ block
is executed only when the conditions of both the ‘if’ statements are false.

Syntax
if (condition1)
{
Statement(s) // Executed when condition1 is true
}
else if (Condition 2)
{
Statements(s) // Executed when condition 1 is false and condition 2 is true
}
else
{
Statements(s) // Executed when both condition1 and condition2 are false.
}

Example
//Checking the eligibility of age to work in an organization
# include <stdio.h>

int main()
{

32
int age;

printf(“Please Enter Your Age Here:”);


scanf(“%d”, &age);

if ( age < 18 )
{
printf(“Not Eligible to Work”);
}
else if (age >= 18 && age <= 60 )
{
printf(“You are Eligible to Work \n”);
}
else
{
printf(“You are too old to work!1\n”);
}
return 0;
}

2.8 Switch Case Statement

The switch..case statement is another decision making statement. It used to check the
nested conditions. It checks the multiple values of one variable. It is used to avoid the
complicated nested ‘if’ and ‘else if’ statements. It can evaluate simple conditions /
expressions. The compound of condition checking is not possible in the switch case.
Syntax
switch (expression)
{
case constant1:
// statements
break;

case constant2:
// statements
break;
.
.
.
default:
// default statements
}

33
Figure 2.6: Switch Case Statement Flow
The case statement can have character constant or numerical constant. The default part will
be executed when all the case statements are not matched for the resulting expression in
the switch statement.

Example
// Simple Calculator
// Program to create a simple calculator
# include <stdio.h>
int main() {
char operator;
double n1, n2;

printf(“Enter an operator (+, -, *, /): “);


scanf(“%c”, &operator);
printf(“Enter two operands: “);
scanf(“%lf %lf”,&n1, &n2);

switch(operator)
{
case ‘+’:
printf(“Addition\n”);
printf(“%.1lf + %.1lf = %.1lf”,n1, n2, n1+n2);
break;

case ‘-‘:
printf(“Subtraction \n”);
printf(“%.1lf - %.1lf = %.1lf”,n1, n2, n1-n2);
break;

case ‘*’:

34
printf(“Multiplication \n”);
printf(“%.1lf * %.1lf = %.1lf”,n1, n2, n1*n2);
break;

case ‘/’:
printf(“Division \n”);
printf(“%.1lf / %.1lf = %.1lf”,n1, n2, n1/n2);
break;

// operator doesn’t match any case constant +, -, *, /


default:
printf(“Error! Operator is not correct”);
}
return 0;
}

2.9 goto Statement


The ‘goto’ statement transfers the control from the current place to specified location. The
specification is done with the help of ‘label’. The unconditional jump has to be handled with
care to maintain a finite number of execution and termination of program.
Syntax 1 – Refer label in later part
goto Label:

Label:
Syntax 2 – Refer label in early part. It needs proper termination to avoid infinite repetition.

Label:
….
Goto Label:

Example
// Program to print Numerical table till 10th multiplication
#include <stdio.h>
int main()
{
int num, i=1;

35
printf(“Enter the number to print table till 10 :”);
scanf(“%d”, &num);
table:
printf(“%d x %d = %d\n”,num, I, num*i);
i++;
if(i<=10)
goto table;
}
2.10 While loop
While loop is being used to execute the continuous group of programming statements
repeatedly until the condition is true. The loop is executed only when the condition is true.
It is an entry control loop.

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

Figure 2.7: While Loop Statement Flow


Example
//Print the number in reverse till 0

#include <stdio.h>

int main () {

int n;

36
printf(“Enter the limit :”);
scanf(“%d”, &n);

/* Execute until n>0 */


while( n > 0 ) {
printf(“value: %d\n”, n);
n--; //decrement by 1
}

2.11 Do…While Loop


Do the loop statement until the condition is true. It executes the statements once before
checking the condition. It is an exit control loop. Execute the statements once even if the
condition is false.
Syntax
do {
statement(s);
} while( condition );

Figure 2.8: Do..While Statement Flow


Example
//Display number in reverse till 0
#include <stdio.h>
int main () {
int n;
printf("Enter the limit :");
scanf("%d", &n);

37
do {
printf("value : %d\n", n);
n--;
}while( n>0);
return 0;
}
2.12 For loop
This loop is used to repeat a group of statements in the specified number of times. It is a
finite loop through which the number of iterations can be predicted in advance. The syntax
contains three components.
o Initialization: Contains assignment expression
o Condition: Contains logical and relational expression
o Increment: Contains arithmetic expression
Syntax
for (initialize; condition; increment) {
statement(s);
}

Figure 2.9: For loop statement flow


Example
// Program to print upto n numbers
#include <stdio.h>

int main ()

38
{
int n,i;
printf("Enter the limit :");
scanf("%d", &n);

for (i=1;i<=n;i++)
printf("\nValue :%d",i);
return 0;
}

2.13 Nested Loop


A nested loop is a loop which exists as a part of the suite of outer loop. The nested loop is
structured as the nested if statement. Nested structure of loop can be formed from any of
the loop statements learnt previously.. Innermost loop executed all its iterations for every
iteration of the outer loop. Two or more mixed loop statements are also allowed to form a
nested loop structure.
Syntax – While Loop
while (Condition1)
{
Statement(s)
while (Condition2)
{
Statement(s)
}
Statement(s)
}
Example
//Program to display number triangle
# include <stdio.h>
int main()
{
int n=5;// variable declaration

39
int i, j;
for(i=1;i<=n; i++) // outer loop
{
for(j=1;j<=i; j++) // inner loop
{
printf("%d\t", i); // printing the value.
}
printf("\n");
}
}

2.14 Break Statement


The break statement is used to bring the control of execution out of the loop. It is also used
in switch statement along with case statements. The break statement is used within every
case to bring the control out of the switch once when the case is matched with the
expression given. The statements next to the break statement will not be executed.
Syntax
while {
statement(s)
break; //bring the control out of loop
statement(s) // Skipped
}

Example
// Program to print only till 5
#include<stdio.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ", i);

40
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);

2.15 Continue Statement


The continue statement takes the execution control to the beginning of the loop and
continues the execution for the next iteration. The statements given next to continue will be
skipped in one particular iteration. Continue statement can be used with any of the loop
statements.
Syntax

while{
statement(s)
continue; //takes the control to the beginning of loop
statement(s) // Skipped
}

Example
// Program to print till 20 and skips all the number multiples of 3
void main ()
{
int i;
for(i = 0; i<20; i++)
{

if(i%3==0)
continue;
printf("%d ",i);
}

41
}

2.16 Comma Operator


Comma(,) is a special symbol supported in C programming. This is being used as a separator.
The below table gives the usage of comma in various programming statements
void main(int a, char *a) Used as separator of parameter in function
printf(“Value %d”,a);
int a, b; Used as separator identifiers declared in
single statement
int y, x=10; Used to separate the sequence of
y = (x++, evaluable statements. The result of the first
printf("x = %d\n", x), statement will be assigned to the variable
++x, on the left of the assignment operator (=).
printf("x = %d\n", x),
x++); y will be assigned with 11 (x++).

Key terms
Data input, Data Output, Flow control, selection statement, loops, iteration, nested loops,

continue, break, comma operator.

Self Assessment
I Multiple choice Questions

1. Choose a right C Statement.


a) Loops or Repetition block executes a group of statements repeatedly.
b) Loop is usually executed as long as a condition is met.
c) Loops usually take advantage of Loop Counter
c) All the above.

2. Which loop is faster in C Language, for, while or Do While.?


a) for
b) while
c) do while
d) All work at same speed

3. What is the output of C Program.?

42
int main()
{
int k;

for(k=1; k <= 5; k++);


{
printf("%d ", k);
}

return 0;
}
a) 1 2 3 4 5
b) 1 2 3 4
c) 6
d) 5

4. What is the way to suddenly come out of or Quit any Loop in C Language.?
a) continue; statement
b) break; statement
c) leave; statement
d) quit; statement

5. Choose facts about continue; statement is C Language.


a) continue; is used to take the execution control to next iteration or sequence
b) continue; statement causes the statements below it to skip for execution
c) continue; is usually accompanied by IF statement.
d) All the above.

6. Choose a correct C Statement regarding for loop.


for(; ;);
a) for loop works exactly first time
b) for loop works infinite number of times
c) Compiler error
d) None of the above

7. Which of the following cannot be checked in a switch-case statement?


a) Character
b) Integer
c) Float
d) enum

43
8. If block always need to be assoicated with a else block?
a) True
b) False

9. If you have to make decision based on multiple choices, which of the following is best
suited?
a) if
b) if-else
c) if-else-if
d) All of the above
10. The continue statment cannot be used with ________
a) for
b) while
c) do while
d) switch

II Descriptive
1. Write an input statement to get one character input.
2. How to apply a ‘for’ loop to iterate statements?
3. Differentiate break and continue statements
4. How can the nested loop be used in a program?
5. Explain how switch statement can be used in place of nested if..else?
6. Write a program to find the sum of N numbers.
7. Write a program to find whether the person is eligible to get a grade in an exam?

Answer: Self assessment- MCQ


1. D
2. D
3. C
4. B
5. D
6. B
7. C
8. B
9. C
10 D

Summary
The primitive data types supported by the C programming language along with the syntax to
define the variables and constants of each type are explained in this module. The selection

44
/ control statements used to change the execution flow of the program are also discussed.
The repeated execution of programming statements is accomplished using the looping
statements. The loop statements of the C programming are discussed.

45
MODULE – 3
FUNCTIONS & RECURSIONS
Objective
● To learn modularity in programming style.
● To learn the recursive function.
● To learn to write an efficient program.
Outcome
● Able to write user defined functions.
● Able to apply functions in problems which need modularity.
● Able to implement different level of storage to write optimal program
Introduction

The module deals with the concepts of functions. The detailed syntax of user defined functions
declaration, definition and function call are discussed. The concept of recursive function to execute
the function more than once by calling itself is discussed. The difference between storage classes to
maintain different visibility, accesses and scope of variables have been given in detail to write an
efficient and optimal program.

3.1 Functions

The functions are used to group the set of code under a single name. The set of programming
statements which have been used repeatedly are grouped as a single unit called function. The
functions are reusable codes. That avoids writing the same statements again and again. So it
reduces the size of the program.

The function has to be called explicitly to use it. Calling of the function is also known as
invoking the function. Functions are called by their name. There are two categories of
functions.
1. Built-in functions
2. User defined functions

Built-in functions
The C programming language provides a set of reusable functions as a Library. The functions
are grouped into separate header files based on the similarity of the functionality defined in
it. The respective header file has to be included in the linker/header section of the program to
make use of the built-in function.

User defined functions


The program can define its own functions, it is referred to as a user defined function. It
supports reusability and also reduces the size of the program. The user defined function
contains three components.

● Function Declaration/Function Prototype

46
● Function Definition
● Function Calling

3.2 Function Prototype / Function Declaration

The function prototype is a declaration statement to specify the details about the user
defined function. The function declaration statement has to be written in the Function
declaration part of program structure. The function prototype consists of three parts
o Function Return type
o Function Name
o Parameters / Arguments

Function Return Type: The result of function statements can be displayed within the
function itself using the output statement. In some cases, the function needs to return value
to the location from where it had been invoked.
Function Name: Function name is an identifier. The function is being invoked by its name.
The rules defined for identifier declaration are also applicable for function name declaration
also.
Parameter / Arguments: Parameters are the values passed to the function from the invoking
statement. The function declaration needs to specify the type of parameters to be passed.
More than one parameter is also allowed. In that the parameters are separated by comma
operator.

Syntax

ReturnType FunctionName(); //No parameter


ReturnType FunctionName(parameterType); // One parameter
ReturnType FunctionName(ParameterType1, ParameterType2,…ParameterTypeN); // N
parameters

The no parameter function can be specified explicitly using the ‘void’ keyword.

ReturnType FunctionName(void); //No parameter

Example

void Display(); // No parameter


void Display(int); //one parameter of integer type
void Display(int, float); //Two parameters, one is integer and second is float type.

47
3.3 Function Definition

The group of statements of function performing the task is specified in function definition.
The function defining consists two components
1. Function header: The function header should match with the function prototype. The
parameters have to be given along with identifiers. There should not be a semicolon at the
end of the statement.
2. Function body: The function statements covered within curly braces ({ }) is known as
function body.
Syntax
ReturnType FunctionName(ParameterType IdentifierName)
{
Function Body
}

The parameter in function definition is referred to as formal argument. More than one function
parameter is separated by comma operator.

3.4 Function Call

Invoking the function is known as function call. The function is being called by its name.

Syntax

FunctionName(); //Without parameter

FunctionName(Parameter1, Parameter2); // With parameter

Variable = FunctionName(); //Function with return type

The value passed in the function call is called a formal argument. The value being returned
from the function will be received in a variable given along with the function call statement.

3.5 Control Flow in Function call

The execution flow will be sequential until the occurrence of selection or conditional
statement. In function components the control will be transferred to function definition
when the function call statement occurs. The control returns back to the function call after
executing all the statements of function or when the return statement occurs.

48
Figure 3.1: Function Execution Flow

Example
The program given here implements all the three components of function. The program is
to find the average of three numbers.

//Find average of numbers


#include <stdio.h>
void Average(); //Function Declaration
int main()
{
printf("Find average of numbers");
Average();
return 0;
}

void Average()
{
int num1, num2, num3;
float avg;
printf("Enter three numbers :");
scanf("%d%d%d",&num1,&num2,&num3);
avg = num1 + num2 + num3;
printf("Average :%f", avg);

3.6 Passing parameter

The main use of the function is reusability. The function statements can be applied on

49
different data for any number of times. Instead of getting the value in the function definition
statement the values can be sent from the function call. The calling statement can decide on
which data the function definition statements work. The value sent from the function calling
statements to the function definition is called parameter.

The function declaration should have the data type of values to be passed. The data types
have to be separated by comma when more than one value is passed.

The value passed from the function calling statement is being received in variables given in
the function header part of function definition.

Actual Argument: The value passed in function call is known as actual argument.

Formal Argument: The parameters in the header part of function definition is known as
formal argument

The actual argument and formal arguments are two different copies. The value of the actual
argument will be copied into variables in the formal argument. The changes in formal
argument will not be reflected in argument. The actual argument has to be passed as
reference or pointer to maintain the values of both the argument as single copy. In such
cases the changes in formal argument gets reflected in actual argument.

Example

The program is to find the average of three numbers. The values are passed as parameters
to function. The average is calculated as function definition and displayed. The different
values can be passed for each time of function call.

#include <stdio.h>
void Average(int, int, int); //Function Declaration
int main()
{
int num1, num2, num3;
printf("Find average of numbers");
printf("Enter three numbers :");
scanf("%d%d%d", &num1, &num2, &num3);
Average(num1, num2, num3); //Function call with parameter
return 0;
}

50
void Average(int n1, int n2, int n3) //function definition
{

float avg;
avg = n1 + n2 + n3;
printf("Average :%f", avg);

3.7 Call by reference

The actual parameter can be received as reference in function definition. In that both actual
parameter and formal parameter will refer to the same copy of value in memory. So, the
changes made in function definition will affect the value in the actual parameter also. The
function declaration should have the prototype to indicate the reference parameter by
giving address of operator(*). The formal parameters in function definition are preceded by
operator (*) to receive actual parameters as reference. The function call should have
operator (&) in front of parameters

Syntax
ReturnType FunctionName(DataType1 *, DataType2 *); // function declaration

FunctionName(&Parameter1, &Parameter2); //Function Call

ReturnType FunctionName(DataType *Identifier1, DataType * Identifier2)


{

Example

#include <stdio.h>
void Increment(int *);
int main()
{
int a=10;
printf("Before Function Call %d:",a); //10
Increment(&a);

51
printf("After Function Call %d:",a); //40
return 0;
}

void Increment (int *m)


{
*m = *m+30;
}
10

a m

The actual parameter ‘a’ and formal parameter ‘m’ refers to the same memory location. The
formal parameter can access the value in the location only with value of operator(*). So the
changes done by one parameter will affect the other.

3.8 Return Value

The function can return the value to the function calling statement. The ‘return’ statement.
The execution control will be transferred back to the function call whenever the ‘return’
statement occurred in function definition. The data type of the value being returned from
the function has to be given in function declaration and function definition header also. The
function can return a maximum of one value.

Example

The program contains the function Average to find the average of three numbers passed.
The calculated average is returned back to the function call using the ‘return’ statement.

#include <stdio.h>
float Average(int, int, int); //Function Declaration - Return
int main()
{
int num1, num2, num3;
float avg;
printf("Find average of numbers");
printf("Enter three numbers :");
scanf("%d%d%d",&num1,&num2,&num3);

52
avg = Average(num1,num2,num3); //Function call with parameter & Receive Value
printf("Average :%f", avg);
return 0;
}

float Average(int n1, int n2, int n3) //function definition


{

float average;
average = n1 + n2 + n3;
return average; // return value

3.9 Recursions

The recursion problem solving divides the program into subprograms until there is no more
possibility of sub division. Each division reduces the problem size. In order to complete problem
solving one sub problem call the next and next and so on. Each call will execute the same set of
statements that are called instances. After each execution the control returns to the subprogram
which made a call.

The functional module that makes a conditional call to itself is called recursive function. The instance
of function will be created for each call of the function to itself. So, the instance is a copy of the same
function. As the definition is the same then it includes a function calling statement to itself. So, the
chain will go on. The un-terminatable recursive function call is called infinite recursive. The recursive
functions have to be designed in such a way to handle the infinite recursive. One prompt solution is
making the recursive call conditionally. That’s why the definition of recursive function given as “The
recursive is a function that have conditional call to itself”

Figure 3.2: Recursive Function Execution Flow


Example

53
The program to find the factorial of a given number is given here.

#include<stdio.h>
long int Factorial(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, Factorial(n));
return 0;
}

long int Factorial(int n) {


if (n>=1)
return n * Factorial(n-1); //Recursive call
else
return 1;
}

3.10 Storage Class

The identifiers declared in a program will have different visibility and different life space
based on the location where it is defined. By default, the life of identifier and visibility is only
within the block where it is defined. Memory space will be allocated to all the identifiers in
main memory. The content in register memory can be accessed more quickly than the
content in main memory. The lifetime, visibility and the storage allocation can be changed
and handled in the program explicitly to write optimal programs.

The storage classes are used to decide the variable features, that is life time, visibility, scope
and storage. There are four storage classes in programming in C.
● Auto
● Register
● Static
● Extern

Auto: The auto identifier visible only within the function where it is defined. The life and
scope of the auto identifier is only within the function. All the identifiers are auto by default.

54
The auto identifier will be allocated memory in main memory. The keyword ‘auto’ can be
used to mention the same explicitly.

auto int Mark = 98;

Example

void main()
{
auto int i=10;
f1();
printf(“%d”, i) //10

}
void f1()
{
int i=40;
}

The identifier ‘I’ within main() and ‘i’ within the function f1() are different. Each has a scope
only within their own block. For each time of call to f1() new memory space will be allocated
and value 40 will be assigned.

Register: The register type identifier visible only within the function where it is defined. The
life and scope of the register identifier is only within the function. The register identifier will
allocate memory in the register. The keyword ‘register’ is mentioned in the identifier
declaration. It is good to register only important identifiers in register type because the
system will have a limited number of registers only. The system allocates main memory
when the register is not available. The address of operator & cannot be used.

register int Mark = 50;

Static: The identifiers in function will be allocated a memory newly for each function call and
the life of that variable will vanish when the function completes the execution and returns
the control back to the function calling statement. But the static identifiers are allocated a
memory only when the function is invoked, and the life of that exists until the completion of
the entire program. The visibility of static identifiers is only within the function. The
keyword ‘static’ has to be given in the identifier declaration.

55
static int i = 10;

Example
#include <stdio.h>
void f1();
int main()
{
int a = 10;
f1();
f1();
return 0;
}
void f1()
{
static int i=10;
i++;
int j=30;
printf("Static %d", i);
printf("Non Static %d", j);
}

The function f1() contains ‘i’ as static. So that is initialized only once when it is called for the
first time. The value increased will be kept as and continued from for the next function call
also. The output of above code is

Static 11
Non Static 30

Static 12
Non Static 30

External: The external identifier has lifetime, visibility and scope in the entire program. The
external identifier is accessible in another program by including a file in the header file. The
external variable can be defined only in the global declaration part of program structure. The
keyword’ extern’ has been mentioned explicitly to make an identifier as an external storage
class.

extern int i=10;


void main()

56
{
i = 10;
}

3.11 Multi file programs

The user defined program can be included as a header file. Through which the function
defined in one file can be called from another file. The program included in the header file
should not have a main() function. The concept allows to make the user defined functions
as library functions. The user file should be given within double quotes(“”).

The identifiers in one file can be accessed in another page only when that is declared with
the ‘extern’ keyword.

File2.c
extern int I =10;
void function1()
{
I++;
}

File1.c
# include “File2.c”
extern int I; // defined in another file but referred here
void main()
{

Key term

Function, Built-in Function, User defined Function, Prototype, Function Declaration,


Function Definition, Function Call, Parameter, Call by value, Call by Reference, Actual
argument/ Actual Parameter, Formal Parameter/ Formal Argument, Return value, Recursive
function, Storage, extern, auto, static, register, global variable, scope of variable.

Self Assessment
I Multiple choice questions.
1. Choose correct statement about Functions in C Language.

57
a) A Function is a group of c statements which can be reused any number of times.
b) Every Function has a return type.
c) Every Function may no may not return a value.
d) All the above.

2. The keyword used to transfer control from a function back to the calling function is
a) switch
b) goto
c) go back
d) return

3. Which of the following is a correct format for declaration of function?


a) return-type function-name(argument type);
b) return-type function-name(argument type){}
c) return-type (argument type)function-name;
d) all of the above

4. What is the scope of an external variable?


a) Whole source file in which it is defined
b) From the point of declaration to the end of the file in which it is defined
c) Any source file in a program
d) From the point of declaration to the end of the file being compiled

5. A function which calls itself is called a ___ function.


a) Self Function
b) Auto Function
c) Recursive Function
d) Static Function

6. A recursive function is faster than __ loop.


a) for
b) while
c) do while
d) None of the above

7. which of the following is default a storage class specifier?


a) auto
d) register
c) extern

58
d) volatile

8. what is the inital value of register storage class specifier?


a) 0
b) Null
c) Garbage
d) Infinite

9. What is the scope of static class specifier?


a) Within block
b) Within Program
c) Global Multiple files
d) None of the above

10. The value of static storage class


a) change during different function call
b) persist between different function call
c) increases during different function call
d) decreases during different function call

II Descriptive

1. What is program modularization?


2. Write the syntax of function declaration statement for the detail :
Function Name – Inverse
Number of Parameter – 2
Type of parameter- Integer
Return type: float
3. Explain when the call by reference can be used?
4. What way is a recursive function useful for iteration?
5. Describe the storage classes.
6. When can the call by reference function be used? Justify.
7. Write a program to implement choice based calculators using functions.
8. Write the program to find the simple interest using the function. Pass the principle
amount, duration of deposit and rate interest received from the user to function.
9. Write a program to swap two numbers using call by reference.

Answer: Self Assessment - MCQ


1. D
2. D

59
3. A
4. D
5. C
6. D
7. A
8. C
9. A
10. B
Summary
The module covers the concept of functions to implement the reusable coding structure. The
programming syntax of user defined functions declaration, definition and function call are discussed.
The different methods of passing values to the functions are explained. The concept of recursive
function to execute the function more than once by calling itself is discussed. The difference between
storage classes to maintain different visibility, accesses and scope of variables have been given in
detail to write an efficient and optimal program.

60
Module 4
ARRAYS, STRUCTURE and UNION
Objective
To learn derived data type an Array.
To learn user defined data types structure and union.
To implement structure to write application program

Outcome
Able to used array to handle homogeneous data
Able to use structure to write application programs.
Able to identify efficient data types to write a program.

Introduction
The module deals with two derived data types, an array and pointer. The method of
accessing array elements using pointers is discussed. The application program needs to
access more details of different types. The user defined data types structure and union
supports to group more than one different data type in a single group. The model covers the
programming statement to implement structure and union.

4.1 Arrays
Array is a derived data type. It is used to store more than one homogeneous type of values
in a single identifier. Elements in an array are identified by its position, it is referred to as the
index of an element. The index always starts from 0 and the last index is size-1. Single array
can hold any of the primitive data type values. The values of an array will be stored in a
continuous location. So, by knowing the location of the first element the remaining can be
assessed easily.

Value 1 2 3 4
0 0 0 0
Index 0 1 2 3
The index of operator square brackets([]) is used to access an element.

Array Declaration

The declaration of an array is like the declaration of a basic identifier, but the size of an array
has to be given using the index of operator. The size of an array can not be altered later.

Syntax

61
DataType ArrayIdentifierName[Size];

Example

int Marks[10];

The ‘Marks’ in an integer array can store a maximum of 10 elements from index 0 to 9.
The value of an array can be initialized during the declaration itself. The values are covered
within curly braces({}), within which the values are separated by comma(,).

Syntax

DataType ArrayIdentifierName [Size] = {Value1, Value2,..};

Example

int Marks[5] = {89, 90, 88, 98, 97};

Access Array Element


The array elements are accessed using the index position. The index position has to be given
within the index of the operator.

Marks[0] = 100;

The value in the 0th position of the index will be changed with new value 100.

4.2 Iterate array


All the elements of an array can be accessed continuously by writing the access statements
within the loop. The number of iterations can be defined early because the number of
elements are fixed. So, the ‘for’ loop may be the appropriate one.

The given program receives 5 elements of an array and does the sum of all the elements.
This program can be simplified to a single ‘for’ loop, but to give more clarity about the use
of iteration separate loops are used to get the value and to do the sum of elements.

#include <stdio.h>

int main()
{

62
int Marks[5];
int i, sum=0;
for(i=0;i<5;i++)
{
printf("Enter element %d :", i);
scanf("%d", &Marks[i]);
}

for(i=0;i<5;i++)
{
sum += Marks[i];
}
printf("Total Marks :%d", sum);
return 0;
}

4.3 Passing arrays to Function

All the elements of an array can be passed as parameters to function. The array identifier
always points to the address of the first element. By knowing that remaining elements can
be accessed. The below ‘printf’ statement displays the address of ‘Marks’ identifier.

printf(“Address : %d”, Marks); //Display address

So the address of the array can be passed to a function or entire array. In both the
possibilities the changes made in the formal array parameter will be reelected into actual
array parameters.

Passing All the elements

In order to pass all the elements of an array to function the index of the operator has to be
given in function declaration and function definition. The values of the actual array will be
copied into a formal array.

Syntax
ReturnType FunctionName(DataType []); // Function Declaration

ReturnType FunctionName(DataType Identifier[]) // Function Definition.


{

63
}

Example
#include <stdio.h>
void TotalMark(int[]); //Function Declaration

int main()
{
int Marks[5];
int i, sum=0;
for(i=0;i<5;i++)
{
printf("Enter element %d :", i);
scanf("%d", &Marks[i]);
}
TotalMark(Marks); //Function Call
printf("%d", Marks[4]); // 100 , Change in actual value
return 0;
}
void TotalMark(int M[]) // Function Definition
{
int i, sum=0;
for(i=0;i<5;i++)
{
sum += M[i];
}
M[4]=100; //Change mark in index 4
printf("Total Marks :%d", sum);
}

The changes made in formal argument M[4]=100 will be reflected in the actual argument.

Passing Address of an Array

The address of the array can be passed to function. In order to pass the address of an array
to function the pointer operator has to be given in function declaration and function
definition. The address of the actual array will be copied into a formal array pointer.

Syntax

64
ReturnType FunctionName(DataType *); // Function Declaration

ReturnType FunctionName(DataType *Identifier) // Function Definition.


{

Example
void TotalMark(int*); //Function Declaration

int main()
{
int Marks[5];
int i, sum=0;
for(i=0;i<5;i++)
{
printf("Enter element %d :", i);
scanf("%d",&Marks[i]);
}
TotalMark(Marks); //Function call
return 0;
}
void TotalMark(int *M) Function Definition
{
int i, sum=0;
for(i=0;i<5;i++)
{
sum += M[i];
}
printf("Total Marks :%d",sum);
}

4.4 Multi-dimensional array

The more than one dimension of homogenous values can be stored in an array. It consists
of row and column structure. The elements are accessed using row and column index. It uses
an index of operators separately for row and column, one is to specify the row and another
is to specify the column index.

65
5 3 6
8 40 5
0
25 30 8

This is a three rows and three columns array, mathematically it can be referred to as 3X3
matrix. The nested loop structure has to be used to iterate all the elements of an array. The
outer loop can be used to row and the inner loop can be used to access each column of the
row.

Declaration Syntax

DataType ArrayIdentifierName[RowSize][ColumnSize];

Example
int Mat[3][4]; //Three rows and 4 column array

Access Element

The row index and column index have to be specified to access an element. Row index ranges
from 0 to RowSize-1 and column index ranges from 0 to columnSize-1.

Mat[1][2]=100; //2nd row 3rd element is assigned with 100

The above matrix after the assignment statement will be


5 3 6
8 40 10
0
25 30 8

Example
The program to find the sum of all the elements in a two dimensional array.

#include <stdio.h>
void TotalMark(int[]);

66
int main()
{
int Mat[3][3];
int i,j, sum=0;
for(i=0;i<3;i++)
{
for(j=0; j<3; j++)
{
printf("Enter element %d %d:", i,j);
scanf("%d",&Mat[i][j]);
}
}

for(i=0;i<3;i++)
{
for(j=0; j<3; j++)
{
sum += Mat[i][j];
}
}

printf("Total Marks :%d",sum);


return 0;
}

4.5 String

String is a set of characters. In programming, an array of characters is used to form a string.


The values to an array can be given as single characters within single quotes(‘’). In another
way the value can be put into double quotes(“”). The size of an array will adjust to the
number of characters in a string.

Syntax

char ArrayName[Size]; //Without value


char ArrayName[Size]={‘char1’, ‘char2’,…}; //Fixed size and with value
char ArrayName[]={“String”}; //Value as string

67
Example

char Name[10];
char Name1[10]={‘L’, ‘i’, ‘g’, ‘h’, ‘t’};
char Name2[10]={“Status”};

Access String Array

The individual characters can be accessed using index value. The entire array can be accessed
as string. The format specifier %s is used to access as string. The address of operator & is not
applicable while access as string. The scanf() function given here used to get the value as
string.

char Name[10];
scanf(“%s”, Name); //Get value as string

The same is applicable in printing also.

Example
The program is to find if the given string is palindrome or not. The string is received in a
character array and the library function from string.h are used to do the comparison.

#include <string.h>
#include <stdio.h>

int main()
{
char s1[1000],s2[1000];
int l,i,j;
printf("Enter the string: ");
scanf("%s", s1);
l=strlen(s1);
for(i=l-1, j=0;i>=0;i--,j++)
{
s2[j]=s1[i];
}
s2[j]='\0';
if(!strcmp(s1,s2))
printf("string is palindrome");

68
else
printf("string is not palindrome");
return 0;
}

4.6 Structure

Structure is a user defined data type. It groups more than one primitive data type to create
user defined data types. It represents a record. The storage size of the structure is the sum
of the size of all the data types in it. It is a good practice to define the structure in the global
declaration part of the program.

Define Structure
The keyword ‘struct’ is used to define the structure. All the members of the structure are
covered by curly braces ({}). The definition of structure has to be terminated by semicolon
(;).

Syntax

struct StructureName
{
DataType Identifier1;
DataType Identifier2;
};

The identifiers of the structure are referred to as members.

Example

struct Book
{
int BookId;
char BookName[100];
};

Define Structure Variable

The identifiers of structure can be defined as like the variable is being defined for primitive
data type. The structure identifier has a separate copy of the structure member.

69
Syntax
struct StructureName IdentifierName;

Example
struct Book b1;

The identifier ‘b1’ is a variable of type Book.

The value for the structure identifier can be given along with the declaration itself. The
values have to be given within curly braces({}). The values are taken in the order of members
within the structure.

struct Book b1={10, “Programming in C”};

The value of the members after the above declaration will be


BookId 10
BookName Programming in C

Access Structure Member

The structure members are accessed using the dot (.) operator along with the identifier of
structure.

Syntax
IdentifierName.member;

Example

b1.BookId = 40;

All the operations being performed on primitive type identifiers can also be performed on
structure members.

4.7 Array of Structure Variable

The structure variable can be defined as an array. This feature is highly applicable for
applications to handle the set of record values as a single unit.

70
Syntax
struct StructureName ArrayIdentifierName[size];

The value can be assigned to each record during the declaration. The value has to be covered
with curly braces.

struct StructureName ArrayIdentifierName[size]={{value1, value2..}, {value1, value2..}}

Each internal curly braces are treated as one record. Individual records are accessed using
index position.

ArrayIdentifierName[index].member = value;

Example

The program here is to find the result of 5 students. The structure of Students has been
defined with necessary members. The structure identifier of size 5 has been defined in the
main() function.

#include <stdio.h>
struct Student
{
int RegNo;
char Name[100];
int m1,m2,m3,total;
float average;
char result;

};
int main()
{
struct Student S[5];
int i;
for (i=0; i<5;i++)
{
printf("Enter Student Register No :");
scanf("%d", &S[i].RegNo);
printf("Enter Student Name :");

71
scanf("%s", S[i].Name);
printf("Enter Mark1 :");
scanf("%d", &S[i].m1);
printf("Enter Mark2 :");
scanf("%d", &S[i].m2);
printf("Enter Mark3 :");
scanf("%d", &S[i].m3);

S[i].total = S[i].m1 + S[i].m2 + S[i].m3;


S[i].average = S[i].total/3;

if(S[i].m1>=40 && S[i].m2>=40 && S[i].m3>=40 )


S[i].result='P';
else
S[i].result='F';
}

printf("\nResult of students");
printf("\nReg No\t\tName\t\t\tTotal\t\tAverage\t\tResult");
for (i=0; i<5;i++)
{

printf("\n%d\t\t%s\t\t%d\t\t%f\t\t%c",S[i].RegNo,S[i].Name,S[i].total,S[i].average,S[i].resul
t);
}
}

4.8 Passing Structure to Function

As like passing primitive data type values to functions, the structure identifiers can also be
passed as parameters to function. The parameter type in function declaration and function
definition should use structure name. The structure can also be passed as value or reference.

ReturnType FunctionName(struct StructureName); //Function Declaration

ReturnType FunctionName(struct StructureName Identifier) //Function Definition


{

72
FunctionName(StructureIdentifier); //Function Call

Example

The program to find the result of student marks has been done in this program. The result
calculation is implemented in a functional module. The value received for the structured
identifier in main() is passed as parameter to the calculation function.

#include <stdio.h>
struct Student
{
int RegNo;
char Name[100];
int m1,m2,m3,total;
float average;
char result;

};
void ResultCalculation(struct Student);
int main()
{
struct Student S;
int i;

printf("Enter Student Register No :");


scanf("%d", &S.RegNo);
printf("Enter Student Name :");
scanf("%s", S.Name);
printf("Enter Mark1 :");
scanf("%d",&S.m1);
printf("Enter Mark2 :");
scanf("%d",&S.m2);
printf("Enter Mark3 :");
scanf("%d",&S.m3);
ResultCalculation(S);

}
void ResultCalculation(struct Student STemp)

73
{
STemp.total = STemp.m1 + STemp.m2 + STemp.m3;
STemp.average = STemp.total/3;

if(STemp.m1>=40 && STemp.m2>=40 && STemp.m3>=40)


STemp.result='P';
else
STemp.result='F';
printf("\nResult of students");
printf("\nReg No\t\tName\t\t\tTotal\t\tAverage\t\tResult");

printf("\n%d\t\t%s\t\t%d\t\t%f\t\t%c",STemp.RegNo,STemp.Name,STemp.total,STemp.av
erage,STemp.result);

4.9 Self-Referential Structure

The structure having the pointer type member to itself is known as self-referential structure.
The linked data structure can be formed using self-referential structure. structures pointing
to the same type of structures are self-referential in nature.

Syntax
struct StructureName
{
DataType MemberIdentifier;
struct StructureName *MemberIdentifier; //Self reference
};

Example:
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;

74
}

The ‘link’ is a pointer member of type node. The pointer points to itself.

4.10 Union

Union is a user defined data type groups primitive data type into a single unit. The primitive
data identifiers declared within the union are called as members. The functionality of the
union is the same as the structure, but the only difference is that the size of the union is the
size of the data member with maximum size. All the members in the union share a single
storage space. The keyword ‘union’ is used to define the union data type.

Union Declaration

union UnionName
{
DataType Identifier;
DataType Identifier1;
};

Union Variable declaration

union UnionName UnionIdentifier;

Access Union Member

UnionIdentifier.Member

Example

union Item
{
int Id;
float Price;
char Avail;
};
int main()
{

75
union Item Code;
Code.Id=1;
Code.Price=4.5;
printf("%f",Code.Price); //4.5000
printf("\n%d",Code.Id); // 1083179008 – Garbage value
return 0;
}

Among the data members of the union, the float member takes the highest storage. So the
union Item has been allocated a memory of 4 bytes. The values assigned to all the data
members will occupy the same space. The member a value assigned as latest only available
in memory. In above code Code.Price have been assigned as latest. It over writes the content
assignment Code.Id=1. So the printing of Code.Id=1 is showing garbage value.

Key Term

Array , homogeneous, index, multi dimensional, address, pointer, string, structure, record,
union, self-reference, member.

Self Assessment
I.Multiple Choice Questions
1. Which of the following are themselves a collection of different data types?
a) string
b) structures
c) char
d) all of the above

2. User-defined data type can be derived by___________


a) struct
b) enum
c) typedef
d) all of the above

3. Which operator connects the structure name to its member name?


a) –
b) <-
c) .
d) Both <- and .

76
4. What is the correct syntax to declare a function Display() which receives an array of
structure in function?
a) void Display(struct *var);
b) void Display(struct *var[]);
c) void Display(struct var);
d) none of the above

5. The size of a union is determined by the size of the __________


a) First member in the union
b) Last member in the union
c) Biggest member in the union
d) Sum of the sizes of all members

6. Members of a union are accessed as________________


a) union-name.member
b) union-pointer->member
c) both union-name.member & union-pointer->member
d) none of the mentioned

7. What is the similarity between a structure, union and enumeration?


a) All of them let you define new values
b) All of them let you define new data types
c) All of them let you define new pointers
d) All of them let you define new structures

8. A union cannot be nested in a structure


a) True
b) False

9. The______ function returns the number of characters that are present before the
terminating null character.
a) strlength()
b) strlen()
c) strlent()
d) strchr()

10. In C, if you pass an array as an argument to a function, what actually gets passed?
a) Value of elements in array
b) First element of the array

77
c) Base address of the array
d) Address of the last element of array

II.Descriptive Questions
1. Define an Array.
2. How the elements of an array are accessed?
3. Write a program to find the determinant of matrix and matrix transpose.
4. In what factor does the union differ from Structure?
5. How can self referential structure be used to implement list data structure?
6. How are the array and address of memory related?
7. Write a program to swap two numbers by passing the address of variables to function.
8. Write a program to find the total marks of 10 students by using array of structures.
9. Write a program to implement library system using structures.
10. Write a program to compare two strings which are stored in character array.

Answer: Self Assessment - MCQ


1. B
2. D
3. C
4. A
5. C
6. C
7. B
8. B
9. B
10. C
Summary
The derived data types array is discussed. The programming syntax to implement the multi
dimensional array incorporating the matrix is given an explanation. The user defined data
types, structure and union are discussed. The concept of self referential structure to
implement the linked data structure is covered.

Module 5

78
POINTERS and FILES

Objective
To learn the concepts of pointers.
To handle possible errors during program execution.
To use files in a program.

Outcome
Able to use pointer in program
Able to relate pointers and an array
Able to use files in a program to store content permanently.

Introduction
The module covers the concept of pointer, pointer declaration. The various operations in the
pointer and the relationship between pointers and an array has been given an explanation.
The content in a file is non-volatile. The programming syntax to do various operations in a
file and the built-in functions supporting the file operations are discussed in detail.

5.1 Pointers

Pointer is a variable that can store the memory address of another variable. The value of
another variable can be accessed using the pointer variable. It allows quick access of value
and also supports low level programming. The address operator (&) and value of operator
(*) used to point the address and value in that address respectively. The operator (*) used
to declare the pointer variable and also used to access the value from the location being
pointed by the pointer variable.

The address of a variable is accessed by mentioning the address of the operator in front of
the pointer variable. The value of operator is mentioned in front of the pointer variable to
access the value in a memory location being pointed by it.

The pointer variables are classified based on the value in a location being pointed by it.
• Integer pointer : The pointer identifier holds the address of location having
integer value.
• Float Pointer : The pointer identifier holds the address of location having float
type value.
• Character Pointer : The pointer identifier holds the address of location having
character type value.
• Structure Pointer : The pointer identifier holds the address of user defined
structure type identifier.

5.2 Pointer Declaration

The pointer variable is declared using asterisk operator (*).

DataType *IdentifierName;

79
Example
int *pt;

The identifier ‘pt’ is a pointer that can point to a memory address having integer value. In
other words, the address of an integer variable can be assigned to an integer pointer.

int m=10;
int *pt;
pt = &m;

The address of constant can not be assigned to a pointer variable.

5.3 Access Value using Pointer

The value of the location being pointed pointer identifier can be accessed using value of
operator (*). After assigning an address of variable to pointer variable, both of them will
point to the same memory location. So the value being changed by either of that will reflect
in both.

Example

int m=10;
int *pt;
pt = &m;
printf(“%d”, *pt); // 10

(*pt) ++;

printf(“%d”, *pt); // 11
printf(“%d”, m); // 11
m++;
printf(“%d”, *pt); //12

The expression (*pt) ++ increases the value in a location being pointed by a pointer variable
pt.

Assume that X101 is the address located for variable ‘m’ and it is having a value 10.
m
X101 10

The statement pt= &m; assigns the address of ‘m’ to ‘pt’.

pt
X201 X101

The value in location X101 can be accessed using ‘m’ using ‘pt’ which has this address.

80
5.4 Passing Pointer to Function

The pointer identifier can be passed as an argument to function. It is similar to assigning a


value of one variable to another. The address in the actual argument is copied into the formal
argument. The pointer operator (*) have to be given function declaration and function
definition.

The changes made on formal arguments within the function will be reflected in actual
pointer arguments. The actual pointer argument may have the address of another variable.
So the changes in formal argument also affect the value of the original variable.

Example
void addOne(int* ptr) {
(*ptr)++; // adding 1 to *ptr
}

int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
printf("%d",i); // 11
return 0;
}

Pointer ‘p’ points to the variable ‘i’. The pointer variable is passed as parameter to function,
so formal argument ‘ptr’ will also have the address of ‘i’. So the changes made through the
formal parameter ‘ptr’ will do the changes in value ‘i’.

Assume X101 is the location allocated for variable ‘i'.

i
X101 10

The statement p=&i assigns the address of ‘I’ (X101) to the location allocated for ‘p’.

p
X201 X101

After function call value in a location of ‘p’ will be assigned to the location allocated for
formal pointer parameter ‘ptr’.

ptr
X301 X101

5.5 Pointer and Array

81
An array is a homogeneous data structure. The values of an array will be stored continuously.
The array identifier contains only the address of starting location. So array itself a pointer

int a[5] = {10,20,30,40,50};

Addres X100 X104 X108 X112 X116


s
Value 10 20 30 40 50

The integer in C programming is allocated 4 bytes of memory. So an array a[5] will be


allocated 20 bytes of memory location and identifier ‘a’ will be assigned the starting address
of the location allocated.
a
Xc410 X100

The index operation a[0] will be expanded as


*(a+0) 🡪 *(X100+0) 🡪 *(X100) 🡪 10

The value of operator (*) from an address X100 access the value in that location. Adding an
integer with integer pointer will add 4 bytes. In order to access the 3rd value that is the
value in index 2, either the index operator ([]) can be used or the index can be added with
an array variable. The expression a[2] is same as *(a+2).

The array identifier can be assigned to another pointer variable simply using an assignment
operator. Thereafter both will point to the same memory location. So the changes made
through one variable will affect another.

int a[5]={10,20,30,40,50};

int *p;
p=a; // Assign address of ‘a’ to pointer ‘p’
p[1]=44;
printf(“%d”, a[1]); //44 – Changed using pointer

5.6 Array of Pointers

Array of pointers is an array of pointer variables; it is also known as a pointer array. It stores
the address of pointer variables or memory locations.

Syntax

DataType *PointerIdentifier[size];

Example

82
int *ptr[3];

The pointer ‘ptr’ can store 3 addresses which are having integer values.

int a=10, b=20, c=30;


ptr[0] = &a;
ptr[1] = &b;
ptr[2] = &c;

a
Xc120 10

b
Xd130 20

c
Xx310 30
ptr
Xssm2 X400

X400 X404 X408


Xc120 Xd130 Xx310

The pointer ‘ptr’ will be allocated 3 continuous locations and the starting address will be
assigned to ‘ptr’. Each location of the ‘ptr’ pointer array is stored with addresses of three
different integer variables. The values of all these three variables can be accessed using a
single pointer array ‘ptr’.

printf("%d",*ptr[0]); //10

printf("%d",*ptr[1]); //20

printf("%d",*ptr[2]); //30

The statement *ptr[1] will be expanded as


*(*(ptr+0)) 🡪 *(*(X400+0)) 🡪 *(*(X400)) 🡪 *(Xc120) 🡪 10

Internally the expression gets evaluated faster than evaluating the direct variable. Accessing
the pointers is faster than accessing identifiers, because the pointer has a direct address, so
it reduces the address lookup time.

5.7 Files

83
The collection of information stored is known as a file. It is permanent. The content of the
file can be accessed in the C Program. The value given as an input and received as an output
from the program can be stored in file for later access.

The following way of access are allowed


• Sequential access
• Character by character
• Line by line
• Random access
• Record wise access as structure data type.
FILE is an in-built structure used to create file pointers. The file pointer is used to track and
access the content in file.

5.8 Operations in File


1. File Open
2. File Close
3. Read
4. Write

The library functions available in the stdio.h header file are used to do all the file operations.
The functions and the descriptions are given in table.
Function Syntax Description
fopen() FilePointer = fopen(..) Function used to open a file
fclose() fclose(FilePointer) Function used to close the file
getc() int getc(FilePointer) Function to get one character
from file. The return value in
a form of ASCII.
putc() putc(Value, FilePointer) Writes one character into a
file at the location being
pointed by file pointer.
getw() int getw(FilePointer) The function returns an
integer value.
putw() putw(IntegerValue, The function writes the
FilePointer) integer value into file. The
value may be a constant or
variable.
fprintf() fprintf(FilePointer, Write the value into a file.
“FormatSpecifier”, Used to write any type of
Value) value. Value can be given
through the identifier. The
second parameter is used to
specify the format specifier of
value.
fscanf() fscanf(FilePointer, Read the value from the file.
“FormatSpecifier”, The type of value is specified
identifier) using the format specifier in
the second parameter. The

84
value read from the file will
be stored in a variable given
in the third parameter.
fseek() fseek(FilePointer, int The function used to move
offset bytes, int position) the file pointer. The second
parameter specifies the
number of bytes to be
moved. The third parameter
is to specify the position from
where the move to be taken.
Three position values are (0 –
From beginning, 1 – from
current, 2 – from end). Used
for random access of files.
ftell() long ftell(FilePointer) Function returns the current
position of file pointer. Used
for random access of files.

File Open
The file can be opened using FILE structure. The mode of opening a file has to be specified
while opening a file. The file should exist when opened in read mode. The file will be created
newly when it opens for write operation and also when it is not available. Opening an existing
file for write operation will clear previous content.

The file will contain read and write pointers. Both the pointers will be in the beginning of the
file when it is opened. The read pointer moves ahead when read operation is performed on
file. The write pointer will move ahead when the write operation is performed.

File Mode
The file can be opened in three modes, the respective symbolic character has to be given
while opening a file.
Read : r
Write : w
Append: a

Syntax
FILE *FilePointer = fopen(“FileName”, “Mode”);

Example

FILE *fp = fopen(“Sample.txt”, “r”); //open in read mode.

More than one mode of file open is allowed, the respective symbolic characters have to be
given together.

FILE *fp=fopen(“Sample.txt”, “rw”); //open in read and write mode.

85
File close

The file has to be closed after completing all the operations. The file pointer pointing to the
file will be removed from the memory. The function close() is used to close the file.

FilePointer.close();

File Read
The content of the file can be read as character, line or record. The respective functions have
to be used. The file open mode has to give a symbolic constant as ‘r’. The file should already
exist to open in read mode. Opening a non-existing file is an error. The content of the file
can be read until it reaches the end of file (EOF).

Example
The program reads the content of the file. Each time it reads one character using the getc()
function. The reading operation continues until it reaches EOF.

#include <stdio.h>
void main()
{
char c;
FILE *fp;
fp = fopen(“File1.txt”, “r”);
while(c=getc(fp)!=EOF)
printf(“%c”, c);
fclose(fp);
}

File Write

The write operation allows to write the content into a file. The file has to be opened inwrite
mode. The symbolic constant for write operation is ‘w’. The non-existing file will be created
when it has been opened in write mode. The content of the existing file will be erased while
opening it in a write mode. The file can be opened in append mode to retain the existing
content and continue the write operation.

Example
The program writes the line received in the gets() function into a file using the fprintf()
function.

#include<stdio.h>
void main()
{
char c[100];
FILE *fp;

86
fp= fopen(“Sample.txt”, “w”);
printf(“Enter the string :”);
gets(c);
fprintf(fp,”%s”,c);
fclose(fp);
}

Key Terms

Pointe, File, Array, Array of Pointers, Open, Close, Write, Read, Seek, File Pointer, Sequential
access, random access, Record.

Self Assessment
I. Multiple Choice Questions
1. A pointer is
a) A keyword used to create variables
b) A variable that stores address of an instruction
c) A variable that stores address of other variable
d) All of the above

2. Which of the following does not initialize ptr to null (assuming variable declaration of a as
int a=0;)?
a) int *ptr = &a;
b) int *ptr = &a – &a;
c) int *ptr = a – a;
d) All of the mentioned
3. One of the uses for function pointers in C is __________
a) Nothing
b) There are no function pointers in c
c) To invoke a function
d) To call a function defined at run-time
4. What does the following declaration mean?
int (*ptr)[10];
a) ptr is array of pointers to 10 integers
b) ptr is a pointer to an array of 10 integers
c) ptr is an array of 10 integers
d) ptr is an pointer to array
5. What is (void*)0?
a) Representation of NULL pointer
b) Representation of void pointer

87
c) Error
d) None of above

6. The operator used to get value at address stored in a pointer variable is


a) *
b) &
c) &&
d) ||

7. What are the basic operations of file?


a) Open
b) Close
c) Read
d) All of these

8. The functions used to get the location of read pointer ____


a) tellg()
b) tellp()
c) seekg()
d) seekp()

9. What is a C FILE data type?


a) FILE is like a Structure only
b) FILE is like a Union only
c) FILE is like a user define int data type
d) None of the above

10. What is the need for closing a file in C program?


a) fclose(fp) closes a file to release the memory used in opening a file.
b) Closing a file clears Buffer contents from RAM or memory.
c) Unclosed files occupy memory and PC hangs when on low memory.
d) All the above

II.Descriptive questions

1. Describe the use of pointers?


2. How can a pointer be passed as an argument to function?

88
3. Differentiate Array of Pointer and Pointer to an Array.
4. What are the file modes supported in C programming?
5. What is the use of EOF?
6. Write a program to find the sum of an element in an array using pointer to an array.
7. Write a program to read alternate characters from a file.

Answer: Self Assessment - MCQ


1. C
2. A
3. D
4. B
5. A
6. A
7. D
8. A
9. A
10. D

Summary
The concept of pointer and pointer declaration are discussed in this module. The various
operations in the pointer and the relationship between pointers and an array are explained.
The programming syntax to do various operations in a file and the built-in functions
supporting the file operations are discussed in detail.

Further Reading

Online Links
https://www.programiz.com/c-programming
https://www.geeksforgeeks.org/c-programming-language/
https://www.tutorialspoint.com/cprogramming/index.htm

Glossary Terms

Identifier – The name given to the value or function being referred to in the program. The
naming convention must be followed.
Keywords – The predefined reserved words provided in the programming language to write
syntactic oriented semantic statements.
Variable – Variable is an identifier used to refer to a value in a program, The value of a

89
variable is modifiable anywhere in a programming statement.
Constant – Constant is an identifier used to refer to a value in a program, The value of a
constant is not modifiable anywhere in the program.
Control Statement: The programming statement used to change the sequential flow of
program execution. They are also referred to as selection control statements.
Iterative statement: - The programming statement used to execute a set of statements more
than once based on the condition.
Function – A group of programming statements grouped under a single name for reusability.
The function reduces the size of the program.
Call By Value – Calling the function definition by passing value or identifier as actual
argument is call by value. The actual parameter and formal parameter are treated as two
separate copies.
Call By Reference – Calling the function definition by passing an address of identifier as actual
argument is call by reference. The actual parameter and formal parameter both will refer to
the value in the same location.
Storage Class - The storage class is a concept used to define an identifier in various scope,
lifetime and visibility. Auto, Static, Register and Extern are the four storage classes in C
Programming.
Recursive - The function calling to itself is called as recursive. The self reference has to be
maintained on a recursive conditional basis.
Pointer – Pointer is a concept used to refer to the memory address of a value. It provides
faster execution of programs.
Array – A derived data type stores more than one homogeneous type values.
Multi-Dimensional Array: An array used to store the value in rows and column order to form
a matric.
Structure – Structure is a concept used to define a user defined data type.
Self-Referential Structure – The structure having a data member of its own type is Self-
Referential structure.
Union – The union is a concept used to define a user defined data type. Size of the union will
be equal to the size of the data member with maximum storage space. All the data members
will share the same memory location.
Array of Pointer – The pointer having addresses of more than one value is known as an array

90
of pointer.
Address of Operator – The operator used to refer or access the memory address of a value.
The Address of operator symbol is (&).
Value of Operator – The operator used to refer or access the value through memory address.
The value of operator symbol is (*).
File mode – The file mode is to specify the purpose of opening a file. Their basic file modes
are read, write and append.
File pointer – The pointer identifier of FILE structure type used to point the address of a file
in a memory location.
EOF – The character constant points to the end of file content.

91

You might also like