Programming in C PDF
Programming in C PDF
PROGRAMMING IN
C
CONTENT AT A GLANCE
www.EngineeringBooksPdf.com
PROGRAMMING IN C
MODULE 1
MODULE 2
MODULE 3
Unit 1 : Functions
Unit 2 : Variables and Storage Classes
MODULE 4
Unit 1 : Arrays
Unit 2 . Strings
Module 5
Unit 1 : Pointers
Unit 2 : Macros and Preprocessors
Module 6
Unit 1 : Structures
Unit 2 : Unions
TABLE OF CONTENTS
MODULE 1
www.EngineeringBooksPdf.com
PROGRAMMING IN C
1.1 Introduction
1.2 Problem Solving Techniques
1.3 Algorithm
1.3.1 Properties of an Algorithm
1.3.2 Basic Statements used and Examples
1.4 Flow chats
1.4.1 Types of Flowcharts
1.4.2 Symbols used in Flowcharts
1.4.3 Writing Expressions in Computer Language
1.4.4 Examples
1.5 Programming by using Simple Flowcharts
1.5.1 Adding first N Numbers
1.5.2 Fahrenheit Scale Convert into Celsius Scale
1.5.3 Area and perimeter of a Triangle
1.6 Questions
1.7 Programing Exercise.
Unit 2 : C Fundamentals
2.1 What is C ?
2.2 Program Structure in C
2.3 Executing a C program
2.4 C character set
2.5 Identifiers and Keywords
2.5.1 Keywords
2.6 Basic Data Types
2.7 Modifiers to Basic Data Types
2.8 Constants
2.8.1 Integer constants
2.8.2 Decimal Integer Constants
2.8.3 Octal Integer Constants
2.8.4 Hexadecimal Integer Constants
2.8.5 Unsigned and Long Integer Constants
2.8.6 Floating Point Constants
2.8.7 Character Constants
2.8.8 String Constants
2.9 Variables
2.9.1 Variable Declarations
2.9.2 Assigning Values to Variables
2.9.3 Declaring a variable as constant
2.10 Questions
2.11 Programing Exercise.
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Unit 3 : Operators In C
3.1 Introduction
3.2 Arithmetic Operators
3.3 Relational Operators
3.4 Logical Operators
3.5 Conditional Operator
3.6 The size of Operator
3.7 Precedence of Operators
3.8 Questions
3.9 Programing Exercise
MODULE 2
unit 1 : Input Output Statements
1.1 Introduction
1.2 Formatted I / O Functions
1.3 The printf() Function
1.3.1 Application of printf() Function
1.3.2 Escape Sequence in printf() Function
1.3.3 Minimum Field Width Specifier (MFWS)
1.3.4 The Precision Specifier
1.4 The scanf() Function
1.5 Unformatted I / O Function
1.6 Character Input/Output(I/O)
1.7 String I / O
1.8 Questions
1.9 Programming exercises
2.1 Introduction
2.2 The if – else statement
2.3 Nested -ifs
2.3.1 The if -else - if Ladder
2.4 Switch Statement
2.4.1 Rules of Switch Statement
2.4.2 Difference Between if Statement and Switch Statement
2.5 Questions
2.6 Programming Exercise.
www.EngineeringBooksPdf.com
PROGRAMMING IN C
3.1 Loops
3.2 The for loop
3.2.1 The for Loop Variations
3.2.2 The Infinite Loop
3.2.3 The Comma Operator in The for Loop
3.2.3 Declaring Variables Inside The for Loop
3.2.4 The Nested for Loop
3.3 While Loop
3.3.1The Infinite while Loop
3.4 Do-while Loop
3.4.1 Limitation of Do-while Loop
3.5 Break Statement
3.5.1 Break Statement Within Loops
3.5.2 Can break Statement be Used Inside if Construct
3.6 Continue Statement
3.7 Goto and Labels
3.8 Questions
3.9 Programming Exercise
MODULE 3
Unit 1 : Functions
1.1 Introduction
1.2 What is a Function?
1.2.1 Functions are Used in C for the Following Reasons
1.3 Structure of Function
1.3.1 Function Definition
1.3.2 Function Prototypes
1.3.3 Function Invocation
1.4 Types of Arguments
1.5 Types of Functions
1.5.1 A Function With No Arguments And No Return Value
1.5.2 A Function With No Arguments and Returns a Value
1.5.3 A Function With Arguments and Returns No Value
1.5.4 A Function With Arguments and Returning a Value
1.6 Questions
1.7 Programing Exercise
www.EngineeringBooksPdf.com
PROGRAMMING IN C
MODULE 4
UNIT 1: Arrays
1.1 Introduction
1.2 Defining an Array
1.2.1 Declaring Single Dimensional Array
1.2.2 Array Index
1.3 Initialization of One Dimensional Array
1.3.1 Compile Time Initialization
1.3.2 Run Time Initialization
1.4 Entering Data Into The Array
1.5 Reading Data From Array
1.6 The Size of an Array
1.7 Multidimensional Arrays
1.7.1 Declaration of Two-dimensional Array
1.7.2 Two-Dimensional Array Initialization
1.8 Processing a Two Dimensional Array
1.8.1 Entering Data into Two Dimensional Array
1.8.2 Printing data of Two Dimensional Arrays
1.9 Passing Arrays as Arguments
1.10 Questions
1.11 Programing Exercise
UNIT 2: Strings
2.1 Introduction
2.2 Declaring a string
www.EngineeringBooksPdf.com
PROGRAMMING IN C
MODULE 5
Unit 1 : POINTERS
1.1 Introduction
1.2 How variables are stored in memory?
1.3 What is a Pointer?
1.4 Pointer Declaration
1.4.1 Pointer Declaration Styles
1.4.2 Multiple Declarations
1.5 Pointer Initialization
1.5.1 The Address of Variables
1.5.2 Null Pointers
1.5.3 Understanding pointers
1.6 Pointer Expressions
1.7 Pointer Arithmetic
1.7.1 Pointer increment and decrement
1.7.2 Pointer Addition and Subtraction
1.7.3 Pointer Multiplication and Division
1.8 Pointers and Function
1.8.1 Call by Reference
1.8.2 Call by Value
1.9 Pointers and Arrays
1.9.1 Pointers and One Dimensional Array
1.9.2 Pointers and Strings
1.10 Questions
1.11 Programing Exercise
www.EngineeringBooksPdf.com
PROGRAMMING IN C
MODULE 6
Unit 1: STRUCTURES
1.1 Introduction
1.2 Defining a Structure
1.3 Declaring Structure Variables
1.4 Accessing Structure Members
1.4.1 Assigning Values to the Members
1.4.2 Structure Initialization
1.5 Questions
1.6 Programing Exercise
unit 2:Unions
2.1 Introduction
2.2 Declaration of Union
2.3 Working With Unions
2.4 Difference between Structures and Unions
2.5 Questions
2.6 Programing Exercise
www.EngineeringBooksPdf.com
PROGRAMMING IN C
*****
MODULE 1
1.1 Introduction
To develop the solution for the given problem, the following programming
techniques are used.
www.EngineeringBooksPdf.com
PROGRAMMING IN C
1.3 Algorithm
The word ‘Algorithm’ is the name of one Persian author meaning rules of
restoration and reduction. Once the problem is analyzed, its solution is
broken into a number of sample steps. A problem in a finite sequence is
called an algorithm.
1.3.1 Properties of an Algorithm
i. Algorithm always begins with the word ‘Start’ and ends with the word
‘Stop’
ii. Step wise solution is written in distinguished steps. This is as shown in
example 1.1
Start
Step 1:
Step 2:
Step 3:
.
.
.
Step n:
End
10
www.EngineeringBooksPdf.com
PROGRAMMING IN C
iii. Input Statement: Algorithm takes one or more inputs to process. The
statements used to indicate the input is Read a or Input b. This is
illustrated in example 1.2
Read x, y
Z=x*y
i) Sequential Order
ii) Conditional Order
iii) Iterative Order
11
www.EngineeringBooksPdf.com
PROGRAMMING IN C
i) Sequential Order
Each step is performed in serial fashion I.e. in a step by step procedure
this is illustrated in example 1.5
a) Syntax :
if (condition)
Then {set of statements S1}
if (condition)
Then {set of statements S1}
else
Then {set of statements S2}
12
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Step
1 : Start
Step
2 : Read marks
Step
3 : Is marks greater than 60 ?
Step
4 : if step 3 is TRUE
print ’GRADE A’
Step 5 : Other wise
print ’GRADE B’
Step 6 : End
Example 1.7 Format of Conditional order Algorithm
c) Syntax – Nested if else (condition)
If (condition 1)
Then S1
Else
If (condition 2)
Then S2
Else
Then S3
Here if and else condition is in a nested fashion this is more suited for the
programs have been multiple conditions. This is illustrated in example 1.8
Here algorithm repeats the finite number of steps over and over till
the condition is not meet. Iterative operation is also called as
looping operation. This is illustrated in example 1.9
13
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Advantages
i. Communication – it is better way of communicating the logic of a
program solution.
ii. Effect analysis – with the help of flow charts problem can be analyze in
a effective way
iii. Effective coding – flow charts acts as a blue print during the system
analysis
iv. Proper debugging – flow chart helps in debugging process.
Limitations
i. Alterations and modifications: If alterations are required, the flowchart
may require re-drawing completely.
1.4.1Types of Flowcharts
14
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The flow chart being symbolic representation standard symbols is used for
each specific operation. These symbols are used to represent the
sequence of operations and flow of data and documents required for
programming. Flow should be from top to bottom. The most commonly
used symbols are shown in the figure 1.1
Subroutine
Database
Document printout
15
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Print A
Start
Read a
c=a +b
Stop
1.4.4 Examples
i) Draw a flowchart to find greater of 2 numbers
Start
Read a, b
Yes No
Is a < b
Print a Print b
Stop
16
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Start
Initialize
Count C=0
Sum S=0
S=S+1
No yes
Is count
Print Sum S
C=50?
Stop
Start
READ n
A=1
Sum = Sum+A*A
A = A+1 Is a =n?
Print Sum
Stop
1.5.2 Fahrenheit Scale Convert into Celsius Scale
17
www.EngineeringBooksPdf.com
PROGRAMMING IN C
START
READ FARH
CENTI (FARH-32)/1.8
PRINT CENTI
END
Solution: Formula for calculating the area of a triangle with the length of
the three sides as a, b, c is given by A s * ( s a ) * ( s b ) * ( s c ) , where s is
abc
the semi-perimeter of the triangle, s . The perimeter of the
2
triangle is given by P = a+b+c.
Input
Start a, b, c
abc
s
2
A s * ( s a) * ( s b ) * ( s c )
P=2*s
Output
A,P
End
Input A,B,C
Step 2: [Check the validity of given inputs and compute the area if the
inputs valid]
IF ( (A+B)>C OR (B+C)>A OR(C+A)>B) then
S (A+B+C)/2
18
www.EngineeringBooksPdf.com
PROGRAMMING IN C
AREA = SQRT(S*(S-A)*(S-B)*(S-C))
Write “Area of triangle is “,AREA
ELSE
Write “Given inputs are invalid”
1.6 Questions
*****
MODULE 1
Unit 2 : C Fundamentals
2.1 What is C ?
19
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Note that Portability means that it is easy to adapt software written for
one type of OS to run on another type.
20
www.EngineeringBooksPdf.com
PROGRAMMING IN C
1. #include <stdio.h>
2. #include “stdio.h”
21
www.EngineeringBooksPdf.com
PROGRAMMING IN C
vi.All sections except the main() function may be absent when they
are not required in any C program.
i. Creating a program
ii. Compiling the program
iii. Linking the program with functions that are needed from the C
library.
iv. Executing the program
22
www.EngineeringBooksPdf.com
PROGRAMMING IN C
System Ready
Source Program
Edit Source program
Syntax
Errors?
Object Code
Logic Error
Data Error
Logic & Data
Errors?
Correct Output
Stop
In MS DOS :
23
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Identifiers are the names given by user to various program elements such
as variables, functions and arrays. The rules for identifiers are given below.
24
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Invalid Identifiers:
I) 5thstandard : first character must be a letter
II) “Sam” : illegal character (“ ”)
III) Emp-no : illegal character( - )
IV) Reg no : illegal character (blank space)
2.5.1 Keywords
Key words or Reserve words of the C language are the words whose
meaning is already defined and explained to the C language compiler.
Therefore Reserve words can not be used as identifiers or variable names.
They should only be used to carry the pre-defined meaning. For example
int is a reserve word. It indicates the data type of the variable as integer.
Therefore it is reserved to carry the specific meaning. Any attempt to use
it other than the intended purpose will generate a compile time error. C
language has 32 keywords. Following are some of them
Some compilers may also include some or all of the following keywords.
25
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Modifiers are used to alter the meaning of basic data types to fit various
needs. Except the type void, all others data type can have various
modifiers preceding them
Table 2.3 shows the list of modifiers that can be used with each basic data
types.
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Memory Requirement
Data Types Modifiers
Bits Byte
Character i) Char 8 1
ii) signed char 8 1
iii) unsigned char 8 1
Integer i) int 16 2
ii) signed int 16 2
iii) unsigned int 16 2
iv) short int 16 2
v) long int 32 4
vi) signed long int 32 4
vii) unsigned long int 32 4
Floating point i) float 32 4(6 digits
ii) double 64 ofprecision)
iii) long double 128 8(10 digits of
precision)
16(10 digits of
precision)
2.8 Constants
There are four basic types of constants in C. They are integer constants,
floating-point constants, character constants and string constants. Integer
and floating point constants represent numbers. They are also called
numeric- type constants.
27
www.EngineeringBooksPdf.com
PROGRAMMING IN C
28
www.EngineeringBooksPdf.com
PROGRAMMING IN C
For most of the PC’s the typical maximum value of decimal integer
constant is 32767. This is equivalent to 77777 in octal or 7FFF in
Hexadecimal.
29
www.EngineeringBooksPdf.com
PROGRAMMING IN C
These constants are also called as ‘real constants’. The real constant can
be written in two forms namely factorial form and exponential form. If the
value of the constant is either too small or too large the exponential form
is used. The interpretation of a floating-point number in exponential form
is same as scientific notation, except that base 10 is replaced by the letter
E (or e). Thus the number 1.5 x 10 -3 can be written as 1.5 E -3 or 1.5 e -
3
. This is equivalent to 0.15e-2 or 15e-4. Etc.,
In the exponential form the part of the constant before ‘e’ is called
exponent. This is shown in example 2.6
3.5 e +5
Mantissa Exponent
30
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Constant Value
‘A’ 65
‘b’ 98
‘3’ 51
‘ ’ (blank space) 32
These values will be same for all the computers that utilize ASCII
character set. There values will be different for the computers that utilize
an alternate character set. For example IBM mainframe computers utilize
EBCDIC (extended information code) character set, in which each
individual character is numerically encoded with its unique 8-bit
combination EBCDIC is entirely different from ASCII character set.
31
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Hi
How are
You ?
Because the escape sequence new line character ‘\n’ is embedded in the
string. Data types range is given in the below table
2.9 Variables
For Ex : sum = a+b. In this equation sum, a and b are the identifiers or
variable names representing the numbers stored in the memory locations.
Rules to be followed for constructing the Variable names(identifiers)
32
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Syntax :
Data type ‘variable’
For example:
int a; float c; char name;
int sam; double count;
If two are more variables of the same data type has to be declared they
can be clubbed as shown in example given below.
short int a, b, c ;
long int r, s, t ;
The above declarations cab also be written as :
short a, b, c;
long r, s, r;
33
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Syntax:
Variable name = value;
For Example: :a = 10; int lvalue = 0;
It is also possible to assign a value to a variable at the time the variable is
declared. The process of giving initial value to the variable is called
initialization of the variable.
For Example:
int a=10, b=5;
float x=10.5, y=1.2e-9
The data item can be accessed in the program simply by referring to the
variable name. Data type associated with the variable cannot be changed.
However variables hold the most recently assigned data. This is shown in
the example2.9 given below.
Int a, b, c;
Char d;
---
a = 3;
b = 5;
c=a+b;
---
a = 4;
b = 5;
c=a-b;
We may want the value of the certain variable to remain constant during
the execution of the program. We can achieve this by declaring the
variable with const qualifier at the time of initialization.
For example,
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The above statement tells the compiler that value of variable must not be
modified during the execution of the program. Any attempt change the
value will generate a compile time error.
2.10 Questions
35
www.EngineeringBooksPdf.com
PROGRAMMING IN C
*******
MODULE1
36
www.EngineeringBooksPdf.com
PROGRAMMING IN C
UNIT 3. Operators IN C
3.1 Introduction
Unary operators:
Operators Actions
- Unary minus
++ Increment
- - Decrement
Binary operators:
Operator Action
+ Addition
37
www.EngineeringBooksPdf.com
PROGRAMMING IN C
- Subtraction
* Multiplication
/ Division
% Modules
Unary Minus ( - )
This symbol is used to indicate the negative sign of the value. For
example
a = -10;
b = -a;
Here the value -10 is assigned to a and the value-a to b.
Y = y+1
Is written as
Y = y++
These are two types of increment and decrement operators. They are
a. Prefix increment (++i)
b. Postfix increment (i++)
c. Postfix decrement (- -i)
d. Postfix decrement (I - -)
In the prefix increment, first increment and then do operation .In postfix
increment, first do the operation and then increment. In prefix
decrement first decrement and then do operation. In postfix decrement,
first do the operation and then decrement. This is shown in the example
3.1
Output
i=1
i=2
i=3
38
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Explanation :
In the first statement original value of i is displayed. In the second
statement since prefix is used, first i is incremented i.e. ++i = i +1, I =
2. Then the value is printed hence i = 2.
In the third statement, final value is retained and displayed.
(ii) Let i = 1;
Print f (“ i = %d \n ”, i );
Print f (“ i = %d \n ”, i + +);
Print f (“ i = %d \n ” );
Output
i=1
i=1
i=2
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Modules
Case 1 :
int a = 5;
int b = 2;
int c ;
39
www.EngineeringBooksPdf.com
PROGRAMMING IN C
c = a / b;
Print f ( “the quotient c = %d \ n”, c);
Output:
The quotient c = 2
Case 2 :
int a = 5;
int b = 2;
float c ;
c = a / b;
Print f ( “the quotient c = %f \ n”, c);
Output :
The quotient c = 2.5
int a = 20;
int b = 5;
float c, d;
c = a / b;
d = a%b
Print f ( “the quotient = %f \ n”, c);
Print f ( “the reminder = %f \ n”, d);
Output :
The quotient = 4
The reminder = 0
Operator Action
< Less than
<= Less than or equal to
> Greater than
=> Greater than or equal to
The associatively of these operators is from left to right. The following are
the two equality operators associated with the relational operators.
Operator Action
40
www.EngineeringBooksPdf.com
PROGRAMMING IN C
== equal to
|= not equal to
Example
Let I, j, k be integer variables, Where the values are 1, 2, 3
respectively.
Operator Action
&& and
|| or
! not
In logical operation the operands are themselves logical. The individual
logical expression is compared, using logical operators. The result
evaluates which is represented by integer values 0 or 1. The logical AND
evaluates to true condition only if both of the operands are true. Logical
OR evaluates to true condition if any one of the condition is true. The
logical expression can be changed from false to true or from true to false
with negation operator. This is as shown in example 3.5
Logical OR ( | | )
41
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Case 1 :
Let a = 4, b = 5, c = 6
(a < b) && (b < c)
= (4 < 5) && (5 < 6)
= true && true
= true
= value=1
Case 2 :
Let a = 4, b = 5, c = 6
(a < b) || (b > c)
= (4 < 5) || (5 > 6)
= true || false
= true
= value=1
Case 3 :
Let a = 4, b = 5, c = 6
! (a < b) || (b > c)
= ! (4 < 5) || (5 > 6)
= ! (true) || false
= false
= value=0
42
www.EngineeringBooksPdf.com
PROGRAMMING IN C
case 1
Let i be integer variable.
int i = 0;
( i < 1) ? 0 : 50
Expression i < 1 is true
Hence the entire conditional expression takes the value 0. Otherwise the
value is 50
case 2
Let a, b be integer variables.
int a, b, c;
a = 2, b = 5;
c = ( a = = b) ? 5 : 10
Expression (a = = b) is evaluated and this results in false
condition. Hence the conditional expression takes the value 10.
i.e C = 10.
The sizeof operator is one of the special operator. This operator returns
the size of its operand in bites. The sizeof operator always precedes its
operand. This is as shown in the example 3.8
Output
Integer requires : 2 bytes
Float requires : 4 bytes
Double requires : 8 bytes
Character requires : 1 byte
43
www.EngineeringBooksPdf.com
PROGRAMMING IN C
3.8 Questions
44
www.EngineeringBooksPdf.com
PROGRAMMING IN C
*****
MODULE 2
1.1 Introduction
Classification:
Console I / O function
45
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The printf() function is used to print the different types of output. This is
given below.
46
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Output:
C programming is easy
Output:
The value of integer a is5
The value of float is 10.3
In the above instance instead of using two printf() statements only one
printf() can be used. This is as shown below
Output
The value of integer a is 5
The value of float is 10.3
The characters are always given in single quote and strings are enclosed
in quote (double).
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Hi
How are
You
Example 1.1 Escape Sequence Usage
An integer placed between the % sign and format code is called minimum
field width specifier or % number format code; ex. %5d. If string or
number to be printed is longer than that minimum it will printed as such.
Minimum field width specifiers are used to make the O/P such that it
reaches the minimum length specified. This is done by padding. Default
padding is done with spaces. This is used most commonly produce table
in which column line up.
If we wish to pad the space (if any) with zeros, place zero before MFWS.
For example %d, will pad a number with ‘zeros’ if numbers is less than
five digits. So that the total length is 5. %d will pad a number with
‘apace’. If number is less than five digits. So that the total length is five.
48
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Double count;
Count = 10.51324; // here total digits are 8, includes dot ( . )
operators.
Output
10.51324
10.51324 // inserts 2 blank spaces. So that total length = 10
digits
0010.51324 // inserts 2 zeros. So that total length = 10 digits
printf(“5.4f\n”, 176.012543871);
printf(“2.8d\n”, 5214);
printf(“8.12S\n”, “This is C language book”);
Output
176.012543871
00005214
This is C language book
Example 1.3: Precision specifier
49
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The scanf() reads the input data from standard input device. i.e.
keyboard. The general format of the scanf() function is scanf( “format
string” list of arguments ); where format string consists of format
specifiers and arguments consists of address of variables. To this
corresponding address the data read from keyboard is sent. The address
of the variable is denoted by ampersand symbol ‘&’ (it is called as
‘’address of the operator). Some format specifiers as shown in the table
1.1 is used. Example 1.4 shows how to work with scanf() function.
Note that the values that are supplied through keyboard must be
separated by either blank tabs or newlines. Escape sequences are not
included in scanf() function.
50
www.EngineeringBooksPdf.com
PROGRAMMING IN C
(I) getchar()
(II) putchar()
(III) getch()
(IV) getche()
Output
a
d
51
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Drawback with getchar() is that buffers the input until ‘ENTER’ key is
pressed. This means that getchar does not see the characters until the
user presses return.This is called line buffered input. This line buffering
many leave one or more characters waiting in the input queue, which
leads to ‘errors’ in interactive environment. Hence alternatives to
getchar() is used.
.
The putchar( ) function:
Single characters can be displayed using the C library function putchar.
This function is complementary to the character input function getchar.
The putchar function, like getchar, is a part of the standard C I/O library.
It transmits a single character to a standard output device. The character
being transmitted will normally be represented as a character type
variable. It must be expressed as an argument to the function, enclosed
in parentheses, following the word putchar.
The general syntax is
putchar(character variable)
where character variable refers to some previously declared character
variable.
Alternatives to getchar()
getch()
getche()
The getch() function reads a single character at a time and it waits for
key press. It does not echo the character on the screen. The getche() is
same as getch()/ but the key is echoed. This is illustrated below.
char ch;
Ch = getch() // let key press = k
putchar(ch);
Output
52
www.EngineeringBooksPdf.com
PROGRAMMING IN C
1.7 String I / O
In order to read and write string of characters the functions gets() and
puts() are used gets() function reads the string and puts() function takes
the string as argument and writes on the screen. This is illustrated below
Output:
Enter your name: Fredric /* string as entered by user*/
The name entered is: Fredric
1.8 Questions
53
www.EngineeringBooksPdf.com
PROGRAMMING IN C
(b) The value for i = decimal integer, j =floating point and k = character.
(c) The values for I and j = long integer and k =double floating point
54
www.EngineeringBooksPdf.com
PROGRAMMING IN C
char c;
Write an appropriate printf function for each of the following situations,
assuming that all integers will be displayed as decimal quantities.
*****
MODULE 2
55
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Control structures
x=0;
printf(. . .);
a=b+c;
Braces { and } are used to group statement into a block. So that they are
syntactically equivalent to a single statement. These braces are used to
group multiple statements in if, else, structures, while or for loops. In the
conditional controlled structure, a condition is given. This condition is
logically evaluated. Depending upon whether the condition evaluates to
either true or false state. The appropriate branching is taken.
Unconditional branching means transferring the control of the program to
a specified statement without any conditions. Let us study each one in
detail.
56
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Syntax: i) if (expression)
Statement;
else
statement; /* else part is optional*/
ii) if (expression)
{
Statement1;
Statement2;
...
Statement n;
}
else
{
Statement1;
Statement2;
...
Statement n;
}
(i) if (x > 0)
printf( “%i”, x);
(ii) if (a > b)
printf( “ a is greatest ”);
else
printf( “ b is greatest ”);
(iii)if ( a = = b )
{
printf( “ a & b are equal ” )
printf( “ x/a is equal to x/b ” )
}
Some invalid forms of if are given below.
(i) if ( a > b );
printf( “a is greatest” )
(ii) if ( a > b )
57
www.EngineeringBooksPdf.com
PROGRAMMING IN C
statement1;
statement2;
statement3;
(iii) if ( a > b )
{
Statement 1;
statement 2;
...
Statement n;
};
Example1
Write a program to calculate greatest of 3 numbers.
# include <stdio.h>
main()
{
int a, b, c;
printf(“Enter three numbers”);
scanf (“ %d %d %d “, &a, &b, &c);
if ( ( a > b) && (a > c))
printf (“\n a is greatest”);L
if ( ( b > a) & & (b > c))
print f (“\n b is greatest”);
if ( ( c > a) & & (c > b))
print f (“\n c is greatest”);
}
Example2
# include <stdio.h>
main()
{
int a;
58
www.EngineeringBooksPdf.com
PROGRAMMING IN C
if( a )
{
if ( b )
{
Statement1;
---
Statement n;
}
if ( c )
{
Statement1;
---
Statement n;
}
else
{
Statement1;
---
Statement n;
}
}
else
{
Statement1;
---
Statement n;
}
The final else is associated with if (a) and not associated with if c,
because it is not in the same block.
59
www.EngineeringBooksPdf.com
PROGRAMMING IN C
if ( expression )
Statement:
else
if ( expression )
Statement:
else
if ( expression )
Statement:
...
else
Statement:
The condition are evaluated from top, towards down. As soon as a true
condition is found, the statement associated with it is executed and the
rest of the ladder is bypassed. If none of the conditions are true, the final
else is executed. If final else is not present, no action taken place if all
other conditions are false. This is given in the below example
# include <stdio.h>
main()
{
int i;
i = 0;
clrscr();
printf(“Enter your choice (1-4);”);
s scanf (“ %d” , & i);
if ( i == 1)
printf(“\n your choice is 1”);
else if ( i = = 2)
printf(“\n your choice is 2”);
else if ( i = = 3)
printf(“\n your choice is 3”);
else if ( i = = 4)
printf(“\n your choice is 4”);
else
printf(“\n invalid choice”);
}
Output:
60
www.EngineeringBooksPdf.com
PROGRAMMING IN C
switch (expression)
{
case constant1;
Statement sequence
break;
case constant2;
Statement sequence
break;
case constant3;
Statement sequence
break;
...
default
Statement sequence
}
Switch, case and default are key words and statement sequence can be
single statement or a compound statement. If it is compound statement it
must be enclosed in braces.
61
www.EngineeringBooksPdf.com
PROGRAMMING IN C
# include <stdio.h>
main()
{
char ch()
printf(“\n Enter a lower case alphabeet (a-z);”);
scanf (“ %d” , & ch);
if ( ch<’a’ || ch>’z’)
printf(“\n Character is not lower case alphabet”);
else
switch (ch)
{
case ‘a’ :
case ‘e’ :
case ‘i’ :
case ‘o’ :
Case ‘u’ :
printf(“\n Entered Character is vowel”);
break;
case ‘z’ :
printf(“\n Entered Character is last alphabet”);
break;
default;
printf(“\n Entered Character is consonant”);
}
}
Explanation: each case need not have its own statements. A set of case
can have common statements to be executed. This is as shown in the
above program. The default can either end with break or not. This
depends upon program structure.
# include <stdio.h>
main()
{
int a()
printf(“\n Enter a an integer (10-13);”);
scanf (“ %d” , & a);
switch (a)
62
www.EngineeringBooksPdf.com
PROGRAMMING IN C
{
case 10 :
printf(“\n You have entered 10”);
break;
case 11 :
printf(“\n You have entered 11”);
break;
case 12 :
printf(“\n You have entered 12”);
break;
case 13 :
printf(“\n You have entered 13”);
break;
default;
printf(“\n Invalid choice”);
}
}
Output :
Enter an integer : 11
You have entered : 11
Note : observe here the case labels. This in accordance with the program
flow labels need not be always in the order of 1, 2, 3 . . etc.,
1. write a program to choose color using switch case statements.
# include<stdio.h>
main()
{
int a;
printf(“ choose the color u like; red-11, blue-22, violet-13: ”);
scanf(“%d “, &a);
switch(a)
{
case 11:
printf(“/n you have selected RED colour “);
case 22:
printf(“/n you have selected BLUE colour “);
case13:
printf(“/n you have selected VIOLET colour “);
default:
printf(“/n Invalid choice“);
63
www.EngineeringBooksPdf.com
PROGRAMMING IN C
}
}
Output:
choose the color u like; red-11, blue-22, violet-13: 22
you have selected BLUE colour
you have selected VIOLET colour
Invalid choice
Analysis:
Observe here the out put. Since the user has entered the choice as 22 ,
expected out put is only the line you have selected BLUE color. But the
program has executed the case statements where a match is found and
all subsequent cases and default also. The reason is break clause is not
used. If break clause is used after each case , the problem is eliminated.
This is shown in the below example.
/* a program to choose color using switch case statements */
# include<stdio.h>
main()
{
int a;
printf(“ choose the color u like; red-11, blue-22, violet-13: ”);
scanf(“%d “, &a);
switch(a)
{
case 11:
printf(“/n you have selected RED colour “);
break;
case 22:
printf(“/n you have selected BLUE colour “);
break;
case13:
printf(“/n you have selected VIOLET colour “);
break;
default:
printf(“/n Invalid choice“);
}
}
Output:
choose the color u like; red-11, blue-22, violet-13: 22
you have selected BLUE colour
64
www.EngineeringBooksPdf.com
PROGRAMMING IN C
2.5 Questions
www.EngineeringBooksPdf.com
PROGRAMMING IN C
1. Write a program to input two numbers from keyboard and find the
result of subtraction of greater number – smaller number.
2. Input a year from keyboard and determine whether it is leap year or
not.
3) Create a menu driven program to input a character from user and
Determine:
i. Whether it is alphabet or not.
ii. Whether it is in upper – case or not. Using switch case.
4) Write a program to compute net amount from the given quantity
purchased and rate per quantity. Discount @10% is allowed if quantity
purchased exceeds 100. Use the formula
Net Amount = (Quantity Purchased x Rate Per Quantity) – Discount
******
66
www.EngineeringBooksPdf.com
PROGRAMMING IN C
MODULE 2
3.1 Loops
1. for loop
2. while loop
3. do-while loop
Syntax explanation:
(1) Initialization:
This is some kind of expression which initializes the control variable or
(index varaible) This statement is carried out only once before the start of
the loop. e.g. i = 0;
(2) Condition:
The condition is evaluated at the beginning of every loop and the loop is
only carried out while this expression is true. e.g. i < 20;
67
www.EngineeringBooksPdf.com
PROGRAMMING IN C
#include<stdio.h>
int main()
{
int i;
for(i=0; i<5; i++)
printf("Hello \n");
Output: Hello
Hello
Hello
Hello
Hello
Analysis:
Observe the program carefully. Inside the body of the main() function,
the statement declares an integer variable i.. In the for statement .the
first expression is initialization statement ie i=0, expression that initializes
the integer variable i to 0.
The third expression in the for statement is i++ in this case. This
expression is evaluated and the integer variable i is increased by 1 each
68
www.EngineeringBooksPdf.com
PROGRAMMING IN C
time after the statement inside the body of the for statement is executed.
In other words, when the for loop is first encountered, i is set to 0, the
expression i<5is evaluated and found to be true, and therefore the
statements within the body of the for loop are executed. Following
execution of the for loop, the third expression i++ is executed
incrementing i to 1, and i<5 is again evaluated and found to be true, thus
the body of the loop is executed again. The looping lasts until the
conditional expression i<5 is no longer true. Summary of evacuation of
for statement is as given in the table below.
Loop Initialization Test condition Loop expression Output
step expression i=0 i<5 True/False i++
1 i=0 True i=1 Hello
2 i=1 True i=2 Hello
3 i=2 True i=3 Hello
4 i=3 True i=4 Hello
5 i=4 True i=5 Hello
6 I=5 False Stops execution
#include <stdio.h>
main()
{
int i;
printf("Hex(uppercase)\t Hex(lowercase)\t Decimal\n");
for (i=0; i<16; i++)
printf("%X %x %d\n", i, i, i);
}
OUTPUT
Hex(uppercase) Hex(lowercase) Decimal
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
A a 10
B b 11
C c 12
D d 13
E e 14
F f 15
69
www.EngineeringBooksPdf.com
PROGRAMMING IN C
ANALYSIS
Observe the program carefully. Inside the body of the main() function,
the statement declares an integer variable i. The printf statement declares
format of the output on the screen. In the for statement .the first
expression is initialization statement ie i=0, expression that initializes the
integer variable i to 0.
The third expression in the for statement is i++ in this case. This
expression is evaluated and the integer variable i is increased by 1 each
time after the statement inside the body of the for statement is executed.
In other words, when the for loop is first encountered, i is set to 0, the
expression i<16is evaluated and found to be true, and therefore the
statements within the body of the for loop are executed. Following
execution of the for loop, the third expression i++ is executed
incrementing i to 1, and i<16 is again evaluated an d found to be true,
thus the body of the loop is executed again. The looping lasts until the
conditional expression i<16 is no longer true.
. The statement contains the printf() function, which is used to display the
hex numbers (both uppercase and lowercase) converted from the decimal
values by using the format specifiers, %X and %x.
main( )
{
int p,n, count;
float r, si;
for(count = 1; count <=3; count = count +1)
{
printf(“Enter values of p,n and r”);
scanf(“%d %d %f”, & p, & n, & r);
si = p * n * r / 100;
printf(“Simple interest = Rs %f \n”, si);
70
www.EngineeringBooksPdf.com
PROGRAMMING IN C
}
}
4. Write a program to print upper case and lower case alphabets using
using char data type in for loop.
/* a program to print upper case and lower case alphabets using using
char data type in for loop */
1) for(i=1;i<4; i=i+1)
Here in the initialization part instead of i=i+1, the statements i++ or
i+=1 can also be used.
2) for(i=1;i<4; )
{
Printf(“ helo for loop”);
i=i+1;
}
Here in the for loop statement increment is not given, but given in the
body of the statement. Semicolon after the condition is mandatory.
3) int i=2;
for(;i<4; i=i+1)
Printf(“ helo for loop”);
Here in the for loop statement initialization is not given, but given
before the statement. Semicolon before the condition is mandatory.
4) int i=2;
for(;i<4;)
71
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The comma (,) operator is basically used in conjunction with for loop
statement. This permits two expressions to be used in initialization and
count section of the for loop. Only one test expression is allowed in the for
loop. The syntax of this is given below.
for (expression1a, expression1b; expression2; expression3a,
expression3b)
Here expression 1a and expression 1b and expression 3a expression 3b
are separated comma operator.
For example consider the below for statement
for(i=0,j=2;j<=0;j--,i++)
Here i and j are the two different variables used and they are separated
by comma operator. Operation of this is given in the below example:
#include <stdio.h>
main()
{
int i, j;
OUTPUT:
1 - 0 = 1
2 - 1 = 1
3 - 2 = 1
4 - 3 = 1
5 - 4 = 1
6 - 5 = 1
7 - 6 = 1
72
www.EngineeringBooksPdf.com
PROGRAMMING IN C
8-7=1
#include<stdio.h>
main()
{ int j;
for(int i=0; i<5;i++)
{
j=i*i;
printf(“The value of j is%d”,j);
The concept of using a loop within a loop is called nested loop. If a for
loop contains another for loop statement, such loop is called nested for
loop.. A nested for loop can contain any number of for loop statements
within itself. Usually only two loops are used. In this the first loop is called
outer loop and the second is called inner loop. These types of loops are
used to create matrix. In this the outer loop is used for counting rows and
the internal loop is used for counting columns. The syntax and example
program is given below.
SYNTAX:-
for (initializing ; test condition ; increment / decrement)
{
statement;
for (initializing ; test condition ; increment / decrement)
{
body of inner loop;
}
statement;
}
Example: Write a program to generate a matrix of order4*4 containg
symbol*(asterisk).
73
www.EngineeringBooksPdf.com
PROGRAMMING IN C
* * * *
* * * *
* * * *
****
The simplest of the three loops is the while loop. The while-loop has a
condition and the statements .The syntax is given below.
while (condition)
{
statements;
}
The statement block, surround by the braces { and }.If there is only one
statement in the statement block, the braces can be discarded. Consider
an example of using the while statement.
1) Write a program to understand the use of while loop.
74
www.EngineeringBooksPdf.com
PROGRAMMING IN C
#include <stdio.h>
main()
{
int a;
printf("Enter a character:\n(enter x to exit)\n");
while (a != `x')
{
a = getc(stdin);
putchar(a);
printf("\n");
}
printf("\nOut of the while loop. Bye!\n");
}
OUTPUT
Enter a character:
(enter x to exit)
i
H
x
x
Out of the while loop. Bye!
ANALYSIS
The char variable a is initialized before the the while Statement. In the
while condition the relational expression c !=`x' is tested. If the
expression returns 1, which means the relation still holds,the statements
under the while are executed. The looping continues as long as the
expression returns 1i.e returns True value. However when the user enters
the character x, which makes the relational expression return 0, the
looping stops.
You can also make a while loop infinite by putting 1 in the expression
field, like this:
while (1) {
statement1;
statement2;
.
.
75
www.EngineeringBooksPdf.com
PROGRAMMING IN C
.
}
The while and for loops test the termination condition at the beginning of
the loop. By contrast, the do-while loop, tests at the bottom after making
each pass through the loop body; the body is always executed at least
once. The syntax of the do is
do
statement
while (expression);
#include<stdio.h>
int main(void)
{
int pass-word= 15;
int code;
int i=3;
do
{
printf("Type the password to enter.\n");
scanf("%d", &code);
if (code==15)
printf("Right code. You can Enter\n");
76
www.EngineeringBooksPdf.com
PROGRAMMING IN C
else
("Wrong code. No Entry\n");
i=i-1:
}
while(i!=0)
Output:
13
Wrong code. No Entry
15
Right code. You can Enter
Analysis:
Here do part is executed to know the password. If it is right, entry is
given otherwise not. Loop will repeat only for three set of inputs. For the
fourth set variable i value does not satisfy the while condition. Hence loop
is quit.
In Do-while, the loop the is executed as least once before checking the
validity condition. In Do-while structure entry to the loop is automatic
(even with invalid input).Choice is given only for the continuation of the
loop. Such problems are deemed to be lack of control. Example for such
problem is given below.
77
www.EngineeringBooksPdf.com
PROGRAMMING IN C
231
Enter the number to be reversed: 0
0
Analysis:
The above program reverses a number that is entered by the user. It
does this by using the modulus % operator to extract the right most digit
into the variable r_digit. The original number is then divided by 10, and
the operation repeated whilst the number is not equal to 0.If user enters
the number other than zero, program works. If user enters 0(zero), then
also the do part is executed, violating the condition at while. This means
its possible to enter a do { } while loop with invalid data. Hence it is
better to avoid the usage of Do-while statement. Its easy to avoid the use
of Do-while construct by replacing it with other constructs. The above
program can be written without Do-while construct. This is shown below.
while( value != 0 )
{
r_digit = value % 10;
printf("%d", r_digit);
value = value / 10;
}
printf("\n");
}
78
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Output
79
www.EngineeringBooksPdf.com
PROGRAMMING IN C
1
2
3
4
Analysis:
Here break statement is given with respect to the if condition. When
variable i value gets equal to four, loop gets terminated because of break
statement.
for ( ; ; )
{
scanf("%d" , &t);
if ( t==10 )
break ;
}
printf("End of an infinite loop...\n");
main()
{
int c;
OUTPUT
Enter a character:
80
www.EngineeringBooksPdf.com
PROGRAMMING IN C
(enter x to exit)
H
I
x
Break the infinite while loop. Bye!
The break does not work with if. It only works only with in loops and
switches. After observing the sample programs where break is used in
conjunction with if structure inside the for loop and while loop, the
common wrong assumption is that the break statement can be used
inside if construct. Thinking that a break refers to an if construct when it
really refers to the enclosing while or for loop has created some high
quality bugs. This is illustrated in the example below.
#include <stdio.h>
int main()
{
int i;
printf(“Enter your choice from 1-3, where apple-
1,Orange-2, grapes- 3, Enter 4 to exit “);
scanf(“%d”,&i);
if(i==1)
Printf(“Your choice of fruit is Apple “);
if(i==2)
Printf(“Your choice of fruit is Orange“);
if(i==3)
Printf(“Your choice of fruit is Grapes“);
if (i == 4)
break;
}
}
/* This program reports error because break is used with if construct */
Instead of breaking a loop, a need to stay in the loop but skip over some
statements within the loop may occur. To do this, the continue statement
is used. The continue statement takes the control to the beginning of the
loop bypassing the statements inside the loop which have not yet been
executed. The continue statement can only be used within the body of a
while, do, or for statement. For better control over the program, like a
break statement, continue is generally used in conjunction with if
structure within loops. When continue is used the next iteration of a do,
for, or while statement is determined as follows:
81
www.EngineeringBooksPdf.com
PROGRAMMING IN C
3) Write a program to find the sum Using the continue statement in for
loop.
/* Using the continue statement */
#include <stdio.h>
main()
{
int i, sum;
sum = 0;
for (i=1; i<8; i++)
{
if ((i==3) || (i==5))
continue;
sum += i;
}
printf("The sum of 1, 2, 4, 6, and 7 is: %d\n", sum);
}
OUTPUT
The sum of 1, 2, 4, 6, and 7 is: 20
ANALYSIS:
Program is to calculate the sum of the integer values of 1, 2, 4, 6, and 7.
because the integers are almost consecutive, a for loop is built in lines
9_13. The statement sum += i; sums all integers from 1 to 7 except for 3
and 5,.3nad 5 are skipped in the for loop by using continue statement.
82
www.EngineeringBooksPdf.com
PROGRAMMING IN C
#include <stdio.h>
main ()
{
Int x;
x = 0;
while (x < 10)
{
++x;
if (x % 2 == 0)
{
continue;
}
printf ("%i is an odd number.\n", x);
}
Output
1 is an odd number.
3 is an odd number.
5 is an odd number.
7 is an odd number.
9 is an odd number.
83
www.EngineeringBooksPdf.com
PROGRAMMING IN C
for ( ... )
statement
for ( ... )
{
...
if (disaster)
goto error; /* Here semicolon is associated with the label
error*/
}
error:Statemnt; /* Here colon(:) is associated with the label error*/
Analysis:
Here error is a label name that tells the goto statement where to jump.
Label name is placed in two places: One is at the place where the goto
statement is going to jump (note that a colon must follow the label
name), and the other is the place following the goto keyword. The rules to
name a variable also applies to label also. Also, the place for the goto
statement to jump can appear either before or after the statement. Tehy
are called forward goto or backward goto statements respectively.
Goto statement must be used in seldom. The programs written with goto
are unreliable and hard to debug. The goto Statements are practically not
necessary, and it is almost always easy to write code without it. However
a goto may be necessary for exiting a loop from within a deeply nested
loop.
Such as breaking out of two or more loops at once. since it can only The
break statement be used from the inner most loop only, it cannot be
used instead of goto in nested structure. Functioning of the goto
statement is given in the below example.
#include <stdio.h>
int main()
{
int i, j;
84
www.EngineeringBooksPdf.com
PROGRAMMING IN C
}
}
printf( "Loop is quit. i = %d\n", i );
Output:
Outer loop executing. i =0
Inner loop executing. j =1
Outer loop executing. i =1
Inner loop executing. j =2
Outer loop executing. i =2
Inner loop executing. j =1
Jumped to stop. I=2
3.8 Questions
*****
85
www.EngineeringBooksPdf.com
PROGRAMMING IN C
MODULE 3
Unit 1 : Functions
1.1 Introduction
The function takes a data from main () function and returns a value. To
invoke a function call is made in the main () function. The function which
sends the data to the function is called as the Calling Function and the
function which is called by the calling function is called as the Called
Function. This is described as given below.
Function 1 Function 2
Sending the data
………….. ……………..
……………..
……………
…………….
Calling is Finding
made some value
Returning a value
www.EngineeringBooksPdf.com
PROGRAMMING IN C
#include <stdio.h>
int main (void)
{
printf ("Programming is interesting.\n");
return 0;
}
This program prints the message “Programming is interesting” at the
output terminal. The same program can be written using the function
concept as given below.
#include <stdio.h>
void printMessage (void)
{
printf ("Programming is interesting.\n");
}
int main (void)
{
printMessage ();
return 0;
}
Here the function called print Message () is used to print the message.
More about functions is dealt in the following sections.
1.2.2 Classification
87
www.EngineeringBooksPdf.com
PROGRAMMING IN C
1. Function definition
2. Function declaration
3. Function invocation
The function definition is the C code that implements what the function
does. It contains two parts. The first part is function header and second
part is function body. Function definition has the following syntax
In the first line of the above code function header int sum (int x, inty)
It has four main parts
88
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Function Header
1) Data type
The data type in the function header tells the type of the value returned
by the function. This is also called as return type. Any of the basic data
type such as int, float, char etc may appear in the data type part of the
function. The data types are assumed to be of type int if they are not
shown explicitly. When a function is not returning any value it may be
declared as type void. For example,
(ii) Consider a function which just shows a message on the screen. In this
function there is no need to return any value to the calling program. The
data type of such function is void. This is a special specifier that indicates
absence of data type.
89
www.EngineeringBooksPdf.com
PROGRAMMING IN C
2) Function name
counter();
square();
message();
output();
3) Arguments List
The arguments are also called as parameters. This tells what arguments
the function needs when it is called (and what their types are).More than
one argument is called arguments list. The arguments are optional. Each
parameter consists of a data type specifier followed by an identifier, like
any regular variable declaration (for example: int x) and which acts within
the function as a regular local variable. They allow to pass arguments to
the function when it is called. The different parameters are separated by
commas. Data type of the function parameters is not mandatory and it is
based on function requirements. The structure of arguments is given
below.
void can also be used in the function's parameter list to explicitly specify
that the functions to takes no actual parameters when it is called. For
example, function printmessage could have been declared as:
void printmessage ()
{
Printf( “I am learning functions in c“);
90
www.EngineeringBooksPdf.com
PROGRAMMING IN C
4) Function Body
Whatever is written with in the curly braces { } below the function header
is called is the body of the function. It contains the declarations and
statements necessary for performing required task. The function body
contains three parts:
2. Function Statements
That actually performs task of the function.
return;
return (expression);
return;
return 3;
return n;
return ++a;
return (a*b);
The data type of the return expression must match that of the declared
function data type. This is shown in the below example.
91
www.EngineeringBooksPdf.com
PROGRAMMING IN C
All identifiers in C need to be declared before they are used. This is true
for functions as well as variables. For functions the declaration needs to
be done before the first call of the function. There are two ways to do
this. They are
In this approach the function called is defined before the main () function.
ie defining before main().Function definition comprises of function header
and the function body . The function definition itself can act as an implicit
function declaration. Hence the complier knows what functions are used in
main() before entering the main().Syntax is
For example consider a simple adding program which defines the function
before it is called.
/* This program allows the user to input two numbers, then passes
those two numbers into a sum function, and finally prints the returned
sum.*/
#include <stdio.h>
int sum (int n1, int n2) /* Function header*/
{
int answer; /*Function body */
answer = n1 + n2; /*Put the sum of the two numbers
into answer */
return answer(); /* Exit function and return answer
*/
}
main ()
{
92
www.EngineeringBooksPdf.com
PROGRAMMING IN C
int number1,number2,total;
printf ("What is the first number? ");
scanf ("%d", &number1);
printf ("What is the second number? ");
scanf ("%d", &number2);
Analysis:
I. Here int sum (int n1, int n2) is a user defined function. That is, it is
a custom function that programmer has created. It is defined before
the main ().
II. Function int sum()accepts two integer values, n1 and n2 from
main() calculates the sum and returns an integer result using the
return statement
III. The function sum () has two parts one is function header, int sum
(int n1, int n2) and other is function body. This header reveals that
the function name is sum (), the arguments passed are int n1 and
int n2 and it return data type is of int. The statements written
within the curly braces are called function body.
IV. Within the main function user is prompted for two numbers. Here
the main function calls the sum function by passing the two
numbers as arguments and then storing the return value into total.
Functions such as scanf and printf, used in mani() are called library
functions. They exist in a pre-defined library of C (stdio.h)
In the above example the function is defined before the main program.
For many programmers, this is a rather illogical way to work, as they
want the main function of the program to be at the beginning, rather than
user defined functions. If main function is defined before user defined
function, compiler prompts error. Solution for this is to declare the
function before it is used. Function declaration is also called function
prototype, since they provide a model or blueprint for the function.
Function declaration tells the compiler,” a function that looks like this is
coming up later in the program”, so it is like seeing reference of it before
the function itself.
93
www.EngineeringBooksPdf.com
PROGRAMMING IN C
To declare a function prototype simply state the data type the function
returns, the function name and in brackets list the type of parameters in
the order they appear in the function definition. Function prototype
contains the same information as the function header contains, but it
ends with semicolon. The only difference between the header and the
prototype is the semicolon (;). There must the semicolon at the end of
the prototype. It is a complete statement in itself.
Notice that function declaration does not contain the body of the function
and function declaration is terminated with a semicolon. So a prototype
shows what the inputs and output of the function is going to be, but
doesn't show how the function does it's work. It is basically a copy of the
function without anything inside the curly brackets. For example consider
the simple program with a function prototype
#include <stdio.h>
int sum (int, int); /* Function prototype*/
int main (void)
{
int total;
total = sum (2, 3); /* Function call*/
printf ("Total is %d\n", total);
return 0;
}
/* Function definition*/
int sum (int a, int b) /* Function header*/
{
return a + b; /* Function body*/
}
Advantage of function prototype:
C compiler checks there turn data tupes and types and counts of all
parameter lists. Try compiling the following:
#include <stdio.h>
int add (int,int); /* function prototype for add */
void main()
{
printf("%d\n",add(3));
}
int add(int i, int j)
{
return i+j;
}
94
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The function is called (or invoked) from main (). To invoke a function in
main, the function name is written, followed by parentheses. The syntax
of the function call is very similar to that of declaration, except that the
return data type is not used. A semicolon is placed at the end of the call
expression. The following facts occur when function is invoked.
#include <stdio.h>
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
Printf(“The result is%d “,z);
return 0;
}
Analysis:
1. Here function addition is defined before the main. Hence there is no
need of function prototype.
95
www.EngineeringBooksPdf.com
PROGRAMMING IN C
square (float X)
{
float y;
Y = x * x;
return (y);
}
main ( )
{
float a,b,
printf ("\n Enter any number:");
Result:
Analysis:
Square of 2.5 is not 6.000.Why the result is different? This is because the
function square(float x) by default, always returns an integer value. The
fractional part is truncated. In order to return the float type , float data
type must be mentioned at the function as shown in the below example.
main ( )
{
float square ( );
96
www.EngineeringBooksPdf.com
PROGRAMMING IN C
float a, b;
printf ("\n Enter any number ");
scanf ("%f" &a);
b = square (a);
printf ("\n square of entered number % f is % f, " a, b);
}
float square (float x)
{
float y;
y= x *x;
return ( y);
}
Result:
Enter any number:2.5
square of entered number 2.5 is 6. 2500000
main ( )
{
{
int Message1 ( );
}
}
int message1 ( )
{
statement 1;
statement2;
statement 3;
}
(iv) Any function can be called from any other function even main ( ) can
be called from other functions. for e.g.
97
www.EngineeringBooksPdf.com
PROGRAMMING IN C
main ( )
{
message ( );
}
int message ( )
{
printf (“ \n Hello”);
main ( );
return 0
}
message ( )
{
printf (“\n Hello”);
}
main ()
{
message ( );
message ( );
}
(vi) The order in which the functions are defined in a program and the
order in which they get called need not necessarily be same for e.g.
void message2 ( )
{
printf (“\n I am learning functions in C”);
}
void message1 ( )
{
printf ( “\n Hello “);
}
main ( );
{
message1 ( );
message2 ( );
}
98
www.EngineeringBooksPdf.com
PROGRAMMING IN C
main ( )
{
printf (“\nThis section is in main”);
void say( )
{
printf {“\nFunctions are easy.”);
}
}
main()
{
function1(a1,a2,a3……an)
}
function1(f1,f2,f3….fn);
{
functionbody;
}
here a1,a2,a3 are actual arguments and f1,f2,f3 are formal arguments.
99
www.EngineeringBooksPdf.com
PROGRAMMING IN C
int c;
c=a+b;
printf (“The sum is %d”,c);
return;
}
main()
{
int x,y;
Printf(“ Enter two integers“)
scanf(%d %d” ,&x, &y);
add (x, y); / *Actual parameters */
}
Analysis:
1) Consider the above program. The function definition begins with this
declaration:
This line informs the compiler that add() uses two arguments called a and
b, both a, b variables are of the type int. Both the a and b variables are
called formal arguments. Like variables defined inside the function, formal
arguments are local variables, private to the function. That means
programmer doesn’t have to worry about duplicating variable names used
in other functions. These variables will be assigned values each time the
function is called.
4) In the above program int a and int b values are assigned by actual
arguments in the function call. Consider the line in main program add
(x,y);
100
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The actual arguments are the x and y. These values are assigned to the
corresponding formal arguments in add() — for the variables x and y
respectively.
7) Both the arguments actual and formal should match in number, type
and order. The values of actual arguments are assigned to formal
arguments on a one to one basis starting with the first argument as
shown below. If not compiler will flag error. For example,
6) When a function call is made only a copy of the values actual arguments is passed to the
called function. What occurs inside the functions will have no effect on the variables used in
the actual argument list.
According the arguments and the returning value, functions are divided
into three categories.
101
www.EngineeringBooksPdf.com
PROGRAMMING IN C
If a called function does not have any arguments, it is not able to get any
value from the calling function. Also if it does not return any value, the
called function is not receiving any value from the function when it is
called. That is , there is no data transfer between the calling function and
the called function. This can be represented as given below.
Function 1 Function 2
f2()
f1(x) No input
Calling ………………
the ………………
Returning from
function f2( )
……………… the function
……………… No output
Example :
main( )
{
message ( );
}
void message( )
{
printf(“\n WELCOME”);
}
Analysis:
main ( ) is the calling function and message ( ) is the called function.
Between the functions, no data is transferred.
A function which does not get value from the calling function but it can
return a value to calling program. This can be represented as given
below.
Function 1 Function 2
f1(x) f2()
No input
Calling ………………
………………
the
function f2( ) Returning from
……………… 102
the function
………………
www.EngineeringBooksPdf.com
PROGRAMMING IN C
A value
Example :
main( )
{
int a;
a=todaytemp( );
printf(“\n The returned value form the todaytemp( )
function is %d”,a);
}
todaytemp( )
{
return(100);
}
Analysis:
Here the called function does not receive any parameters from main ie
called function but returns a value to called program.
That is, data is transferred from calling function to the called function but
no data is transferred from the called function to the calling function. A
function that does not return any value cannot be used in an expression it
can be used only as independent statement. This is represented as given
below.
Function 1 Function 2
f1(x) f2()
sending
………………
Calling
the ………………
Returning from
function f2( )
……………… the function
……………… No output
Example :
103
www.EngineeringBooksPdf.com
PROGRAMMING IN C
#include
main()
{
int a,b;
printf(“Enter the two numbers”);
scanf(“%d%d”,&a,&b);
largest(a,b)
}
/*Function to find the largest of two numbers*/
largest(int a, int b)
{
if(a>b)
printf(“Largest element=%d”,a);
else
printf(“Largest element=%d”,b);
}
Analysis:
In the above program the calling function reads the data and passes it on
to the called function. But called function does not return any value.
fun (a,b)
int a,b;
{
int y,z;
y=a+b;
z=a-b;
return y;
return z; /* Two return statements for one single
function called is invalid * /
}
104
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Function 1 Function 2
f1(x) f2()
Sending Data
………………
Calling
the ………………
function f2( ) Returning from
……………… the function
……………… Receiving Data
Example :
#include<stdio.h>
float findaverage(float a, float b); /*Function prototype*/
main()
{
float a=5,b=15,result;
result=findaverage(a,b);
printf("average=%f \ n",result); /*Function prototype*/
}
float findaverage(float a, float b)
{
float average;
average=(a+b)/2;
return(average);
}
1.6 Questions
1) What is a function?
2) Explain the structure of a function.
3) What is the difference between function declaration and function
definition?
4) Explain function invocation with explain with an example.
5) Explain the function types with examples.
105
www.EngineeringBooksPdf.com
PROGRAMMING IN C
MODULE 3
106
www.EngineeringBooksPdf.com
PROGRAMMING IN C
A local variable exists inside the specific function that creates them. They
are unknown to other functions. Local variables cease to exist once the
function that created them is completed. They are recreated each time a
function is executed or called. Local variables must always be defined at
the top of a block i.e at the starting of the brace ({). When a local
variable is defined - it is not initialized by the system and must be
initialized. For example consider the below program,
main()
{
int x;
float y;
…….
tree();
}
void tree()
{
int x;
float y;
…….
}
Here each x and y variables are LOCAL to its own routine and are called
local variables. The x and y variables in main () is unrelated to the x and
y variables in the tree function. (Local variables are also called
“automatic''.)
.
2.2 Global Variables
int max;
main()
{
Printf(“ The value of global variable max is: %d“,max);
max=max+1;
}
f1()
{
107
www.EngineeringBooksPdf.com
PROGRAMMING IN C
max++;
Printf(“ The value of global variable max in the fuction is:
%d“,max);
…..
}
Output:
The value of global variable max is: 0
The value of global variable max in the function is: 2
Analysis:
Here int max is global variable. The int max can be used in both main and
function f1 and any changes made to it will remain consistent for both
functions. When the global variable is declared its value is initialized to
zero by the system. this is seen by the first output. the value of variable
is incremented by one in the main() function. In the function f1, max is
called. Even after exiting the main() the value of max variable is retained
ie 1 and it is incremented by one in the functionf1. The value of variable
is two. This is seen in the second output.
To understand the difference between local and global variable consider
the below example.
Analysis:
The variable i in main is global and will be incremented to 5.The variable
i in func is internal and will be incremented to 11. When control returns to
main the internal variable will die and any reference to i will be to the
global.
108
www.EngineeringBooksPdf.com
PROGRAMMING IN C
In this call by value method the value of each of the actual arguments in
the calling function is copied into corresponding formal arguments of the
called function. With this method the changes made to the formal
arguments in the called function have no effect on the values of actual
argument in the calling function. The following program illustrates this:
main ( )
{
I nt a = 10, b=20;
swap (a,b);
printf ("\na = % d, b = % d", a,b);
}
swap (int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf ( "\n x = % d, y = % d" , x, y);
}
output :
x = 20, y = 10
a =10, b =20
Analysis:
In the above program the initial values of variables are a=10 and
b=20.These variables are passed as arguments to called function swap().
Function swap() has formal arguments x and y equivalent of a and b
variables and this function swaps the variables which is seen in the
second line of output. After swapping the control returns to main(), but
the values of variables are unaltered in the main() and this is seen in first
109
www.EngineeringBooksPdf.com
PROGRAMMING IN C
line of output. This is because when the arguments are passed their copy
is only sent not the original arguments.
2.4 Recursion
5! = 5 x 4 x 3 x 2 x 1 = 120
To understand the recursive functions consider the program given below.
#include <stdio.h>
#include <conio.h>
unsigned long fact(int);
void main()
{
unsigned long f;
int n;
clrscr();
printf("\nENTER A NUMBER: ");
scanf("%d",&n);
f=fact(n);
printf("\nFACTORIAL OF %d IS %ld",n,f);
getch();
}
unsigned long fact(int a)
{
110
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Output:
ENTER A NUMBER:0
FACTORIAL OF 0 IS 1
ENTER A NUMBER:3
FACTORIAL OF 3 IS 6
Analysis:
The factorial function includes a call to itself make this function recursive.
When the function is called to calculate the factorial of 3, the value of the
formal parameter a is set to 3. Because this value is not zero, the
following program statement
fac=a*fact(a-1);
is executed, which, given the value of a, is evaluated as
fac=3 * fact(2);
111
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Apart from data type variables have storage class. In C , there are four
types of storage classes. They are
Automatic variables are declared inside a particular function and they are
created when the function is called and destroyed when the function exits.
Automatic variables are local or private to a function in which they are
defined. Other names of automatic variable are internal variable and local
variable. A variable which is declared inside the function without using
any storage class is assumed as the automatic variable because the
default storage class is automatic.
Storage: Memory.
Default initial Value: Garbage.
Scope: Local (to block in which variable defined)
Lifetime: Till control remains within block where it is defined.
Syntax:
auto<variable>
Here auto is the keyword for automatic variable.
For example consider the below program.
main()
{
auto int x, y;
int a,b;
x = 10;
printf(“Values : %d %d”, x, y);
}
Analysis:
Here x and y are defined as automatic variables by the usage of keyword
auto. Variables a and b are also considered as auto because any variable
which does not have any storage class explicitly specified , it is considered
as automatic storage class only.
112
www.EngineeringBooksPdf.com
PROGRAMMING IN C
External variable:
External variable is a global variable which is declared outside the
function. The memory cell is created at the time of declaration statement
is executed and is not destroyed when the flow comes out of the function
to go to some other function. .The global variables can be accessed by
any function in the same program. A global variable can be declared
externally in the global variable declaration section.
Specifications:
Storage: Memory.
Default initial Value: Zero
Scope: Global
Lifetime: As long as the program execution doesn’t come to an end.
Syntax:
There is no keyword to state any variable as global. if any variable is
declared outside the function without any other storage class , it is
implicitly considered as global variable.
int x = 100;
main ( )
{
…..
x = 200;
f1 ( );
f2 ( ); …
…..
}
f1 ( )
{
x = x + 1;
….
…..
}
f2 ( )
{
x = x + 100;
….
…..
Printf(“ The final value of global variable x is %d“,x );
}
Output;
113
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Analysis:
These variables are alive throughout the program. A static variable can be
initialized only once at the time of declaration. The initialization part is
executed only once and retains the value till the end of the program.
Storage: Memory.
Default initial Value: Zero.
Scope: Local (to block in which variable defined)
Lifetime: Value of the variable remains as it is between function calls.
Syntax:
A variable can be declared as static by using the keyword “static”. For
example
staic int x ; For example consider the program,
main()
{
int j;
for(j=1; j<=3; j++)
stat();
}
stat();
{
static int x=0;
x=x+1;
printf(“The Value of X is %d\n”,x);
}
Output:
The Value of X is 1
The Value of X is 2
The Value of X is 3.
Analysis:
114
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Syntax;
register int x;
Specifications:
Output:
Enter two numbers: 2.4
The sum is 6
Analysis:
In the above program, all the variables are stored in the registers instead
of memory.
115
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Programs:
#include <stdio.h>
int calc_result( int var1, int var2, int var3 )
{
int sum;
sum = var1 + var2 + var3;
return( sum ); /* return( var1 + var2 + var3 ); */
}
main()
{
int numb1 = 2, numb2 = 3, numb3=4, answer=0;
answer = calc_result( numb1, numb2, numb3 );
printf("%d + %d + %d = %d\n", numb1, numb2, numb3,
answer);
}
#include <stdio.h>
#include <conio.h>
int reverse(unsigned long);
void main()
{
unsigned long num;
clrscr();
printf("\nENTER A NUMBER: ");
scanf("%lu",&num);
printf("\nREVERSE OF %lu IS ",num);
reverse(num);
getch();
}
int reverse(unsigned long n)
{
int dig;
if(n==0)
return 1;
else
{
dig=n%10;
n=n/10;
printf("%d",dig);
116
www.EngineeringBooksPdf.com
PROGRAMMING IN C
reverse(n);
}
}
#include <stdio.h>
#include <conio.h>
unsigned long fib(int);
void main()
{
int n,i;
unsigned long f;
clrscr();
printf("\nENTER A NUMBER: ");
scanf("%d",&n);
printf("\nTHE FIBONNACI SERIES UPTO %d NUMBERS
IS:\n",n);
for(i=0;i<n;i++)
{
f=fib(i);
printf("%lu ",f);
}
getch();
}
unsigned long fib(int x)
{
unsigned long res;
if(x==0)
return(0);
else
if(x==1)
return(1);
else
{
res=fib(x-1)+fib(x-2);
return(res);
}
}
117
www.EngineeringBooksPdf.com
PROGRAMMING IN C
char char;
int num;
printf("enter a character:");
scanf(“%c”, &char);
printf("enter a number of times to repeat it:");
scanf(“%d”, &num);
repchar (char,num);
return 0;
}
/*repchar () function definition*/
void repchar(char ch, int n)
{
for(int j=0,j<n;j++)
Printf(“%c”,ch);
Printf(“/n”);
}
2.6 Questions
#include<stdio.h>
void large( )
{
int a,b;
printf(“Enter values of a and b :”);
scanf(“%d %d”,&a,&b);
if(a<b)
printf(“large : %d”,b);
else
printf(large : %d”,a);
}
118
www.EngineeringBooksPdf.com
PROGRAMMING IN C
main( )
{
large( );
large( );
}
*******
MODULE 4
UNIT 1: Arrays
1.1 Introduction
are defined and each of which can store a single whole number. If date of
birth is 1-2-2009, this can be stored in the variables as, day = 1; month
= 2; year = 2009; similarly, to store five different numbers, five variables
would have to be declared such as,
With five numbers this is fairly easy. But what if a hundred items has to
be stored? Can hundred variables be declared? If yes, program would
become rather large and repetitive and cumbersome. As a solution for
such problems programming language C has given the concept of an
array. In array a variable is allowed to store more than one item. All of
the items in a single array variable must be the same type - e.g. an
integer or a float or a char.
119
www.EngineeringBooksPdf.com
PROGRAMMING IN C
array or one dimensional or linear array. More than one column are called
multidimensional array.
Like any other variable arrays must be declared explicitly before they are
used. The general form of declaration is:
data-type Array-Name[Array-Size];
Here data-type is the type specifier that indicates what data type the
declared array is such as int, float double or char. Array-Name is the
name of the declared array and rules of declaring the variable applies to
array name. Array-Size defines how many elements the array contains.
This is always an integer. Note that the brackets ([ and ])are required in
declaring an array. The bracket pair ([ and ]) is also called the array
subscript operator.
int array_int[8];
where int specifies the data type of the array whose name is array_int.
The size of the array is 8, which means that the array can store eight
elements (that is, integers in this case).
The other examples are
120
www.EngineeringBooksPdf.com
PROGRAMMING IN C
For ex, consider the array declaration int num[6];This array consists of
five elements and index of first element is 0 , second is one and so on.
This described in the below figure.
int num[6];
num [1]
num [2]
num [3]
num [4]
num [5]
1. Static array
2. Dynamic array
.
Declaration for static array specifies the array size, which cannot be
altered afterwards. But for dynamic arrays the size can be altered. Using
dynamic memory the dynamic array’s size can be modified. This is
discussed pointers in chapters.
1. Compile time
2. Run time
This initialization is done while writing the program itself. Following is the
syntax of initialization of the array.
121
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Here, the array variables are initialized with the values given in front of it.
That is, the 0th element of array will contain 5, 1st will contain 7 and so on.
Remember, the array indexing or subscripting is always done from 0th
position. The values of the array will be get stored in following manner
var[0] 5
7
var[1]
9
var[2]
3
var[3]
4
var[4]
Each element in the array will be referred individually by its index such
as, var[0], var[1], var[2], . . .
In the array declaration, the size can also be omitted. In such cases the
compiler will automatically identify the total number of elements and size
will be given to it. For example:
This array is not declared with size, but initialized with values. Here, size
of the array will be automatically set to 8. Now it can be referred as the
general array. Compile time initialization can also be done partially. Such
as
Here, array ‘x’ is having size 5, but only 0th, 1st, and 2nd elements are
declared with values. The remaining 3rd and 4th element of the array will
be
automatically set to 0. This property is applicable to all numerical type of
the
array in C. However, if we have more values than the declared
size, the compiler will give an error. For example –
122
www.EngineeringBooksPdf.com
PROGRAMMING IN C
int n[10];
In this all 10 elements contains junk values. The individual array element
can be assigned to a variable with a statement such as
int G;
G = grade [50];
The statement assigns the value stored in the 50th index of the array to
the variable g. A value can be stored into an element in the array simply
by specifying the array element on the left hand side of the equals sign.
This is as shown in the statement,
grades [100]=95;
The value 95 is stored into the element number 100 of the grades array.
An array can initialized at run time by the program or by taking the input
from the keyboard. Generally, the large arrays are declared at run time in
the program itself. Such as –
int sum[20];
for (i = 0;i<20;i++)
sum[i] = 1;
Here, all the elements of the array ‘sum’ are initialized with the value one.
The loop control structures are applicable in these cases. The scanf
function can also be used to input the values from the user. In such
cases, the loop control structure is applicable. For example:
int sum[10], x;
printf(“Enter 10 numbers: ”);
for(x=0;x<10;x++)
scanf(“%d”, &sum[x]);
Here, the array ‘sum’ is initialized by taking the values as input from
123
www.EngineeringBooksPdf.com
PROGRAMMING IN C
the keyboard.
/* Initializing an array */
#include <stdio.h>
main()
{
int i;
int list[10];
for (i=0; i<10; i++)
{
list[i] = i + 1;
printf( "list[%d] is initialized with %d.\n", i, list[i]);
}
}
Output:
124
www.EngineeringBooksPdf.com
PROGRAMMING IN C
ANALYSIS
1) Write a program to read 10 data from users and to find sum of them
using array.
/* Input 10 numbers from user and find the total of all of them */
#include<stdio.h>
main( )
{
int val[10], i, total=0;
printf(“Enter any ten numbers: ”);
for(i=0;i<10;i++)
scanf(“%d”, &val[i]); // input numbers
for(i=0;i<10;i++)
total = total + val[i]; // find total
printf(“\nTotal is: %d”, total);
}
Sample Output:
Enter any ten numbers: 1 2 3 4 5 6 7 8 9 10
Total is: 55
data-type Array-Name[Array-Size];
sizeof(data-type) * Array-Size
125
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Here sizeof is a library function, data-type is the data type of the array.
Array-Size specifies the total number of elements the array can take. The
result returned by the expression is the total number of bytes the array
takes.Another way to calculate the total bytes of an array is simpler; it
uses the following expression:
sizeof(Array-Name)
Here Array-Name is the name of the array. Consider the below program
to know how to calculate the memory space taken by an array.
#include <stdio.h>
main()
{
int total_byte;
int list_int[10];
total_byte = sizeof (int) * 10;
printf( "The size of int is %d-byte long.\n", sizeof (int));
printf( "The array of 10 ints has total %d bytes.\n",
total_byte);
}
OUTPUT
So far, all the arrays dealt with have been one-dimensional arrays, in
which the dimension sizes are placed within a pair of brackets ([ and ]).In
addition to one-dimensional arrays, the C language also supports
multidimensional arrays. Arrays can be declared with as many dimensions
as compiler allows. The general form of declaring a N-dimensional array is
126
www.EngineeringBooksPdf.com
PROGRAMMING IN C
datatype arrayname[rows][columns];
int x[2][3];
Array type: int
Array name: x
Array indices: i,j
Standard identification: x[i][j]
Number of entries: n x m
Where n is row size and m is column size and x[i][j] indicates any
particular element.
Arrays can be declared with the other variables in the program, such as
//declaration
int data [3][4] = {
{8, 2, 6, 5}, //row 0
{6, 3, 1 ,0}, //row 1
{8, 7, 9, 6} //row 2
};
127
www.EngineeringBooksPdf.com
PROGRAMMING IN C
In the above case elements of the first row are initialized to 1,2,3 &
second row elements are initialized to 4,5,6.
The initialization can be done row wise also, for the above example it is
If the initialization has some missing values then they are automatically
initialized to 0.
For example
In this case the first two elements of the first row are initialized to 3, 4
while the first element of the second row is initialized to 5 & rest all
elements are initialized to 0.
User can store the values in each of these memory locations by referring
their respective row and column number as,
table[2][3] = 10;
table[1][1] = -52;
Can this be done for two dimensional arrays also? For example consider a
multidimensional array sap declared as given below.
This is illegal because the array sap could be of 2 rows and 3 columns,
or of 3 rows and 2 columns. To avoid this ambiguity, the column size
(second subscript) must be specified explicitly in the declaration. For
example,
128
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Arrays are usually processed using a for statement. To process all the
items in a two-dimensional array, a nested for statement (that is, one for
inside another for) has to be used. The first for loop will process the row
indexes of the array, and the inside for loop will process the column
indexes of the array. The length of a two dimensional array is the
number of rows it has.
1) Data can be entered into two dimensional arrays in the following ways.
Number of rows is the conditional expression in the outer for loop and
number of columns is the conditional expression in the inner for loop.
int arr[5][5];
int z = 0, x, y ;
for(x=0;x<5;x++)
{
for(y=0;y<5;y++)
{
arr[x][y] = z;
z++;
}
}
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
2) int n,m;
double x[5][6];
Printf(“Enter the elements for the array matrix “); Outer for lo
129
www.EngineeringBooksPdf.com
PROGRAMMING IN C
To output the Array’s Data the same concept of two for loops are used.
Number of rows is the conditional expression in the outer for loop and
number of columns is the conditional expression in the inner for loop.
Instead of scanf, printf statement is used inside the inner for loop. This is
shown in the example below.
int n,m;
double x[5][6];
for (n = 0; n < 5; ++n
{
for (m = 0; m < 6; ++m)
printf ( "%10.2f", &x[n][m]);
Prinftf(“/n “)
}
#include <stdio.h>
#include <conio.h>
void main()
{
int a[2][3],i,j;
clrscr();
printf("\nENTER VALUES FOR THE MATRIX:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nTHE VALUES OF THE MATRIX ARE:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%5d",a[i][j]);
printf("\n");
}
Result:
130
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Input:
ENTER VALUES FOR THE MATRIX: 1 2 3 4 5 6
Output:
THE VALUES OF THE MATRIX ARE:
123
456
#include<stdio.h>
main()
{
int x[][] = { {8,5,6},
{1,2,1},
{0,8,7}
};
int y[][] = { {4,3,2},
{3,6,4},
{0,0,0}
};
int i,j;
printf("First matrix: ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(“%d”, x[i][j]);
printf("\n");
}
printf("Second matrix: ");
for(i=0;i<3;i++)
{
for(int j=0;j<3;j++)
printf(“%d”, y[i][j]);
printf("\n");
}
printf("Addition: ");
for(i=0;i<3;i++)
{
for(int j=0;j<3;j++)
printf(“%d”, x[i][j]+y[i][j]);
printf("\n");
}
}
}
Result:
131
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Input:
First matrix:
856
121
087
Second matrix:
432
364
000
Output:
Addition:
12 8 8
4 8 5
0 8 7
1) Function must be called by using only the name of array. It need not
include size of array(i.e square brakets[]) or any arguments. For
example,
int list[] = {0, 4, 5, -8, 17, 301};/*This defines the array list */
Let biggest be the called function. To pass the array list and an integer
variable to the called function, it can be written as
biggest(list, n)
2) The function header must have the data type of the array. Size of
array need not be specified. However empty square brackets must be
used, to specify the parameter as an array. Function definition can
have formal parameters.
For example:
The function header for the called function biggest can be written as
132
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The function biggest is defined to have two arguments one array name
and other an integer value. Here int array[] is a formal parameter
which is same as actual parameter int list[].Int size is also a formal
parameter.
#include <stdio.h>
int retrieve_element(int index, int array1[]);
main()
{
int value;
int a[] = {0, 4, 12, 17, 34};
value= retrieve_element(3, a);
Output:
The value of array element is 12
Analysis:
(i)Consider the function prototype.
int retrieve_element(int index, int array1[]);
133
www.EngineeringBooksPdf.com
PROGRAMMING IN C
(ii)Function main declares integer array int a[] and integer variables
index and value. It calls the function retrieve-element by passing two
actual parameters ,first parameter an integer value 3 and second is an
array a. The returned result is stored in variable value.
(iii) Function header in the called function has two formal arguments, int
index and int array1[] which are same as actual arguments in function 3
and a respectively. In other words this can be described as below.
main()
{
int value;
int a[] = {0, 4, 12, 17, 34};
return array1[index];
Here the index is 3. This statement is equivalent to return array1[3]; This
will return the value of the element in the array at the position indicated
by the value of index which is twelve in this case.
2)/*This program reads and prints an array elements by passing the array
as parameter to function*/
#include<stdio.h>
void read(int take[],int in);
void dis(int give[],int out);
void main()
{
int a[5];
134
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Input:
Enter five elements of first list: 1 2 3 4 5
Output:
The elements of first list are
1
2
3
4
5
1.10 Questions
135
www.EngineeringBooksPdf.com
PROGRAMMING IN C
*****
Module 4
UNIT 2: Strings
2.1 Introduction
char string_name[size];
Here char is character data type. This is must for specifying the data type
as string. string_name is the valid variable name given to the string and
‘size’ determines the number of characters in the string. For example:
char star[10];
char book[13];
char phone[ ];
Analysis:
Here ‘star’ is the character array or a string that can store up to 10
elements of type char. It can be represented as:
136
www.EngineeringBooksPdf.com
PROGRAMMING IN C
char star[10];
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]
char phone[ ];
Here phone array does not have size specified. This initializes an upsized
character array, phone, with a string constant. Later when the compiler
sees the statement, it will figure out the total memory space needed to
hold the string constant plus an extra null character added by the
compiler itself and allocates the memory space.
2.3.1 Type 1
M R J O H N
Here null (\0) is appended by the compiler at the end string to denote
that it is end of given string. The compiler can automatically append a null
character (\0) to the end of the array and treat the character array as a
character string. Note that the size of the array is specified to hold up to
nine elements, although the string constant has only eight characters
enclosed in double quotes. The extra space is reserved for the null
character that the compiler will add later.
137
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Here the array str1 has size 4. This it cannot hold a string constant plus
an extra null character and above declaration is considered illegal.
Note that many C compilers will not issue a warning or an error message
on this incorrect declaration. The runtime errors that could eventually
arise as a result could be very difficult to debug.
2.3.2 Type 2
You can also initialize the above a character array stream can be
initialized with a string constant “Hello! “. For example,
The compiler can automatically append a null character (\0) to the end of
the array, and treat the character array as a character string.
2.3.3 Type 3
The third type of initialization is not specifying the array size. For
example,
138
www.EngineeringBooksPdf.com
PROGRAMMING IN C
char ch = `x';
char str[] = "x";
One byte is reserved for the character variable ch, and two bytes are
allocated for the character array str. The reason that an extra byte is
needed for str is that the compiler has to append a null character to the
array.
This is also called as run time initialization. The integers, character and
float data types are read by using functions such as scanf(), gets,etc.
Similarly to read a string two functions are used. They are
1. scanf()
2. gets()
To read strings using scanf() format specifier %s is used with the function
scanf().For example
char name[10];
To input data in
to char array ’name’, scanf function and %s is used as given below.
scanf("%s",name);
Note that the %s format specifier doesn’t require the ampersand (&)
symbol before the variable name. The major limitation of scanf() is that it
reads until occurrence of first separator a white space characters such as
space character, tab or new line and store it into given variable. For
example if the input literal is “How are you?”. Then the scanf statement
will read only the word ‘How’ into the variable name.
139
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The gets() functions reads the string from the keyboard including spaces
until the enter key is not pressed. The getchar() function is used to get a
single charater. The gets() and getchar() functions are defined in stdio.h
library file. For example
char line[100];
printf("Enter a line:\n");
gets(line);
puts("Entered input is :\n");
puts(line);
The gets() function keeps reading characters from the standard input
stream until a new line character or end-of-file is encountered. Instead of
saving the new line character, the gets() function appends a null
character to the array that is referenced by the argument to the gets()
function.
To out put data of the given string two functions are used. They are
1) printf()
2) puts ()
printf(“%s”, name);
printf knows how much to print out because of the NULL character at the
end of all strings. When printf() encounters a null\0, it stops printing. The
string variable can be printed out with precision using printf() statement.
For example
printf("%7.3s",name)
140
www.EngineeringBooksPdf.com
PROGRAMMING IN C
This specifies that only the first 3 characters have to be printed in a total
field width of 7 characters & right justified in the allocated width by
default. We can include a minus sign to make it left justified (%-7.3). For
example consider the following program.
The puts function is a much simpler output function than printf for string
printing. Prototype of puts is defined in stdio.h For example:
#include <stdio.h>
main()
{
char str[80] ; Char str2[45];
printf("Enter a string: ") ;
gets(str1) ;
printf("Enter another string: ") ;
scanf(“%s“,str2); /*Reads upto first white space character*/
Printf(“output of first string:\n”);
printf("%s" , str1\n);
Printf(“output of second string:\n”);
puts(“str2 “)
}
Result:
Input:
Enter a string: This is c language.
Enter another string: This is strings
141
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Output:
Output of first string: This is c language
Output of second string: This
strcpy(string1,string2);
strcpy(Name,”Java”);
142
www.EngineeringBooksPdf.com
PROGRAMMING IN C
strcpy(city1, city2);
This will assign the contents of the string variable city2 to the string
variable city1.The size of the array city1 should be large enough to
receive the contents of city2, if not compiler will lodge an error.
strcat() function:
The process of appending the characters of one string to the end of other
string. Is called concatenation.The strcat() function joins two strings
together. Sstrcat(string1,string2)
Here string1 & string2 are character arrays. When the function strcat is
executed string2 is appended to string1.The string at string2 remains
unchanged.
Example
strcpy(string1,”Web”);
strcpy(string2,”Mining”);
Printf(“%s”, strcat(string1,string2);
strncat(stri,name,4);
strlen() function:
This function counts and returns the number of characters in a string. The
length does not include a null character. The syntax is n=strlen(string);
Where n is integer variable, which receives the value of length of the
string.
Example:
int len;
len=strlen(“Coral Draw”);
Here the integer variable len will store the value 10 which is the length of
given sting.
strcmp() function
In c the values of two strings cannot be directly compare in a condition
like if(string1==string2). The strcmp() function is used for this purpose.
This function returns a zerovalue if two strings are equal, or a non zero
143
www.EngineeringBooksPdf.com
PROGRAMMING IN C
number if the strings are not the same. This returns a negative if the
string1 is alphabetically less than the second and a positive number if the
string is greater than the second.
Strcmp(string1,string2)
String1 & string2 may be string variables or string constants.
Example:
strcmp(“Book”,”Book”) will return zero because 2 strings are equal.
strcmp(“their”,”there”) will return a 9 which is the numeric difference
between ASCII ‘i’ and ASCII ’r’.
strcmp(“The”, “the”) will return 32 which is the numeric difference
between ASCII “T” & ASCII “t”.
strcmpi() function
This function is same as strcmp() which compares 2 strings but not case
sensitive. For example
strlwr () function:
This function converts all characters in a string from uppercase to
lowercase. The syntax is
strlwr(string);
For example:
strlwr(“APPLICATION”) converts the string to application
strupr() function:
This function converts all characters in a string from lower case to
uppercase. The syntax is
strupr(string);
For example strupr(“application”) will convert the string to APPLICATION.
Apart from string functions C has character functions. These functions are
defined in ctype.h library file. Some of the character functions are given
below.
144
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Programs
1. Write a program to find out the length of a given string without using
the library function strlen().
#include <stdio.h>
void main()
{
char str[50];
char nul={‘\0’}
int len;
printf("\nENTER A STRING: ");
gets(str);
for(len=0; str[len]!=nul; len++);
Result:
Input:
ENTER A STRING: This is string in C
Output:
THE LENGTH OF THE STRING IS 19.
145
www.EngineeringBooksPdf.com
PROGRAMMING IN C
2) Write a program to find out the length of a given string using the
library function strlen().
/*The "strlen()" function gives the length of a string, not including the
NULL character at the end.*/
#include <stdio.h>
#include <string.h>
void main()
{
char name[30] = "This is string in C";
int len;
len= strlen( name );
printf( "Length of string <%s> is %d.\n", name ,len);
}
Output:
Length of string < This is string in C > is19.
#include <stdio.h>
#include <string.h>
void main()
{
char ch[100];
int i,len;
printf("\n Enter a string: ");
gets(ch);
len= strlen(ch);
printf("\n The string in the reverse order: ");
for(i=len-1; i>=0; i--)
printf("%c", ch[i]);
getch();
}
Result:
Input
Enter a string: strings are interesting.
Output
The string in the reverse order: .gnitseretni era sgnirts
#include <stdio.h>
#include <string.h>
#include <string.h>
146
www.EngineeringBooksPdf.com
PROGRAMMING IN C
void main()
{
char a[100];
int i,len, flag=0;
printf("\n Enter a string: ");
gets(a);
len=strlen(a);
for(i=0;i<len; i++)
{
if(a[i]==a[len-i-1])
flag=flag+1;
}
if(flag==len)
printf("\n The string is palindrom");
else
printf("\n The string is not palindrom");
}
RESULT:
Input
Enter a string: madam
Output
The string is palindrome
#include <stdio.h>
#include <string.h>
void main()
{
char a[100];
int leni, vow=0;
printf("\n ENTER A STRING: ");
gets(a);
len=strlen(a);
for(i=0;i<len; i++)
{
if(a[i]=='a' || a[i]=='A' || a[i]=='e' || a[i]=='E' || a[i]=='i' ||
a[i]=='I' || a[i]=='o' || a[i]=='O' || a[i]=='u' || a[i]=='U')
vow=vow+1;
}
printf("\n There are %d vowels in the string", vow);
}
RESULT:
147
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Input
Enter a string: Evening
Output
There are 3 vowels in the string
#include <stdio.h>
#include <string.h>
void main()
{
char a[100];
int len, word, i =0;
printf("\n Enter a string: ");
gets(a);
len=strlen(a);
for(i=0;i<len; i++)
{
if( a[i] !=' ' && a[i+1]==' ')
word=word+1;
}
printf("\n There are %d words in the string", word);
}
RESULT:
Input
Enter a string: Strings are very interesting.
Output
There are 4 words in the string
2.10 Questions
1) What is a string? How strings are different from character strings. Give
different types of initialization of the strings.
2)Explain different functions used to write and read the strings.
3) Explian any five string handling functions.
4) Differentiate between scanf() and gets() pertaining to reading the
strings.
148
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Module 5
Unit 1 : POINTERS
1.1 Introduction
Arrays
Structures
Functions
char name;
int number;
float height;
149
www.EngineeringBooksPdf.com
PROGRAMMING IN C
When the variables are initialized, the value of the variable gets stored in
that respective memory location.
1.3 What is a Pointer?
For integer variable quantity let the address of the variable be 5078.This
can be diagrammatically presented as given below.
Number variable
5 Value
5078 Address
(i) Comments/*…*/
(ii) Arithmetic operator for multiplication as in a*b
(iii) Declaring pointer variable using *(dereference operator)
150
www.EngineeringBooksPdf.com
PROGRAMMING IN C
data-type *variable-name;
Here data type can be int, float, char etc and the dereference operator
before the int variable variable-name tells that it is a pointer variable.
Hence the pointer variable variable-name holds the address of another
variable of the same data type. For example,
int x; /* define x */
int *ptr; /* define a pointer to x */
int *p; p is a pointer to an integer.
similarly pointer to char and float can be declared
char *q; q is a pointer to a char.
float *fp; fp is a pointer to float.
*ptr = 7;
This will copy 7 to the address pointed to by ptr. Thus if ptr "points to"
(contains the address of) x, the above statement will set the value of x to
7. That is, when the '*' is used this way, it is referring to the value of that
which ptr is pointing to, not the value of the pointer itself.
151
www.EngineeringBooksPdf.com
PROGRAMMING IN C
int i, j,*p;
This causes p pointer variable to point at i the integer data type. Here
All the variables that are declared in programs are allocated addresses in
the memory. This address can be printed out using the & operator.( which
has already been used in scanf(). For example, consider the below
program.
#include <stdio.h>
main()
{
int x;
x=1000;
printf(“ Value of x=%d\n”,x);
printf(“Address of variable x = %d\n”, &x);
}
OUTPUT:
Value of x = 1000
Address of variable x = 278614
Analysis:
In this case, the value will be stored in 4 locations, not one, since integer
requires 4 bytes to store. However 1000 is ‘sliced’ into 4 pieces,. Here,
what is the address of x? Actually it is 278614, 278615, 278616 and
152
www.EngineeringBooksPdf.com
PROGRAMMING IN C
(ii) int x;
int*ptr;
ptr=&x; /*Address of x is assigned to pointer variable*/
*ptr=&x;/*The value of x is assigned to ptr */
int x=0;
X=5;
Pointers has the following two important aspects. They are given below.
#include <stdio.h>
int main()
{
int x = 12;
int *ptr;
ptr = &x;
153
www.EngineeringBooksPdf.com
PROGRAMMING IN C
return 0;
}
OUTPUT:
Address of x: 0x0065FBFA
Address of x: 0x65fbfa
Address of ptr: 0x65fbfa
Value of x: 12
Note: Format specifiers %x,%X and %p are used to get the address of
the variable in c. ox in the address refers that the format of address is in
hexadecimal format.
#include <stdio.h>
int main()
{
int *ptr, q;
OUTPUT
value of q=19
Contents of ptr=19
address of q stored in ptr=782AB2
#include <stdio.h>
void main()
154
www.EngineeringBooksPdf.com
PROGRAMMING IN C
{
char x, y;
char *p;
x=’t’;
p=&x;
y=*p;
printf("value of x=%c\n", x);
printf("Pointer value in y=%d\n", y);
printf("Pointer value in *p=%d\n", *p);
Output
Value of x=t
Pointer value in y=t
Pointer value in *p=t
#include<stdio.h>
main()
{
int x;
int *ptr1,*ptr2;
x=5;
ptr1=&x;
ptr2=ptr1;
Value of x=5
Contents of ptr1=5
Contents of ptr2=5
int x,y;
int *ptr1,*ptr2;
1)ptr1=&x;
155
www.EngineeringBooksPdf.com
PROGRAMMING IN C
2) y=*ptr1
pointer variable ptr1 is holding the address. The content of that address
is assigned to the variable y, not the memory address.
3) ptr1=&x;
ptr2=ptr1;
Ptr1 holds the address of the variable due to first declaration. In the
second declaration content of ptr1 ie the address of x is transferred to
ptr2.Hence both ptr1, ptr2 both will be holding the same address.
(i) int x;
int ptr1;
ptr1=&x;
Error: pointer declaration must have the prefix of dereference (*)
operator.
(ii) float p;
float*var
var=y;
Error: While assigning variable to the pointer variable the address
operator (&) must be used along with the variable.
(iii) int x;
char *name;
name=&x;
error: Mixing of data type is not allowed.
addition +
subtraction
Pointer increment
Pointer decrement
Integer, float, char, double data type pointers can be incremented and
decremented. For all these data types both prefix and post fix increment
156
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Let int*p;
P++ /*valid*/
++p /*valid*/
p-- /*valid*/
--p /*valid*/
#include <stdio.h>
main()
{
int *p1,p;
float *f1,f;
char *c1,c;
p1=&p;
f1=&f;
c1=&c;
Output:
2) #include <stdio.h>
main( )
{
157
www.EngineeringBooksPdf.com
PROGRAMMING IN C
int x;
int *p;
x=1000;
p=&x;
printf(“Pointer value = %d\n”,p);
printf(“Pointer plus one =%d\n”,p+1);
}
Analysis:
223455+1=223439! That is pointer magic! How does C justify that? Well,
223455 is not just a number, C knows it is the address of an integer that
takes 4 locations. So 223455,223456, 223457 and 223458 are all
together held by the integer. So C interprets +1 as next free location and
gives the answer 223459.Remember that it need not be continuation of
memory location, when a pointer is incremented.
int*p1,*p2;
p1=p1+p2; /* invalid */
p1=p1-p2; /* invalid */
int*ptr;
ptr=ptr+9;
#include <stdio.h>
main()
{
int x;
158
www.EngineeringBooksPdf.com
PROGRAMMING IN C
int*ptr1,*ptr2;
x=10;
ptr1=&x;
ptr2=ptr1+6;
printf(“ Value of x=%d\n“,x);
printf(“Value pointed by ptr1 =%d\n “,*ptr1);
printf(“ Address of x pointed by ptr1=%d\n“, ptr1);
printf(“Content of ptr2=(ptr1+6)is =%u “,ptr2);
printf(“Value pointed by ptr1=%d “, *ptr2);
}
OUTPUT:
int*p1,*p2;
p1=p1*p2; /*Invalid*/
p1=p1/p2; /*Invalid*/
1. Call by reference
2. Call by value.
159
www.EngineeringBooksPdf.com
PROGRAMMING IN C
int x, y;
To pass by reference the variables x and y to function add,
add (&x, &y); /*address of x and y is passed*/
In the called function add () x and y variable values can obtained by
inserting asterisk (*) before the formal parameters name. For example,
main()
{
int x ,y, z;
x=10;
y=20;
add(&x, &y); /*Call by reference*/
z=x+y; /*Z=20+40=60*/
____________
_____________
}
add(a,b)
int *a, int *b;/a,b are formal arguments/
{
*a=*a+*a; /*New values will be copied to actual parameters in
main*/
*b=*b+*b;
}
160
www.EngineeringBooksPdf.com
PROGRAMMING IN C
int *p,*q;
{
*p=*p+*p+2;
*q=*q+*q+3;
}
Output:
x=5, y=6
x=1, y=2
Call by value explained well in functions chapter. Here only the value is
passed but not address. Hence the changes made to formal arguments do
not affect the actual parameters in the main function.
An array is actually very much like a pointer. We can declare the arrays
first element of array can be declared as a1[0] or as int *a1 because a[0]
is an address and *a is also an address. Hence the correspondence
between array and pointers can be understood in the following section.
An array is a collection of items of the same data type. For example, the
following are all array declarations:
161
www.EngineeringBooksPdf.com
PROGRAMMING IN C
#include<stdio.h>
main()
{
int a[4]={1,2,3,4};
int*ptr;
int i,n,temp;
n=4;
Printf(“ Contents of array\n“)
for(i=0;i<=n-1;i++)
temp=a[i];
printf(“a[%d]value =%d \n“ i, temp);
}
Output:
Contents of array
a[0] value=1
a[1] value=2
a[2] value=3
162
www.EngineeringBooksPdf.com
PROGRAMMING IN C
a[3] value=4
OUTPUT:
string is: hello
string pointed by pointer ptr1: hello
#include <conio.h>
void main() {
clrscr();
char *array[2];
array[0]="Hello";
array[1]="World";
printf("The Array of String is = %s,%s\n", array[0], array[1]);
getch();
}
Output
The Array of String is = Hello, World
All the string functions can be used with pointers. Consider a below
program to understand usage of strlen()function with pointer.
163
www.EngineeringBooksPdf.com
PROGRAMMING IN C
OUTPUT
1.10 Questions
a) int a;
int *integer_pointer;
a=222;
integer_pointer=&a;
printf(“The value of a a %d\n”, a);
printf(“The address of a %d\n”,&a);
printf(“The address of integer_pointer %d\n”, &integer_pointer);
printf(“Star integer_pointer %d\n”, *integer_pointer);
b) for char
char a;
char *char_pointer;
a=’b’;
char_pointer=&a;
164
www.EngineeringBooksPdf.com
PROGRAMMING IN C
c) for float
float a;
float *float_pointer;
a=22.25;
float_pointer=&a;
printf(“The value of a %d\n”, a);
printf(“The address of a %d\n”, &a);
printf(“The address of float_pointer %d\n”, &float_pointer);
printf(“Star float_pointer %d\n”, *float_pointer);
d) int a, b
int *ip1, *ip2;
a=5;
b=6;
ip1=&a;
ip2=ip1;
printf(“The value of a is %d\n”, a);
printf(“The value of b is %d\n”, b);
printf(“The address of a is %d\n”,&a);
printf(“The address of b is %d \n”&b);
printf(“The address of ip1 is %d\n”, &ip1);
printf(“The address of ip2 is %d\n”, &ip2);
printf(“The value of ip1 is %d\n”,ip1);
printf(“The value of ip2 is %d\n”, ip2);
****
165
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Module 5
UNIT 2: Preprocessors
2.1 Introduction
Preprocessor directives follow the special syntax rules that are listed
below.
Executed by the pre-processor.
Occurs before a program is compiled.
Begin with #.
Would not end with semicolon.
Can be placed anywhere in the program.
Normally placed at the beginning of the program or before any particular
function.
C compiler
Object code
(.obj file) Machine code
Executable
Librari
.obj files Linker .exe
codefile
unconditional directives
166
www.EngineeringBooksPdf.com
PROGRAMMING IN C
The preprocessor directives can be divided into three categories. They are
167
www.EngineeringBooksPdf.com
PROGRAMMING IN C
#define PI 3.1415926
#define CAPITAL “BANGALORE”
#define AREA 12.36
#include<stdio.h>
#define PI 3.14
#define ERROR_1 "File not found."
#define QUOTE "Hello World!"
main()
{
printf("Area of circle = %f * diameter", PI );
printf("\nError : %s",ERROR_1);
printf("\nQuote : %s\n",QUOTE);
}
#include<stdio.h>
main()
{
printf("Area of circle = %f * diameter", 3.14 );
printf("\error : %s","File not found.");
printf("\nQuote : %s","Hello World!\n");
system("pause");
}
Output
Area of circle = 3.140000 * diameter
Error : File not found.
Quote : Hello World!
2.3.2 Macro Inside the Quotes
While programming, care should be taken such that macro is not included
inside quotes because the macro inside a string does not replaced. For
example ,
168
www.EngineeringBooksPdf.com
PROGRAMMING IN C
# define P 5
sum= P+ value;
printf(“P= %d\n “, P);
sum= 5+ value;
printf(“P= %d\n “, 5);
volume=CUBE(side);
The preprocessor would expand the statement to
volume =(side*side*side)
# undef CUBE
For example,
169
www.EngineeringBooksPdf.com
PROGRAMMING IN C
#include<stdio.h>
#include<string.h>
main()
{
-----
-----
printf(“ ---“);
x= strcpy(---);
}
In the above program printf() is defined in the standard library file
stdio.h.and strcpy is defined in string.h. library file.Because of this stdio.h
and string.h are used in the file inclusion macro.
2.5 Questions
1) what is a macro?
2) What is a preprocessor? How it is different from a macro?
3) What is a header file in c? What is the purpose of using this in
program?
4) List out preprocessor directives.
5) What are the advantages of macro?
*****
170
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Module 6
Unit 1: STRUCTURES
1.1 Introduction
171
www.EngineeringBooksPdf.com
PROGRAMMING IN C
To use the structure within a program, the special data type, called as
structured data type has to be created.. The general format for defining
the structured data type is given below.
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
Here, the fields: title, author, pages and price are called as structure
elements or members. Each of these members belongs to different data
types. The name of structure ‘book’ is called structure tag.
172
www.EngineeringBooksPdf.com
PROGRAMMING IN C
This declares book1, book2 and book3 as variables of type struct book.
The entire structure with variable is given below.
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
struct book book1, book2, book3;
struct book
{
char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
struct book
{
char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
book1.price;
book2.author;
173
www.EngineeringBooksPdf.com
PROGRAMMING IN C
book3.pages;
book1.title;
Like any other data type, a structure variable can be initialized at compile
time. The general format for structure initialization is
struct time
{
int hrs;
int mins;
int secs;
}t1,t2;
174
www.EngineeringBooksPdf.com
PROGRAMMING IN C
1) #include<stdio.h>
main()
{
struct student
{
int roll_no;
char name[10];
int age;
}s;
printf(“Enter roll, name and age: ”);
scanf(“%d %s %d”, &s.roll_no, s.name, &s.age);
printf(“\nEntered information: \n”);
printf(“Roll number: %d”, s.roll_no);
printf(“\nName: %s”, s.name);
printf(“\nAge: %d”,s.age);
}
Result:
Input:
Enter roll, name and age:09kbt657, shyam,
Output:
Input information:
Roll number: 09kbt657
Name: shyam
age: 17
2) #include <stdio.h>
int main (void)
{
struct date
{
int month;
int day;
int year;
};
struct date today;
today.month = 4;
today.day = 25;
today.year = 2009;
175
www.EngineeringBooksPdf.com
PROGRAMMING IN C
Output
#include <stdio.h>
void main()
{
struct book
{
char name[20];
char auth[20];
int page;
float price;
};
struct book b;
printf("\n ENTER THE NAME OF THE BOOK: ");
gets(b. name);
printf("\n ENTER THE NAME OF THE AUTHOR: ");
gets(b. auth);
printf("\n ENTER THE NUMBER OF PAGES: ");
scanf("%d", &b.page);
printf("\n ENTER THE PRICE OF THE BOOK: ");
scanf("%f", &b.price);
printf("\n NAME OF THE BOOK: %s",b.name);
printf("\n NAME OF THE AUTHOR: %s ", b.auth);
printf("\n NUMBER OF PAGES: %d ", b.page);
printf("\n PRICE OF THE BOOK: %0.2f ",b.price);
getch();
}
Result:
Input
ENTER THE NAME OF THE BOOK: Complete Reference Java
ENTER THE NAME OF THE AUTHOR: Schildt
ENTER THE NUMBER OF PAGES:1000
ENTER THE PRICE OF THE BOOK:395
176
www.EngineeringBooksPdf.com
PROGRAMMING IN C
NUMBER OF PAGES:1000
PRICE OF THE BOOK:395
1.5 Questions
1) What is a structure?
2) How structure is different from array?
3) How to declare a structure? explain with an example
4) How do you access the members of structure? Explain with an
example.
5) How do you initialize the structure ? Explain with an example.
6) Define a structure that contains the following three members:
(a) an integer quantity called won
(b) an integer quantity called l o s t
(c) a floating-point quantity called percentage Include the user-
defined data type record within the definition)
*****
177
www.EngineeringBooksPdf.com