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

C- Programming Full Notes

Uploaded by

darshansyd270
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C- Programming Full Notes

Uploaded by

darshansyd270
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

C-Programming 1st Sem BCA

Chapter-1

Introduction to Programming

Definition : Program: “ A Program is set of instructions written in computer languages.”

Steps in Problem Solving:

1 The problem solving by a computer involves following steps.

Problem
Definition

Problem Analysis

Design

Coding

Testing

Maintenance
6

The above representation is known as “Program Development Life Cycle (PDLC) “.

Problem Definition : This is the first step in problem solving. In this identify and define the problem.
It means what are the requirements we need to solve a problem.

Problem Analysis : The given problem must be analyze before it is solved. It means what are the
operations to be performed on the problem.

Design : After defining and analyzing a problem the programmer must design a solution of that
problem. For this purpose the programmer can use two programming tools.

The common programming tools are

 Algorithm
 Flowchart

Algorithm: “Algorithm is a step by step procedure to solve a particular problem”.

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 1 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Steps can write algorithm:


Step 1: start
Step 2: input
Step 3: calculation [ process ]
Step 4: output
Step 5: stop

Example of algorithm: [ write an algorithm for sum of 2 numbers ]


Step 1: start
Step 2: input a,b,c
Step 3: c=a+b
Step 4: output c
Step 5: stop

Write an algorithm for simple interest


Step 1: start
Step 2: input p,t,r,si
Step 3: si=(p*t*r)/100
Step 4: print si
Step 5: stop

Characteristics of an Algorithm:
 It may accept one or more input.
 It should produce at least one output.
 No instruction can be repeated.
 Algorithm must have finite number of steps.

Flowchart: “ Flowchart is a graphical or pictorial or symbolic representation of an algorithm”.

Symbols we are used in Flowchart

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 2 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
Circle Connector

Hexagon Looping

Advantages of Flowchart:
 It is convenient method of understanding program.
 It acts as an important tool for planning and designing a new system.

Disadvantages:
 It is difficult to remember the symbols.

Example of Flowchart:

Coding:
Once we complete algorithm and flowchart we proceed the next step of coding.
“coding is nothing but writing an instructions in a particular language to solve the problem.”

Testing:
After writing a program , programmer needs to test the program for completeness and correctness.

Maintenance:
Maintaining a program is review of the program means any improvements or modifications
Are required for the proper documentation of a program.
Basic Control Structures

Control structure: “The ability to control the flow of execution of a program is known as control
structure”. They are :
 Sequence
 Selection

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 3 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

 Iteration
 Jumping

Sequence : it just executes statements one by one in an order. Most of the code in any problem
belongs to this category only.
Syntax:
Statement 1

Statement 2

….…..

Statement n

Selection: it executes statements based on the condition only. Whether that condition is true then first
statement will be executed otherwise second statement will be executed.

Syntax: if (condition)
Statement 1
else
Statement 2

Flowchart:

Iteration: “It is also known as repetition. It executes statements repeatedly as long as condition is
true.” Syntax: while(condition)
{
Statement 1;
Statement 2;
.
.

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 4 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
Statement n;
}
Flowchart:

Jumping: It is also known as branching. This type of control structure allows the flow of execution
jump to a different part of the program.

Structured Programming
It is also known as modular programming.

Definition: “Designing and solving a program using sequence, selection and iteration control
structures are called as structured programming”.

Advantages:
 Easy to write, debug, understand and modify programs.

Questions:
1. What is a program? 1M
2. Explain the steps to solve a problem. 5M
3. Write any two characteristics of an Algorithm? 1M
4. Define an algorithm and flowchart. 1M
5. Write an algorithm for Simple interest. 3M
6. What are the advantages of an algorithm? 1M
7. What is Structured programming? 1M
8. What are the advantages and disadvantages of flowchart? 1M

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 5 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Chapter-2

Overview of C

Computers can be utilized efficiently only when the communication between human beings
through the languages. We cannot think of English for communicating with computer. But it is
possible to use English like language to work with the computer.

“C is English like language. When we want to learn one English language we are following
these steps.” As similar in C also

Steps in learning Steps in learning


English language C-language

As similar English language we are learn one programming language must and should we follow
above steps. Means first we learn alphabets and then next we learn keywords etc and then using those
words we frame instructions. Finally we are using these instructions we will frame a program.

Types of Languages:

There are 2 main languages are there. They are

 Low level languages


 High level languages.

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 6 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

History of C (or) Evolution of C

Year Language Developed By

1960 ALGOL 60 International Committee

1963 CPL (Combined Cambridge University


Programming Language )

1967 BCPL (Basic Combined Martin Richards at


Programming Language) Cambridge University

1970 B Ken Thompson at AT & T


Bell Laboratory (USA)

1972 C Dennis Ritchie at AT & T


Bell Laboratory (USA)

C is oftenly known as” Middle level language.” Because C has combining features of both high level
and low level languages.

C is a Middle level language. Justify

Before we are answering this question first we must know what are the features of high level and
low level languages.

Features of high level language:

 In this languages writing program is easy.


 Debugging is also easy.
 The speed of execution will be slow when compared to the low level language.

Features of low level language:

 In this languages writing program is difficult.


 Debugging is also difficulty.
 The speed of execution will be faster.

But in C writing program is easy and debugging is easy and also execution speed will be faster.
So this is the reason “C is a Middle level language.” And also C has the combining features of
both BCPL and B languages.

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 7 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
“ C is a programming Language developed at AT & T’s Bell Laboratories of USA in 1972.

It was designed & written by Dennis Ritchie”.

“C inherited the features of B and BCPL,

added some of his own and developed”.

Basic Structure of C-Programming


Document Section
Header file Section (or) linking Section
Global Declaration
main()
{
Local Declaration;
Statements;
}

 Document Section:

This Section contains comments.comments are used to increase readability and


understandability.comments are used any where in our program having no errors. Comments are non
executable statements. This section is optional.

The starting of the comment is indicated by /*

Ending of the comment is indicated by */

Ex: /* welcome to my home */

 Header File Section: This Section helps to include the external file functions such as headerfiles
from the system. This is also known as link section.

Linking: linking puts all other program files and functions together that are required by the program.

We are using different header files such as

o #include<stdio.h>
o #include<conio.h>
o #include<math.h> etc.

Each and every header file must be begin with the # symbol. This # symbol is known as
“preprocessor”. Before processing the program this # symbol instructs the compiler to include all
statements corresponding herder file. For that purpose we used include keyword.

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 8 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

 # include is known as preprocessor directive.

Along with preprocessor directive include header file. Each and every header file must be enclosed
within the angle brackets (< >).

 #include<stdio.h>: in this stdio.h refers to standard input and output statement header file.

The related statements under this header file is

Standard output statement in C will be printf

Standard input statement in C will be scanf

 #include<conio.h> : in this conio.h refers to console input and output header file.

The related statements under this header file is

To clear the output(terminal) screen clrscr();

To visible the output on the output screen getch();

#include<math.h>: any type of mathematical operations included in our program that time we used
this header file.

 main() function:

It is the compulsory part in our program. C program.C program contains one or more
functions, but one which must be main() function. Every program execution in C must be begins with
main().

Here we are representing before main() void keyword. Why means void is a keyword which
should not return a value.

It indicates Start of the function.

It indicates End of the function.

#include<stdio.h> header file

void main() main() function must

{ starting of the function

printf (“welcome to C program”);

} printf is a function to print some


text enclosed within the double
end of the function quotes.

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 9 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

 Decleration:
This section contains representing variables in our program.
This decleration can be two types. They are
o Global decleration
o Local decleration

Global decleration: variables are declared before the main() function. These variables are related to
all functions.

Ex: int a,b; here a and b are global variables.


main()
{
statements;
}
Local decleration: variables are declared inside the function. These variables are related to that
perticular function.

Ex: main()
{
int a,b; here a and b are local variables.
Statements;
}
 Statement is a single line of instruction (or) information. Each and every statement must be
terminated by semicolon.
 Function is a set of statements.

Sample program
void main()
{
clrscr();
printf(“\n welcome to C program”);
getch();
}
After writing the program save that program with .c extension.(using f2)

After save then we are compiling our program. Compiling means debugging means error
rectification.(using f9).

After that run the program (ctrl+f9).

/* WAP to sum of 2 numbers */


void main()
{
int a,b,c;

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 10 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
clrscr();
printf (“enter 2 numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf (“\n sum of 2 numbers is %d”,c);
getch();
}
Output:
Enter 2 numbers 2 3
Sum of 2 numbers is 5.

/* WAP to sum of 2 numbers by using initialization method */


void main()
{
int a=3,b=3,c;
clrscr();
c=a+b;
printf(“\n sum of 2 numbers is %d”,c);
getch();
}
Here we are used initialization procedure in that we assigning values to variables.

Executing a program (or) C – Conventions


The following steps are essential in executing a program in C.

 Creation of a program.
 Compilation and linking of a program.
 Executing the program.

Creation of program:

Programs should be written by using editor. After typing the program, save that program
along with .c extention.

Compilation and linking of a program:

After writing source program we need the help of compiler to change the source to object
program (or) machine program.

Executing the program:

After compiling, the executable code will be loaded in computer main memory.

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 11 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Programming Style:

 All statements should be written in lower case letters.


 The programmer can be written the statement anywhere in between the flower braces.
 The user can write more than one statement on a single line by separating them by a comma
operator.
 The opening and closing braces should be balanced.
 Using comments whenever necessary. Comments are increases program readability and also
help to understand the program logic.

Source Program: It is a program which was created by user in any high level language. It is known
as high level language.

Object Program: C Compiler converts source program in to its machine equivalent code that is
known as object program. It is generated by the compiler.

C is a portable language: The C program written in one computer system can be compiled and run
on other systems with little or no modifications. Hence C language is a portable language.

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 12 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Questions:

1. What is local and global variables ?


2. Explain the structure of c-program.
3. Who developed c-program.
4. What is high level language? Give one example
5. Why C is called as Middle level language.

Mr. MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D) 13 VVFGC,TUMKUR.


C -Programming VVFGC, Tumkur

Chapter – 3

Operators and Expressions


A program is a set of instructions, which will be executed in a sequential form. These statements
are formed using group of basic elements such as character set and tokens.

It can be represented as

C character set

Keywords, data types, constants,


variables etc are the “tokens”.

Statement 1 Statement 2 Statement 3 …. Statement n

Collection of statements
called as “program”.

C - Character set
C is a general purpose language. It contains 2 parts. They are

 Syntax
 Semantics

Syntax of a C language specify character set, words, operators etc. according to the syntax rule
valid C-program can be formulated.

Silpa K C[M.Sc] 1 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Semantics of C language assigns exact meaning of actions to be performed.

The C-character set classified into 4 categories. They are

 Alphabets
 Digits
 Special symbols
 White spaces

Alphabets: C language allows both lower case and upper case letters. But both are having
different significances. [A-Z] , [a-z]

Digits: C language allows 0 – 9 decimal digits.

Special symbols: C allows special symbols like ; , @ , # ,$ ,% , ^, z etc.

White spaces: C allows tabs, space etc white spaces.

C-Tokens
“The smallest individual elements in programming are known as tokens”.

C-Tokens

keywords constants variables operators strings identifiers

Keywords:
Keywords are the reserve words for specific meaning in C language. All keywords have
predefined meaning. Keywords are in lowercase letters only.

Every word in C language is classified as either keyword or an identifier. C has nearly 32


keywords. All keywords have fixed meaning it cannot change.

The list of keywords are


asm auto break case char int float double

else long enum return short signed sizeof static

goto while do done void for union continue

extern register default if struct switch typedef case

Silpa K C[M.Sc] 2 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Identifiers:
“A identifier is a name given to a variable, function and array etc programming
elements”.

Rules for naming identifier:

 The first character must be an alphabet or an underscore.


 Identifiers must consist of only alphabets, digits or underscore. Special characters are not
allowed.
 The maximum length of an identifier in turbo C is 31 characters.
 Keywords should not be used as identifiers.
 Identifier should be a single word. No blank spaces are allowed.
 Identifiers are both uppercase and lower case letters. But both are having different
signicances.

Constants:
“ It is a physical quantity which does not change its value during executing of a
program is known as constant”.

Constants are mainly 2 types. They are

Integer :

Integer constant is a whole number. It has a sequence of digits with out having a decimal
point. It is prefixed with a positive(+) or negative(-) sign.

Syntax:

Sign digit

Silpa K C[M.Sc] 3 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Ex: +125 , -3456 etc.

Floating:

This type of constant has a seequence of digits having decimal point. It is also prefixed
with positive or negative sign.

Before decimal point it cann be represented by integer part.

After decimal point it can be represented by fractional part.

Syntax:

Sign integer part decimal point fractional


part

Ex: + 20. 1234, -7.234

Character constant:

A character constant is a single charcter which is enclosed with in a pair of single quote.

Ex: ‘a’,’d’ etc.

String constant:

It is a sequence of characters which is enclosed with in double quotes.

Ex: “welcome”, “vvfgc” etc.

Variables:
“The quantity that has changes value during executing of a program is known as
variable.”

The variables are the names given to identify the specific elements. These are also known as
identifiers. Variables are represent a perticular memory location where the data can be stored.

Ex: a,b,c ;

Rules to apply varible:

 The first character must be an alphabet or an underscore.


 All succeding charcaters consists of letters and digits.
 variables must consist of only alphabets, digits or underscore. Special characters are not
allowed.

Silpa K C[M.Sc] 4 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

 All variables are in lowercase letters.


 There is no limit on the number of characters in a variable name.

Methods of variable:

Declaration of variable:

All variables must be declared before they are used in program. “the purpose of
declaring variables is to reserve amount of memory required for those variables”.

General format of declaring variable:

datatype variable list ;


Ex: int a, b,c ;

We can declare one or more variables on single line by using comma operator.

Assigning value to variable:

“the process of assigning values to variables is known as initialization”. Here we are


used assignment operator (=).

General format of initialization:

Datatype variable1=value , variable2 = value ……variable n= value ;


Ex: int a=10, b=20 ;

Data type:
The data types are used to inform the type of value that can be stored in a variable. The
data may be numeric or non-numeric. In C data types are classified into 2 ways. They are

 Built in data types


 User defined data types

Built-in data types:

C has 4 basic data types. These are also known as primitive (these operates by machine)
data types. They are

 integer
 floating point number
 double precession number
 character

Silpa K C[M.Sc] 5 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

integer : (int)

All integer numbers are whole numbers without a decimal point. All these numbers can
be preceeded either + or –ve sign.

Ex: 100 , -65 etc.

It is represented by int. the size of this data type will be 2 bytes. For this we are used the format
specifier like %d. the range of this data type will be -32768 to +32767.

2 bytes = 16 bits

2 16 – 1 = 65535

(min) -32768 (max) +32767

Floating point: (float)

Float is a key word used to indicate floating point numbers. These are numbers with
decimal point. Float data type occupies 4 bytes of memory. The range of this data type is 3.4 *10
-38
to 3.4 * 10 +38.

After decimal point this data type will takes only 6 digits of precession. For this data type we
will use %f format specifier.

Ex:20.345, -56.765 etc

Double precession: (double)

This data type is used to declare the variables to hold the large floating point numbers.
When higher precession numbers are required, instead of using float double data type is used.

After decimal digit it will take 14 digits of precession. For this %lf format specifier will be used.
It occupies 8 bytes of memory.

The range of this data type will be 1.7 * 10 -308 to 1.7 * 10 +308.

Ex: +123.566788 etc

Character: (char)

This means that a variable is a character. A char is a single ASCII character. Any symbol
enclosed with in a pair of single quote is a charater.

It occupies 1 byte (8bits) of memory. For this we are used %c format specifier. The range of this
data type will be -128 to +127.

Silpa K C[M.Sc] 6 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

1 byte= 8 bits
2 8 – 1 = 255

(Min) -128 (max) +127

Units of Computer Memory Measurements


1 Bit = Binary Digit
8 Bits = 1 Byte
1024 Bytes = 1 KB (Kilo Byte)
1024 KB = 1 MB (Mega Byte)
1024 MB = 1 GB (Giga Byte)
1024 GB = 1 TB (Terra Byte)
1024 TB = 1 PB (Peta Byte)
1024 PB = 1 EB (Exa Byte)
1024 EB = 1 ZB (Zetta Byte)
1024 ZB = 1 YB (Yotta Byte)
1024 YB = 1 BB (Bronto Byte)
1024 Brontobyte = 1 (Geop Byte)
Geop Byte is The Highest Memory Measurement Unit.

Assigning values to variables

Once we have declared a variable, the next step is to assign a value to that variable. “The
process of assigning values to variables is known as initialization.”
We can assign a value to a variable in 2 ways. They are
 using assignment operator
 reading data from keyboard (or) scanf()
using assignment operator:
in this we are used to assignment operator (=).
Syntax: int a=10;
one or more variables can be initialized with one value at the time multiple assignment
operator will used.
Syntax: int x= y= z= 10;
In the above example we are assigned x, y and z those variables have the same value that is 10.
reading data from keyboard (or) scanf():
one more way of assigning values to variables is to input data from heyboard by using
scanf() function.

Silpa K C[M.Sc] 7 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Syntax: scanf(“formatted string”, &variable1,&variable2 …..&variable n);


Ex: scanf ( “%d %f %c”, &a,&b,&c);

Symbolic Constant
A symbolic constant is a name that substitutes a numeric constant in our program.
Ex: area = 3.142 * r* r;
In the above example numeric constant will be 3.142 this can be replaced by symbolic constant
“pi”.
Then we are using one preprocessor directive that is “# define”.
“#define is a preprocessor directive and is used to declare a symbolic constants in C
program”.
The above example can be rewrite as
# define pi 3.142
Ex:
#define x 100 #define x 100
main() main()
{ {
int a,b,c; int a, b, c;
a=10, b=20; a=10, b=20;
c = x; c = 100;
a = a + x; a = 10 + 100;  110
b = x + b; b = 100 + 20;  120
} }

Silpa K C[M.Sc] 8 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Operators and Expressions


Expression:
The combination of operators and operands is known as expression.
Ex: A + B
In above example A and B are operands. + Symbol is an operator.

Operator:
An operator indicates an operation to be performed on the data.

Operand:
An operand is an entity on which operators perform the operations.

C – Operators
C language provides different types of operators. They are

Unary Operators
An operator that acts upon only one operand is known as unary operator. The unary operators are

Unary minus:

Silpa K C[M.Sc] 9 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Any positive operand can be associated with unary minus operand then its value gets
changed to negative. It is indicates with – operator along with operand.

Syntax: - (operand)

Ex: consider a=3 then b= -a

b = -3

in the above example initially the value of a is 3 but when this a has associated with unary minus
its value gets changed to negative.

Increment and Decrement Operator:

Increment Operator:

This operators used to increment the value of an integer quantity by one.

This is represented by “++” (double plus) symbol. This symbol can be placed either before or
after an integer variable.

This increment is two types. They are pre increment and post increment.

Pre increment:

When the increment operator can be placed before the integer variable that is known as
pre increment operation.

Syntax: + + operand ; (or) + + intvar ;

 In this the first the value of operand or integer variable must be incremented.

 And then use or store that value.

In short cut this referred as “increment and use”.

Ex: a= ++b

This is equivalent to 2 assignment statements. They are

b = b + 1;

a = b;

ex: a= 6 then ++a is 7

Post increment:

Silpa K C[M.Sc] 10 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

When the increment operator can be placed after the integer variable that is known as
post increment operation.

Syntax: operand + + ; (or) intvar + + ;

 In this the first the value of operand or integer variable must be stored or used.

 And then increment that value.

In short cut this referred as “use and increment”.

Ex: a= b + +

This is equivalent to 2 assignment statements. They are

a = b;

b = b + 1;

ex: a= 6 then a+ + is 6 only.

/* program to demonstrate increment operators */

void main()
{
int m = 6 , n = 8;
printf(“ m is %d\n”, + + m);
printf(“n is %d\n” , n + + );
}
Decrement Operator:

This operatoris used to reduce the value of an integer quantity by one.

This is represented by “- -” (double minus) symbol. This symbol can be placed either before or
after an integer variable.

This decrement is two types. They are pre decrement and post decrement.

Pre decrement:

When the decrement operator can be placed before the integer variable that is known as pre
decrement operation.

Syntax: - - operand ; (or) - - intvar ;

 In this the first the value of operand or integer variable must be decremented.

 And then use or store that value.

Silpa K C[M.Sc] 11 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

In short cut this referred as “decrement and use”.

Ex: a= - - b

This is equivalent to 2 assignment statements. They are

b = b - 1;

a = b;

ex: a= 6 then - - a is 5

Post decrement:

When the decrement operator can be placed after the integer variable that is known as
post decrement operation.

Syntax: operand - - ; (or) intvar - - ;

 In this the first the value of operand or integer variable must be stored or used.

 And then decrement that value.

In short cut this referred as “use and decrement”.

Ex: a= b - -

This is equivalent to 2 assignment statements. They are

a = b;

b = b - 1;

ex: a= 6 then a - - is 6 only.

/* program to demonstrate decrement operators */

void main()

{
int m = 6 , n = 8;
printf(“ m is %d\n”, - - m);
printf(“n is %d\n” , n - - );
}

Silpa K C[M.Sc] 12 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Binary Operators
An operator that acts upon minimum two operands is known as binary operator. The binary
operators are

Arithmetic Operators:

These rea the operators used to perform the basic arithmetic operations such as addition ,
subtraction, multiplication and division.

The modulus operator is added to the list of C arithmetic operators. It is used to find the
remainder value.

operations operator precedence associativity


addition + 2 L to R
subtraction - 2 L to R
multiplication * 1 L to R
division / 1 L to R
modulus % 1 L to R

/* program to demonstrate Arithmetic operations */

void main()
{
int a , b ,sum sub, mul, div ;
printf(“\n enter 2 numbers”);
scanf(“%d%d”, &a, &b);
sum = a + b ;
sub = a – b;
mul = a * b;
div = a / b;
printf(“\n sum is %d\n”, sum);
printf(“\n sub is %d\n”, sub);

Silpa K C[M.Sc] 13 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

printf(“\n product is %d\n”, mul);


printf(“\n quotient is %d\n”, div);
getch();
}

Relational operators:

These are used to compare two operands given in an expression.

They define the relationship that exists between 2 constants or variables. They result in either a
true or false value. The value of true is nonzero that is 1 and that of false is zero.

There are 6 relational operators in C.

operator description example result


> greater than 8>5 TRUE
< less than 8<5 FALSE
greater than or
>= equal to 8>=10 FALSE
<= less than or equal to 8<=8 TRUE
== equal to 5= = 5 TRUE
!= not equal to 5!=5 FALSE

void main()
{
int a=10, b=5;
printf (“ a==b %d\n”, a==b);
printf ( “a!=b %d\n”, a!=b);
}

Logical operators:

These are used to combine two or more expressions. A logical relationship between the
two expressions. A logical relationship between the expressions is checked with logical
operators.

The logical operators are

operator description example Returnvalue


&& LogicalAND 8>5 && 5>3 TRUE
|| logical OR 8<5 || 5<3 FALSE
! logical NOT ! (8<15) FALSE

Silpa K C[M.Sc] 14 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Truth table for logical AND (&&) operator:

T T T
T F F
F T F
F F F

Truth table for logical OR ( | | ) operator:

T T T
T F T
F T T
F F F

Truth table for logical NOT ( ! ) operator:

T F
F T

/* To demonstrate the logical operators */

void main()

printf (“5>3 && 3>10 %d\n”, (5>3) && (3>10));

printf (“!(8= = 8) %d\n”, !(8= =8));

Bitwise Operators:

All data items are stored in the computer memory as a sequence of bits (0’s and 1’s).

C provides 6 bitwise operators. They are

Silpa K C[M.Sc] 15 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

operator symbol name meaning


& ampersand bitwise AND
| pipeline bitwise OR
^ caret (exponent) exclusiveOR(XOR)
~ tilde character 1's compliment
<< double less than left shift
>> doublegreaterthan right shift
Bitwise AND (&):

The bitwise AND operator is represented by a single &. This operator operates on two
integer operands. When two operands are one (1) then the result of this operation will be 1.
Otherwise zero (0).

Truth table for bitwise AND (&) operator:

0 0 0
0 1 0
1 0 0
1 1 1

Ex: X = 5 : 00000101

Y = 3 : 00000011

X&Y= 00000001

Bitwise OR ( | ):

The bitwise OR operator is represented by a single | (pipeline). This operator operates on


two integer operands. When two operands are zero (0) then the result of this operation will be 0.
Otherwise one (1). (or)

If any one of the operands will be one then the result of this operation will be one
otherwise zero.

Truth table for bitwise OR ( | ) operator:

0 0 0
0 1 1
1 0 1
1 1 1

Silpa K C[M.Sc] 16 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Ex: X = 5 : 00000101

Y = 3 : 00000011

X | Y= 00000111

Bitwise XOR operator ( ^ ):

The bitwise XOR operator is represented by a ^ (carot) symbol. This operator operates on
two integer operands. When two operands are zero (0) and one then the result of this operation
will be 0. otherwise one (1).

Truth table for bitwise XOR ( ^ ) operator:

0 0 0
0 1 1
1 0 1
1 1 0

Ex: X = 5 : 00000101

Y = 3 : 00000011

X ^ Y= 00000110

Bitwise compliment operator ( ~ ):

This operator is also called as 1’s compliment operator. This operator changes 1 to 0 and
0 to 1. This is represented by ~ (tilde character).

Ex: if x=5 then bitwise compliment operator on ~x will be

X = 5 00000101

11111010

Bitwise left shift operator ( << ):

This shifting operator can change the input number.

Left shift operator is used to move bits from left side to right side. It is represented by << (double
less than).

Syntax: <variable> <shift operator> <number of bits>

Ex: a << 5

Silpa K C[M.Sc] 17 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Ex: if X= 10 then its binary number is

X = 10  00001010

X << 3 then we will get 01010000

Bitwise right shift operator ( >> ):

This shifting operator can change the input number.

Right shift operator is used to move bits from right side to left side. It is represented by >>
(double greater than).

Syntax: <variable> <shift operator> <number of bits>

Ex: a >> 5

Ex: if X= 10 then its binary number is

X = 10  00001010

X >> 3 then we will get 00000001

/* program to demonstrate bitwise operators */

void main()

printf(“12&8 is %d\n”, 12&8);

printf(“12|8 is %d\n”,12|8);

printf(“10<<4 is %d\n”, 10<<4);

Ternary Operator
This is known as conditional operator. This is used to test the relationship between two variables.
This operator contains a condition followed by two statements or two values.

If the condition is true then the first statement 1 is executed otherwise second statement
will be executed. The condition operator is represented by “ ?: “. It requires two or more
arguments.

Syntax: (condition) ? expression1 : expression2

Silpa K C[M.Sc] 18 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Ex: int x=10 , y=5, z;

z(x>y) ? x : y

the condition x>y is true then x value is printed otherwise y will be printed.

Special Operators
 Assignment Operator:

This operator is used to assign values to variables. This operator represented by “ = “


symbol.

Syntax: variable = value ;

Ex: a = 5;

The difference between = and = = operators are

= is the assignment operator, which is used to assigning values to variables.

= = is the relational operator, which is used to compare two quantities means constants, variables
etc.

 Compound assignment operators:

Some times we may require to modify the value of a variable by incrementing,


subtracting, multiplying and dividing with the value of an expression using assignment operator.
In such situations we need compound assignment operator.

Ex: x = x + a it can also represents as x + = a

Y = y * z it can also represents as y * = z

operator Description example meaning


= Assignment n=6 assign 6 to the number
+= sum and assign n+=6 adds 6 and assign to number
- = subtract and assign n-=6 subtract 6 and assign to number
multiply with 6 and assign to
*= multiply and assign n*=6 number
/= divide and assign n/=6 divide by 6 and assign to number
Bitwise AND and
&= assign n1&n2 AND operation on n1 and n2

Silpa K C[M.Sc] 19 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

 Comma Operator:

The comma operator can be used to link the related expressions. It is also known as
delimiter or separator. Using comma operator two or more expressions may be combined into a
single expression.

Syntax: expression1, expression2, expression3 ……..expression n

Ex: temp = a;

a= b;

b = temp; it can also represents in a single line using comma operator

temp = a; a = b; b = temp ;

 Size of ( ) Operator:

Size of ( ) operator returns the number of bytes used for the operands, constants, data
types etc.

Syntax: size of (operand);

Where the operand can be data type, constants or variables using this operator we can get
the size of any data type.

Ex: size of(char) = 1byte

size of(int) = 2bytes

int i;

size of (i) = 2 bytes

Arithmetic Expressions
A group of constants, variables and operators arranged as per the syntax is known as arthemetic
expression.

Arthemetic expression can be classified into 3 types. They are

 Integer Arthemetic expression

 Floating or real Arthemetic expression

 Mixed mode Arthemetic expression

Silpa K C[M.Sc] 20 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Integer Arthemetic:

In this expression all the values should be integers only.

Ex: 2 + 3 = 5

Floating Arithmetic:

In this expression all the values should be floating values.

Ex: 2.5 + 5.6 = 8.1

Mixed mode Arithmetic:

In this some values are integers and some values are real values.

Ex: 2.5 + 2 = 4.5

In this mode by default it will display floating point output.

Type Conversion (or) Type Casting


“ Type conversion is a method of converting a value of one data type to another data
type”.

The type conversions are classified into 2 types. They are

 Implicit Type conversion

 Explicit Type conversion

Implicit Type conversion:

In mixed mode arthemetic expression contains operands of different data types certain
type of conversions are automatically done by the computer itself this is known as implicit type
conversion.

Hierarchy of data types

highest long double

double

float

lowest int

Silpa K C[M.Sc] 21 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Promotion:

When the variable or constant of lower data type is converted into higher data type is
known as promotion.

Ex: int i = 5;

float f;

f = i;

in the above example I is lowest data type that is integer and f is the highest data type that is
float.

Demotion:

When the variable or constant of highest data type is converted into lowest data type is
known as demotion.

Ex: float f = 5.3;

int i;

i = f;

in the above example f is highest data type that is float and i is the lowest data type that is
integer.

Explicit Type Conversion (Type Casting)


In this method we can explicitly convert to the value of one data type to the another data type by
using casting operator. This is known as type casting.

Syntax: <casting operator> expression

Ex: x = (float) 6 + 5 ;

Here 5 and 6 both are integer numbers but the answer will be converted to float data type by
using float casting operator.

Then the answer will be 11.0

/* program to demonstrate type conversion */

void main( )

Silpa K C[M.Sc] 22 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

printf (“5/2 is %d\n”, 5/ 2);

printf (“5/2 is %f\n”,(float) 5/2);

printf (“5.0/2 is %f\n”, 5.0/ 2);

getch();

Precedence of Arithmetic expression


In one arithmetic expression contains one or more operators then computer evaluates this types
of expressions in systematic manner.

During this process computer consider precedence or priority of operators.

precedence level Operator


1 ()
2 ^ , unary increment and decrement
3 *,/,%
4 +,-

Ex: if a =20 , b = 10, c = 5

Then d = a + b * c

In the above example there are 2 operators. They are + and *. In those * has highest precedence
than + operator. For that

d = 20 + 10 * 5

= 20 + 50

d = 70

if same precedence operators are appeared on a single expression in such situations associatively
from left to right the left most operator will be first executed.

Silpa K C[M.Sc] 23 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

CHAPTER - 4
Managing Input/Output Operations
Reading the data from the input devices and displaying the output on the screen using output
devices. These are two main tasks of computer.

The I/O functions in C classified into 2 types. They are


 Formatted I/O functions
 Un formatted I/O functions

Formatted I/O functions


Formatted input function ( scanf() function) :

The scanf() function is the formatted input function.the scanf() is used to accept the
values of any data type. This function scans (or) accepts the values from the standerd input
device.

Syntax: scanf ( “formatted string” , &var1, &var2 …… &var n);

Where

 Formatted string is the format specifiers like %d, %f etc.

 Var1, var2,var3 ----- var n are the arguments passed to the function scanf. They are
address variables.

Silpa K C[M.Sc] 24 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Ex: scanf ( “ %d %f %c “ , &a, &f, &ch);

The second argument in scanf() is the list of variables whose values are to be input. Memory
address of a variable may be obtained by using an ampersand (&) before the variable name.

“ the role of & operator is to indicate the memory location of the variable, so that the value
read at that location.”

/* program to accepts an integer and floating value and print those values */

void main()
{
int a ; float f ;
printf ( “ \n enter integer and float value “);
scanf ( “ %d %f “ , &a, &f );
printf ( “\n integer value is %d float value is %f “ , a, f);
getch();
}

Formatted output function (printf() function) :

The printf() function is the formatted output function. This function prints all types of
values to the console.

Syntax: printf ( “ formatted string “ , list of varibles );

Ex: printf ( “ %d\n %f\n “, a ,f );

Where

 Formatted string is the format specifiers like %d, %f etc and also escape sequences.

 List of varibles are the variables whose values are formatted and printed according to the
specifications of the formatted string.

/* program to print a text on the screen */

void main()
{
clrscr();
printf ( “ welcome to programming “);
getch();

Silpa K C[M.Sc] 25 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

List of escape sequences and format specifiers

Escape sequence:
It causes escape from the normal interpretation of a string. The escape sequence begins
with back slash (\) and is followed by one or more special characters.

Escape sequence meaning


\n newline

\b back space

\t horizontal tab

\a bell / alert

\v vertical tab

Format specifies:
Format specifies specify the type of data that can be displayed from the variables
corresponding to the list of variables with the required format.

Format specifies data type


%d integer

%c character

%f float

%ld long integer

%lf double

%g floating point number in exponent form

%s string

Field width specification for integers:

Syntax1:

printf ( “ %d “, 1234 ); output: 1234

Here compiler wills creates some amount of space that the number required.

Silpa K C[M.Sc] 26 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Syntax 2:

printf ( “ %5d “, 1234 ); output: - 1234

here 5 locations will be created ,but positive format specifier, so that the alignment will be right
to left. So that left side one allocation remaining empty.

Syntax 3:

printf ( “ %8d “, 1234 ); output: - - - - 1234

here also 8 locations will be created , but positive format specifier, so that the alignment will be
right to left. So that left side four allocations remaining empty.

Syntax 5:

printf ( “ %-5d “, 1234 ); output: 1234 –

here 5 locations will be created ,but negetive format specifier is used, so that the alignment will
be left to right. So that right side one allocation remaining empty.

the same thing happened floating point numbers.

Ex: if a= 5432.123

printf( “ %f “, a); output: 5432 . 123

printf(“ % 12. 2 f “, a); output: - - - - - 5432. 12

after decimal digit only 2 digits will be accepted.

For left alingment purpose we use minus before format specifier.

Unformatted I/O functions

Un formatted input functions:

 getchar ()

 getch() and getche()

 gets()

Silpa K C[M.Sc] 27 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

1. Reading a character: (getchar() function)


Reading a single character from the standard input device can be done by using the
function getchar().

The getchar() function reads one character at a time till the user press the entire key. The
getchar() function does not require any argument. Getchar() function requires enter key to be
pressed after the input of character.

Syntax:

character variable = getchar ( )

Ex: void main()


{
char ch;
ch=getchar();
}

2. getch() and getche():


The functions getch() and getche() are unformatted input functions. Getch() and getche()
are used to input only one character at a time through key board and they do not require enter
key to be pressed after the input of character.

The difference between getch() and getche() is that getch() does not display the input
character while entering and getche() display or echos the input character while entering the
character.

Syntax:

character variable = getch ( )

character variable = getche ( )

Ex: void main()


{
char ch;
printf ( “ enter a character “ );
ch= getch();
printf ( “ entered cahracter is %c “, ch);
}

Output: enter a character

Entered caharacter is W

Silpa K C[M.Sc] 28 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

In the above example the character is ‘W’ is entered by the user but getch() does not display the
character typed. If we use getche( ) in place of getch( ) , then we get the result as below

Ex: void main()


{
char ch;
printf ( “ enter a character “ );
ch= getche();
printf ( “ entered cahracter is %c “, ch);
}
Output: enter a character W

Entered caharacter is W

3. gets ( ):
gets( ) is the unformatted input function. This function accept one string at a time.
Syntax:
gets( string)
ex:
gets ( “vvfgc”)

Unformatted output functions:


 putchar ( )
 putch ( )
 puts ( )

1. Writing a character: ( putchar() function)


Writing a character to the standerd output devices can be done by using the function
putchar ( ).
This function prints one character on the screen at a time. The putchar( ) function takes
one argument and that argument is the character is displayed.
Syntax:
putchar ( character variable )

Ex: void main()


{
Char ch;
Ch = getchar ( );
Putchar(ch);
}
Output: X

Silpa K C[M.Sc] 29 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Ex: void main()


{
int i=65 , j; char a, b=’d’;
j= getchar ( );
a = getchar ( );
putchar ( I );
putchar ( b );
putchar ( a );
putchar ( j );
}

Output: XY

AdYX

2. putch ( ) function:
putch ( ) is the unformatted output function. putch ( ) is used to display a character and
the argument to this function is the character to be output.

Syntax:

putch ( charater variable)

Ex: void main()


{
char ch = ‘A’ ;
putch ( ch );
}
The above program outputs the character ‘A’ using putch( ). The functionality of this function is
similar to that of putchar( ).

3. puts( ) function:
puts( ) is the unformatted output function. This function print one string at a time.
Syntax:
puts( string)
ex:
puts ( “vvfgc”)

Silpa K C[M.Sc] 30 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Difference between scanf ( ) and getchar ( ) functions

scanf ( ) getchar ( )
it is formatted input function. It is unformatted input function.

It accepts any type of data like integer, it accept only chracter datatype.

Float, char etc.

It allows format specifiers like %d, %f etc. it can not allow any type of format specifiers.

It can read more than one variable at a time. It can read only one variable at a time.

Syntax: Syntax:

scanf ( “formatted string” , &var1---&var n); character variable = getchar ( );

Difference between printf ( ) and putchar ( ) functions

printf ( ) putchar ( )
It is formatted output function. It is unformatted output function.

It printsts any type of data like integer, It prints only chracter datatype.

Float, char etc.

It allows format specifiers like %d, %f etc it can not allow any type of format specifiers

and also escape sequences like \n, \b etc. and also escape sequences.

It can print more than one variable at a time. It can print only one variable at a time.

Syntax: Syntax:

printf ( “formatted string” , var1---var n); character variable = putchar ( );

Silpa K C[M.Sc] 31 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

CHAPTER - 5
Decision making, Branching and Looping
C has mainly 4 types of instructions. They are

 Type declaration instructions

 Arithmetic instructions

 Input and output instructions

 Control instructions

Type declaration instructions:


These are the instructions used to declare the type of a variable before used in program.

Arithmetic instructions:
These are the instructions used to perform arithmetic operations between variables and
constants.

Input and output instructions:


These are used to perform input and output operations.

Control instructions:
It is the ability to control the flow of execution of a program.
C has mainly 3 types of control structures. They are

 Sequence

 Selection (or) decision (or) branching

 Looping (or) iteration


The C language programs presented until now follows a sequential form of execution of
statements.

Decision making (or) Branching Statement


Branching having different types
1. if statement.
2. if else statement.
3. Nested If statement.
4. Else – if ladder statement
5. Switch – case statement

Silpa K C[M.Sc] 32 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

If Statement
It is one way branching statement. This is depends on the condition.

Whether that condition was true then execute the statements in that if block other wise we come
out from that condition.

 The general form of the if statement is.

Syntax:

if (condition)

{
statement;

Ex:
#include <stdio.h>
main()
{
int i = 3,j = 5;
if(i < j)
printf("value of I is %d”, i);
}
If - else Statement
It is two way branching statement. This is also depends on the condition.

Whether that condition was true then execute the statements in that if block other wise else block
statements are executed.

The general format for an if-else statement is

Silpa K C[M.Sc] 33 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Ex: #include<stdio.h>
void main()
{
int a=10, b=20;
clrscr();
if(a>b)
printf(“a is large %d”, a);
else
printf(“ b is large %d”,b);
getch();
Nested If statement

The if statement may itself contain another if statement is known as nested if statement.
Syntax:

if(condition1)
{
If(condition2)
statement1;
else
statement2;
}
else
{
If(condition3)
Statement3;
}

Silpa K C[M.Sc] 34 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

EX:
main()
{
int a,b,c;
printf(“\n enter 3 numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
printf(“ a is large %d”,a);
else
printf(“ c is large %d”,c);
}
else
{
if (c>b)
printf(“ a is large %d”,c);
else
printf(“ c is large %d”,b);
}
}

Else If ladder Statement


The else-if ladder is a multi-way decision making statement. Which contains two or more else-if,
from which any one block is executed.
The general format for the if-else if statement is

Syntax:
if (condition 1)
simple or group of statement
else if (condition 2)
simple or group of statement
else if ( condition 3)
simple or group of statement
.....
else if ( condition n )
simple or group of statement
else
statement n;

Silpa K C[M.Sc] 35 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Ex:
#include <stdio.h>
main()
{
int i = 2;
if(i == 0)
{
printf(" i == 0");
}
else if(i == 1)
{
printf(" i == 1. \n");
}
else if(i == 2)
{
printf(" i == 2. \n");
}
}

Switch Statement
Switch statement provides multi-way branching. It is an extension of if-else statement. Using if-
else a maximum 2 branches are allowed. If there is need for multiple branches then we use
switch is the best option.
 To take one of a number of possible actions.
 switch is preferred over multiple if...else statements.
Syntax:
switch (expression)
{
case label 1 : statements;
break;
case label 2 : statements;
break;
:
:
case label n : statements;
break;
default : default statements;
} statements;
}

Silpa K C[M.Sc] 36 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

 The expression present within the parenthesis of switch statement must be of type int or
char.
 Based on the expression. The control is transferred to a particular case label are executed.
 The case label must be of type int or char.
 The case default is executed only when none of the cases are true.
 The default block is optional.
 Break is a keyword is used to terminate the switch construct. The control is transferred to
the first statement after the switch construct.
 The labels with several cases need not be in order.
 More than one statement with a case need not be enclosed in braces.
 It is not compulsory to have the statements for a particular case.
 There should not be a semicolon at the end of the closing braces after expression.
 Nested switch construct will be allowed.
Ex:
main()
{
int a=2;
switch (a)
{
case 1 : printf(“number is 1”);
break;
case 2: printf(“ number is 2”);
break;
case 3 : printf(“number is 3”);
break;
default: printf(“invalid number”);
}
}

Looping Statement
Using decision making control structures statements are executed only once during execution of
the program. In some situations, it may be necessary to execute a list of statements more than
once. In such cases, the looping constructs are used.
“ looping construct is a construct that executes the statements repeatedly for a certain number
of times as long as the condition is true.
C has provided three types of iteration statements:
1. While loop.
2. do...while loop
3. For loop
Silpa K C[M.Sc] 37 Lecturer, Dept of BCA
C -Programming VVFGC, Tumkur

While Loop

While loop is also known as “pre tested loop” or “entry controlled loop”.
Why means in this we are first check out the condition. Whether that condition was true then the
control transferred to the inside the loop. Otherwise exit from the loop.
In While looping statement allows a number of lines represent until the condition is satisfied
Ex:
Syntax: #include<stdio.h>
while (condition) main()
{
{
int i = 0;
simple or group of statement while (i<=5)
(body of the loop); {
} printf(" the value of i is %d\n", i);
i = i + 1;
Flowchart: }
}

Do While Loop
In while loop, the condition is tested in the beginning. If the condition becomes false for first
time, then the body of while loop will not executed even once. In some programming situations,
we may require to execute the body of a loop at least once even though condition is false for first
time. In such situations do-while loop is used.
Do-while loop is also known as “post tested loop” or “exit controlled loop”.
Because here we are checked the condition after one iteration. Whether that condition was true
then control transferred to next iteration otherwise comes out from the loop.

Syntax: do

Silpa K C[M.Sc] 38 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

{ #include <stdio.h>
statements; main()
} while (expr); {
int i,n = 5;
i = 1;
do
{
Flowchart: printf("the numbers are %d \n",i);
i = i +1;
}while( i<=n) ;
}

For Loop
For loop is also known as “pre tested loop” or “fixed execution loop”. Thie loop is the
modified form of a while loop.
The for loop is especially used to execute the statements for a certain number of times.

This loop simplifies the program as well as can reduce the number of statements.
Syntax: ex: #include<stdio.h>
for( expression1 ; expression2 ; expression3) main()
{ {
Statement1 int i;
: for ( i=1;i<=5;i++)
: {
Statement printf(“%d”,i);
} }
getch();

Silpa K C[M.Sc] 39 Lecturer, Dept of BCA


C -Programming VVFGC, Tumkur

Jumping control structures


We may come across a situation where we need to terminate the execution of a loop (or) skip
part of a loop. They are

 break statement
 goto statement

Silpa K C[M.Sc] 40 Lecturer, Dept of BCA


C-Programming 1st Sem BCA
Break Statement: The break statement ends execution of the nearest enclosing loop or conditional
statement in which it appears. (or)

The break keyword is used to terminate any of the looping constructs.

This keyword is always used in conection with if within a looping construct.

The flow of execution of break statement is shown below.

Syntax:

while(condition)
{
if(condition)
{
statement 1;
:
statement n
break;
}
}
statement n+1;

Ex: main()
{
int i=1;
while(i<=5)
{
if(i==3)
break;
printf(“%d”,i)
i++;
}
}
In the above program output will be 1 and 2.

When I becomes 3 then break statement will be executed then the control transferred to the out of the
loop.

The continue: when this keyword is encountered, it transfers the control back to the loop condition
by skipping the rest of statements of the body of the loop.

This keyword works only with loops. This cannot be used in switch construct.
The transfer of control of continue statement is as shown below.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 41 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
Syntax: while(condition)

{
if(condition)
{
statement 1;
:
statement n
continue;
}
}

Ex: main()
{
For (int i=1;i<=5;i++)
{
if(i==2)
continue;
printf(“%d”,i);
}
}

In the above example we will get the output of 1, 3, 4, 5.

Because when the value of I becomes 2, the condition (i==2) is satisfied and continue statement will
be executed. At the situation 2 will not be printed it will move to the next iteration.

goto statement:

this is an unconditional branching statement. In order to identify where we are in program, we


must and should needed one label. Alabel is a name that immediately followed by semi colon.

Syntax: goto labelname;

goto even;

goto 5; here 5 is the line number.

Example programs: (nested loops)

1. /* program to find sum of n natural numbers using while statement */

void main()
{
int i=1, sum=0;
while(i<=10)
{
printf(“%d”,i);

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 42 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
sum=sum+I;
i++;
}
printf(“\n sum of first 10 natural numbers is %d”, sum);
}

Output:
1 2 3 4 5 6 7 8 9 10
Sum of 10 natural numbers is 55.

2. /* program to display given series */

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

void main()
{
int i, j, n;
printf(“\n enter the number of lines:”);
scanf(“%d”, &n);
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf(“%d”, j);
}
printf (“\n”);
}
}

3. /* program to find factorial of a given number using for loop */

void main()
{
int num, fact = 1, i;
printf (“\n enter a number”);
scanf(“%d”,&num);
for ( i=1 ; i<= num; i++)
{
fact = fact * I;
}

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 43 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
printf(“\n factorial of %d is %d”, num, fact);
getch();
}

Output:
Enter a number 5
Factorial of 5 is 120.

4. /* program to generate the following series */


* * * *
* * *
* *
*

void main()
{
int i,j,n;
clrscr();
printf("\n enter the number of lines");
scanf("%d",&n);
for( i=n; i>=1; i-- )
{
for( j=1; j<=i; j++)
{
printf("*");
}
printf("\n");
}
getch();
}

5. /* program to generate the following series */


*
* *
* * *
* * * *

void main()
{
int i,j,n;
clrscr();
printf("\n enter the number of lines");
scanf("%d",&n);

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 44 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf ("*");
}
printf("\n");
}
getch();
}

exit() statement:

exit() function is a standerd library function that comes ready made with the C compiler. Its
purpose is to terminate the execution of the program.
Break statement terminates the execution of loop in which it is written, where as exit() function
terminates the xecution of the program itself.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 45 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

CHAPTER - 6
Arrays
A normal variable can hold only one value. Suppose we may need to process a group of data items
that are having the same data ty2pe such as integer, float etc. in such situations we need one special
data structure that is “arrays”.

Definition:
An array can be defined as an ordered collection of homogeneous data elements of same data
type.
Each element in an array is declared by a subscript or index. It is represented by pair of square braces
[ ].
Arrays are mainly classified into 2 types. They are

One dimensional Array


“ It is an array, all the data elements are accessed using same name and single subscript.”
Declaration of one dimension array:

Syntax: datatype arrayname [ size ] ;


Where

 Datatype is any basic datatype or user defined data type.

 Arrayname is the name of the array.

 Size is the number of elements present in that array.


Ex: int a [ 10 ] ;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 46 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Rules for subscript:

 Each subscript size must be positive integer.

 Subscript of subscript is not allowed.

 In C the subscript ranges from 0 to n-1


Accessing elements of an array:
Array elements always starting from 0th the location and ends with n-1. Where n is the size of an
array.
Suppose int a [5] ;
Here first 5 location will be created in memory.

a[0] a[1] a[2] a[3] a[4]

Array Initialisation:

Initialisation is a process of accessing values to a variable.

Syntax: datatype arrayname [ size ] = {ele1, ele2, ……. ele n} ;

Where

 Datatype is any basic datatype or user defined data type.

 Arrayname is the name of the array.

 Size is the number of elements present in that array

 ele1, ele2….ele n are the initial values enclosed with in a pair of braces { }.

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

10 20 30 40 50

a[0] a[1] a[2] a[3] a[4]

Code for accept or read array elements:

printf ( “ \n enter elements to an array”);

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 47 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
for ( i=0; i<n ; i++)

scanf ( “%d” , &a[i]);

Code for print or display array elements:

printf ( “ \n elements of an array are”);

for ( i=0; i<n ; i++)

printf ( “%d” , a[i]);

Example programs
/* program to accept n integers and store them in an array and also print them */

void main()
{
int a[10], i ,n ;
printf(“\n enter the size of an array”);
scanf(“%d”,&n);
printf ( “ \n enter elements to an array”);
for ( i=0; i<n ; i++)
scanf ( “%d” , &a[i]);
printf ( “ \n elements of an array are”);
for ( i=0; i<n ; i++)
printf ( “%d” , a[i]);
}

Output: enter size of an array 5

Enter elements to an array 1 2 3 4 5

Elements of an array are 1 2 3 4 5

/* program to accept 2 integer arrays and find sum of the corresponding elements in the array
*/

void main()
{
int a[10],b[10,c[10, i ,n,sum[10] ;
printf(“\n enter the size of an array”);
scanf(“%d”,&n);
printf ( “ \n enter elements to the first array”);
for ( i=0; i<n ; i++)
scanf ( “%d” , &a[i]);
printf ( “ \n enter elements to the second array”);
for ( i=0; i<n ; i++)
scanf ( “%d” , &b[i]);

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 48 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
for(i=0 ; i<n ; i++ )
sum[i] = a[i] + b[i] ;
printf ( “ \n sum elements of an array are”);
for ( i=0; i<n ; i++)
printf ( “%d” , sum[i]);
}

Output: enter the size of an array 5

Enter the elements to the first array 1 2 3 4 5

Enter the elements to the second array 1 2 3 4 5

Sum elements are 2 4 6 8 10

Multi dimensional Arrays


Multi dimensional arrays can be consisting of more than one subscripts. This can be classified as 2
types. They are

 Two dimensional array

 Three dimensional array

Two dimensional array:

This array can be consisting of 2 subscripts.The simplest and most commonly used arrays are
2 dimensional arrays.

This array required row size and column size. The declaration of 2D array will be

Syntax:

Datatype arrayname [rowsize] [colsize] ;

Ex: int a [2][2] ;

Here total 4 elements stored in that array. (2X2=4)

Three dimensional array:

This array can be consisting of 3 subscripts. The declaration of 3D array will be

Syntax:

Datatype arrayname [size1] [size2] [size3];

Ex: int a [2] [2] [3] ;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 49 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
Here total 12 elements stored in that array. (2X2X3=12)

Initialization of 2D array
The list of values assigned to array elements in order.

Ex: int a[3][3] = {1,2,3,4,5,6,7,8,9} ;

a[0][0] = 1 a[1][0] = 4 a[2][0] = 7

a[0][1] = 2 a[1][1] = 5 a[2][1] = 8

a [0][2] = 3 a[1][2] = 6 a[2][2] = 9

Code for accept or read 2D-array elements:

printf ( “ \n enter elements to an array”);

for ( i=0; i<n ; i++)

for (j=0; j<n ; j++)

scanf ( “%d” , &a[i][j]);

Code for print or display 2D-array elements:

printf ( “ \n elements of an array are”);

for ( i=0; i<n ; i++)

for (j=0; j<n; j++)

printf ( “%d” , a[i][j]);

Lab program: /* program to find addition and subtraction of matrices */

void main()
{
int a[10][10], b[10][10],sum[10][10],sub[10][10],i, j ,n;
clrscr();
printf(“\n enter the order of matrix”);
scanf(“%d”,&n);
printf ( “ \n enter elements to the first array”);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
scanf ( “%d” , &a[i][j]);
printf ( “ \n enter elements to the second array”);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
scanf ( “%d” , &b[i][j]);

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 50 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
{
sum[i][j] = a[i][j] + b[i][j];
sub[i][j] = a[i][j] - b[i][j];
}
printf ( “ \n sum of elements of an array are”);
for ( i=0; i<n ; i++)
{
for (j=0; j<n; j++)
printf ( “%d” , sum[i][j]);
}
printf ( “ \n sub of elements of an array are”);
for ( i=0; i<n ; i++)
{
for (j=0; j<n; j++)
printf ( “%d” , sub[i][j]);
}
getch();
}
Multiplication of matrices
Suppose the order of 1 st matrix is mxn,

The order of 2nd matrix is pxq

The matrix multiplication is possible only, when the columns of 1 st matrix must be equals to the rows
of 2nd matrix.

m x n = p x q

equal

/* program to find matrix multiplication */

void main()
{
int a[10][10], b[10][10], mul[10][10], i, j ,k,n;
clrscr();
printf(“\n enter the order of matrix”);
scanf(“%d”,&n);
printf ( “ \n enter elements to the first array”);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
scanf ( “%d” , &a[i][j]);
printf ( “ \n enter elements to the second array”);
for ( i=0; i<n ; i++)

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 51 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
for (j=0; j<n ; j++)
scanf ( “%d” , &b[i][j]);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
{
mul[i][j]=0;
for(k=0;k<n;k++)
mul[i][j] = mul[i][j] + a[i][k] * b[k][j];
}
printf ( “ \n product matrix is”);
for ( i=0; i<n ; i++)
{
for (j=0; j<n; j++)
printf ( “%d” , mul[i][j]);
printf(“\n”);

}
getch();
}

Sorting
Definition:

Arranging the elements in any one of the order either ascending or descending order.

Bubble Sort:

Bubble sort is the most popular sorting technique. Because it is very simple to understand and
implement.

Condition:

If the 1st element is greater > second element then those two are swapped (interchanged).

Procedure:

 First compare 1st element with the 2nd element of an array. If 1 st element > 2nd element then
those two elements are swapped.

 Now compare 2nd element with 3rd element of an array. If 2nd element > 3rd element then
those two elements are swapped.

 Repeat this procedure up to all elements in an array.

 If number of elements n then number of passes will be n-1.

Code for sorting:

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 52 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
for ( i=0 ; i<n ; i++)
{
for (j=0; j<=n-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1]
a[j+1] = temp;
}
}
}
Ex:
28 20 30 15 05

a[0] a[1] a[2] a[3] a[4]

Pass 1: here 1st element is greater than 2 nd element then exchange of those 2 elements.

28 20 30 15 5

20 28 30 15 5

20 28 15 30 5

20 28 15 5 30

Pass 2:

20 28 15 5 30

20 15 28 5 30

20 15 5 28 30

Pass 3:

20 15 5 28 30

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 53 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

15 20 5 28 30

15 5 20 28 30

Pass 4:

15 5 20 28 30

5 15 20 28 30

Here total number of elements is 5, but number of passes will be (n-1) is 4.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 54 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

CHAPTER - 7
Strings
Definition:
String is a one dimensional array of characters. (or)
String is a collection of characters or sequence of characters to be enclosed into double quotes.
Example= “computer”
This string is stored in memory as shown below

c o m p u T e r \0

The very first character occupies 0th subscript place, the second character is stored at the 1st subscript
place and so on, the last character occupies the (n-1) th subscript. However an n-character array
contains (n+1) array elements.
The compiler automatically adds the terminating NULL character that is ‘\0’ at the end of the string.
This character is used to indicate end of the string. C language provides many string handling
functions which are defined in the header file <string.h>.

Declaration of String and initialization:


Like arrays strings must be declared before they are appear in a c program.

Syntax: data type string name [size] ;


Ex: char name [10] ;

Syntax: data type string name [size] = {“string”};


Ex: char name [10] = { “ vvfgc” }; (or)

char name [10] = { ‘v’, ‘v’, ‘f’, ‘g’, ‘c’, ‘\0’ };

Operations on strings
There are so many operations are in strings. They are

 Reading and writing the strings

 Concatenating strings

 Copying one string to another

 Comparison of two strings

 Extracting portion of a string

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 55 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Reading a string from terminal


Reading string from terminal using 3 ways. They are

 scanf ( ) function

 gets ( ) function

 getchar ( ) function

scanf ( ) function:
The function scanf with %s format specifier is needed to read the string from the terminal.

Syntax: scanf ( “ format specifiers” , string name) ;


In this & symbol is not required for reading variables. Because array itself allocates address for that it
cannot have & symbol.
Ex: suppose if we input “BANGALORE” ,then storage looks like

B A N G A L O R E \0
Ex: suppose if we input “NEW DELHI”, then storage looks like

N E W \0 ? ? ? ? ? ?

The function scanf ( ) has a drawback it just terminates as soon as it finds blank space.
In the above example scanf reads only new but not delhi because after the word new one blank space
is appeared. Then scanf understand the string will be ended.

Ex: /* program to read a string and print by using scanf() function */


void main()
{
char str[30];
printf(“\n enter a string”);
scanf(“%s”, str);
printf(“\n given string is %s”, str );

getch();
}

gets ( ) function:

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 56 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
this unformatted input function. Using this we can read one string at a time.
This is the most convenient method of reading a string . this is a library function and it is available in
the <stdio.h> header file.

Syntax: gets ( string );


It reads characters from the keyboard until a new line character is encountered and then appends a
null character to the string automatically.
Ex: char str[20] = { “this is vision”};
gets ( str );

output: this is vision


in the above example gets function reads the total string. This is the advantage of the gets () function.
But it cannot read more than one string at a time.

Ex: /* program to read a string and print by using gets () function */


void main()
{
char str[30];
printf(“\n enter a string”);

gets (str);
printf(“\n given string is %s”, str );
getch();
}

getchar ( ) function:
This function is unformatted input function. It read only one character at a time.

Ex:
void main()
{
char str[40], ch;
int i=0;
printf(“\n enter a string “);
do
{
ch=getchar( );
str[i]=ch;
i++;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 57 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
}while ( ch !=’\n’);
str[i-1]=’\0’;
printf(“\n the string is %s”, str );
}

Writing a string to screen


Writing string to screen using 3 ways. They are

 printf ( ) function

 puts ( ) function

 putchar ( ) function
printf ( ) function:
The function printf with %s format specifier is needed to print the string on the terminal.

Syntax: printf ( “ format specifiers” , string name) ;

puts ( ) function:
this unformatted output function. Using this we can print one string at a time.
This is the most convenient method of writing a string . this is a library function and it is available in
the <stdio.h> header file.

Syntax: puts ( string );


It prints characters on the terminal until a new line character is encountered and then appends a null
character to the string automatically.
Ex: char str[20] = { “this is vision”};
puts ( str );

output: this is vision


in the above example puts function prints the total string.

Ex: /* program to read a string and print by using puts () function */


void main()
{
char str[30];
printf(“\n enter a string”);

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 58 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
gets (str);
puts ( str );
getch();

putchar ( ) function:
This function is unformatted output function. It print only one character at a time. We can use
this function repeatedly to output a string of characters stored in an array using a loop.
Ex:

void main( )
{
char str[8]= {“skyward”};
int i=0;
for(i=0;i<7;i++)
putchar( str[i]);

putchar(“\n”);
}

Arithmetic Operations on characters


We can manipulate the characters as we manipulate numbers in C language. Whenever a system
encounters a character data it is automatically converted into a integer value by the system.
Ex: void main( )
{
char ch=’A’;
printf(“%c”,ch); it will display the character is A
printf(“%d”,ch); it will display ASCII code of the character
}

Ex2: void main()

{
char ch;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 59 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
ch=’b’- 1;
printf(“%c”,ch); It will prints ‘a’
printf(“%d”,ch); it prints 97

}
Ex3: void main()
{
int i=20;
i = i+’A’;
printf(“%d”, i); it prints 65
}

Converting string to a number: (using atoi () function)


To converting string to a number, there exits a library function atoi ( ), using we can convert
string to a number.
void main()

{
char str[5] = “12345”;
int num;
num = atoi (str);
printf(“number is %d\n”, num);
}

In the above, string is a character array which is assigned the string constant “12345”. The function
atoi converts the string “12345” to its numeric equivalent 12345 and assignes it to the integer
variable num.

Concatenating Operation (strcat( ) )


The process of putting strings together is known as Concatenation. (or)
The process of joining two strings into one string is known as concatenation. We are not directly
added two strings.

For this we use one string building function that is strcat ( ).

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 60 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Syntax: strcat ( string1, string2);


Here, the string2 is appended to string1.
Ex: strcat ( “program”, “ming”);

Output: programming
It will append the string “ming” to the end of the string “program”. By default the total string was
stored in first string.

Procedure:
1. read two strings as string1, string2.

2. Traverse the first string to its end.


3. Attach the second string to the end of first string.
4. Set the last character of the resultant string to a null charcater (\0).

/* program to concatenating two strings with using built-in function */


void main()
{

char str1[40],str2[40];
printf(“\n enter first string”);
gets(str1);
printf(“\n enter second string”);
gets(str2);
strcat(str1,str2);

printf(“concatenating of 2 strings is %s\n”,str1);


}

/* program to concatenating two strings without using built-in function */


void main()
{

char str1[40],str2[40];
int i=j=0;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 61 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
printf(“\n enter first string”);
gets(str1);
printf(“\n enter second string”);

gets(str2);
while( str[i] != ‘\0’)
i++;
while (str2[j] != ‘\0’)
{
str1[i]=str2[j];
i++;

j++;
}
str[i]=0;
printf(“ concatenating of 2 strings is %s\n”,str1);
}

Length of String (strlen( ))


This function returns the number of characters in given string. That is the string length. String length
does not include the null character (\0).

Syntax: strlen (string);


Where string is one dimensional array of characters.
Ex: strlen (“”programming”);

Output: length of the string will be 11.


Ex: strlen (“ india is great”);
Output: length of given string will be 14 with including spaces.

/*program to find length of string using built-in function */


void main()
{

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 62 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
int len;
char str[40];
while(1)

{
puts(“enter the string”);
gets(str);
len=strlen(str);
if(len!=0)
printf(“length of the string is %s\n”, len);
else

break;
}
return(0);
}

/*program to find length of string without using built-in function */


void main()

{
char str[40];
int i=0;
printf(“enter the string\n”);
gets(str);
while(str[i]!=’\0’)

i++;
printf(“length of given string is %s\n”,i);
}

Comparing two Strings(strcmp())


This function compares two strings character by character and returns one of the three values
{ -1, 0 , 1}.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 63 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Syntax: strcmp ( string1 , string2);


Where string1is one dimensional array of characters
String2 is also one dimensional array of characters

This function returns -1 , if the ASCII value of first string is less than that of second string.
This function returns 0 (zero), if both strings are equal.
This function returns 1, if the first string is greater than second string.

Procedure:

 Read 2 strings as string1, string2.

 Find the length of each string.

 Set the counter value to zero.

 Start comparing the first character of both strings and if they are equal then increment the
counter and continue for the next characters until corresponding characters till the end of the 2
strings.

/* program to compare 2 strings without using built-in function */


void main()
{

char str1[40],str2[40];
int i=j=0;
printf(“\n enter first string”);
gets(str1);
printf(“\n enter second string”);
gets(str2);

while( str[i] != ‘\0’)


i++;
while (str1[j] = str2[j] && str1[i] != ‘\0’)
{
i++;
j++;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 64 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
if(str1[i] = = str2[j] )
printf(“\n two strings are equal”);
else

printf(“\n strings are not equal”);


getch();
}

/* compare 2 strings using built-in function */


void main()
{
char str1[40],str2[40];

int i, j;
printf(“\n enter first string”);
gets(str1);
printf(“\n enter second string”);
gets(str2);
i= strcmp(str1,str2);

if (i = = 0)
printf(“strings are equal”);
else
printf(“\n not equl”);
getch();
}

Copying string to another string (strcpy ( ) function)


This function is used to copy one string to the other.

Syntax: strcpy ( string1, string2 )

/* program to copy string to another without using buit-in function */


void main()
{

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 65 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
char source[40], target[40];
printf(“\n enter first string”);
gets(source);

printf(“\n enter second string”);


gets(target);
while (source[i] != ‘\0’)
{
target[i] = source[i];
i++;
}

target[i] = ‘\0’ ;
printf(“ destination string is %s\n”,target);
}

/* program to copy string to another with using buit-in function */


void main()
{

char s[20], t[20];


printf(“ enter the source string\n”);
gets(s);
strcpy(t,s);
printf(“ target string is %s\n”, t);
getch();

Character Handling functions


To find whether a character is a number, lowercase letter, uppercase letter or blank space, we can also
use C-standerd library functions.
Some character handling functions are

function name Meaning


isdigit(char) character is digit

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 66 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

isalpha(char) character is alphabet


islower(char) character is lowercase letter
isupper(char) character is upper case letter
isalnum(char) character is alphanumeric character
isspace(char) character is white space

The above character functions are available in ctype.h header file.

/*program to check whther entered charcter is alphabet or digit or special symbol */


void main()
{
char ch;
clrscr();
printf("\n enter one character");
scanf("%c",&ch);
if(isalpha(ch))
printf("\n the character is alphabet");
else if(isdigit(ch))
printf("\n the character is digit");
else
printf("\n the character is special symbol");
getch();
}

1. /* program to find length of the given string without using library function */

void main()
{
char str[40];
int i=0;
clrscr();
printf("\n enter the string");
gets(str);
while(str[i]!='\0')
i++;
printf("\n the length of the string is %d",i);
getch();
}
Output:
Enter the string vision

Length of the string is 6.

2. /*program to read a string and check whether it is palindrome or not */

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 67 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
void main()
{
int i,len, flag=0;
char word[25];
clrscr();
printf(“\n enter the word”);
scanf(“%s”,word);
for(i=0;i<len;i++)
{
if(wprd[i] != word [- - len])
{
flag = 1;
break;
}
}
if(flag= =1)
printf(“\n the word is not a palindrome”);
else
printf(“\n the word is a palindrome”);
getch();
}
Output 1:
Enter the word madam
The word is palindrome.

Output 2:
Enter the word skyward
The word is not palindrome.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 68 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Chapter – 8

Functions (user defined )


Need for functions:

If the length of a program is too large, it is very difficult for the programmers to handle it.
Generally larger programs increases errors and it would be a complex job to locate and correct the
errors. Therefore, such programs should be broken down into a number of smaller logical
components.

The process of splitting the lenghy and complex programs into a number of smaller
units(components) is called modularization. Programming with such is called modular
programming.

Modularization has several advantages. Some of them are

 Reusability, if a perticular set of instructions are to be accessed repeatedly from several


different places with in the program. This is to avoid rewritting the function on every access.

 Debugging is easier, since each module is smaller and easier, the user can easily locate the
errors and correct them.

 Build library, it allows the programmer to build a library of most commonly used
subprograms. This reduce the time and space complexity.

Definition:

A Function is a set of instructions to carry out a perticular task.

There are 2 types of functions. They are

 Library functions (built-in)

 User defined function

Library functions:

Those are the functions which are already exist in the computer is known as library functions.

For example printf() and scanf() these are the functions available in <stdio.h> header file.

Sin(), cos() etc mathematical functions are available in <math.h> header file.

Strcpy(), strlen() etc functions are available in <string.h> header file.

User defined functions:

These are the functions created by the users.


MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 69 VVFGC,TUMKUR.
C-Programming 1st Sem BCA

Function call:

Function call is to be present inside the main function. This is also known as calling function.
This function call consists of name along with the arguments. Those arguments are called as “actual
arguments”.

Syntax: functionname ( list of actual arguments);

Ex: main( )

int x=10, y=20;

sum(x,y);

Function Prototype:

To avoid confusion and complexity in data transfer between called function and calling
function, we use this prototype. Always this can be placed before main() function.

In some situations definition is placed before main function, then no need to write prototype.

Function name of the function call and prototype are the same and arguments must match.
Prototype consisting of datatypes corresponding function call arguments.

Syntax: returntype functionname (list of formal parameters datatypes) ;

Ex: int sum (int, int) ;

Function Definition:

The actual code of the function written in this function definition. This is the header of the
function.

There should be match with name of the function, list of formal parameters in prtotype and definition.

Prototype terminated by semicolon but definition has not require semicolon.

Syntax: return type function name ( type1 data1, type2 data2 …. type n data n)

Body of the function

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 70 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
Where return type is the any datatype available

Functionanme is the name of the function

Type is the datatype of argument

Data is the formal arguments.

Ex:

int sum(int, int) ; Function prototype


void main()
{
int a=1,b=2,c ;

clrscr();
c=Sum (a, b); Function call (calling function)
printf (“sum of 2 numbers is %d\n”,c); a,b are actual arguments
getch();
}
int sum (int x, int y) Function definition (called function)

{ x,y are formal arguments


int z;
z=x+y;
return (z);
}

Categories of Functions
Based on the arguments and return values functions are classified 4 types. They are

 Function without arguments and without return value.

 Function with arguments and with return value.

 Function with arguments and without return value.

 Function without arguments and with return value.


Function without arguments and without return value.:

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 71 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
In this case function call does not send any arguments to called function and called function
does not send any return value to calling function. Hence there is no data transfer between the calling
function and the called function.
Syntax: function prototype( );
void main()
{
function call ( );
}
function definition( )
{
statements;
}
Ex: void sum( );
void main()
{
int a,b,c;
printf(“enter 2 numbers”);
scanf(“%d%d”,&a,&b);
c=sum( );
getch();
}
void sum( )
{
int x=10, y=20,z;
z=x+y;
printf(“sum is %d\n”,z);
}

Function with arguments and with return value.: In this case function call send arguments to
called function and called function sends return value to calling function. Hence there is data transfer
between the calling function and the called function.
Syntax: function prototype(arguments as datatypes );
void main()
{
function call ( actual arguments);
}
function definition( formal arguments )
{
statements;
return;
}
Ex: int sum( int, int );
void main()
{

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 72 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
int a,b,c;
printf(“enter 2 numbers”);
scanf(“%d%d”,&a,&b);
c=sum(a,b );
printf(“sum is %d”,c);
getch();
}
int sum(int x, int y )
{
int z;
z=x+y;
return(z);
}

Function with arguments and without return value.:


In this case function call send arguments to called function but called function does not sends
return value to calling function. Hence there is data transfer between the calling function and the
called function in one way only.
Syntax: function prototype(arguments as datatypes );
void main()
{
function call ( actual arguments);
}
function definition( formal arguments )
{
statements;
}

Ex: void sum( int, int );


void main()
{
int a,b,c;
printf(“enter 2 numbers”);
scanf(“%d%d”,&a,&b);
c=sum(a,b );
getch();
}
void sum(int x, int y )
{
int z;
z=x+y;
printf(“sum is %d”,z);
}
Function without arguments and with return value.:

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 73 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
In this case function call does not send any arguments to called function but called function
send return value to calling function. Hence there is data transfer between the calling function and
the called function in one way only.
Syntax: function prototype( );
void main()
{
function call ( );
}
function definition( )
{
statements;
return;
}
Ex: int sum( );
void main()
{
int a,b,c;
printf(“enter 2 numbers”);
scanf(“%d%d”,&a,&b);
c=sum( );
printf(“sum is %d”,c);
getch();
}
int sum( )
{
int x=10, y=20,z;
z=x+y;
return(z);
}
Types of Arguments
There are basically 2 types arguments. They are

 Actual arguments (or) parameters

 Formal arguments (or) parameters

Actual arguments:
The arguments associated with a function call is referred as actual arguments. These
arguments are sent from calling function to called function.
Ex: void main()
{
int x=10,y=20;
sum (x,y); here x and y are actual arguments.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 74 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
}

Formal arguments:
The arguments associated with a function definition are referred as formal arguments. These
arguments are receiving arguments from calling function.
Ex: void sum(int x, int y) these are formal arguments.
{
int z;
z=x+y;

return(z);
}

Passing parameters to called function


The arguments present in the function call is actual arguments. These arguments passed two
ways to called function. They are

 Call by value

 Call by reference

Call by value:

When the values of the arguments are passed from a calling function to a called function, the
values are copied into the called function. If any changes are made to the values in the called
function, those changes are not effect to the calling function.

Ex: /* program to swap 2 numbers using call by value */

void swap(int,int);

void main()

Int a=10,b=20;

Swap(a,b);

Printf(“after swap”);

Printf(“the value of a is %d\n”,a);

Printf(“the vlaue of b is %d\n”,b);

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 75 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
}

Void swap(int x, int y)

int temp;

temp=x;

x=y;

y=temp;

Call by reference:

In this method, the actual values are not passed, instead of their addresses are passed to a
calling function. Here no values are copied as the memory locations themselves are refernced. If any
modification is made to the values in the called function, those changes will effect to the calling
function.(original values)

Ex: /* program to swap 2 numbers using call by reference */

void swap(int *, int *);

void main()

int a=10,b=20;

Swap(&a, &b);

Printf(“after swap”);

Printf(“the value of a is %d\n”,a);

Printf(“the value of b is %d\n”,b);

void swap(int *x, int *y)

int temp;

temp=*x;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 76 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
*x = *y;

*y=temp;

Output:

The value of a is 20

Value of b is 10

Recursion
“It is a process of calling a function repeatedly by itself is known as recursion.”

It is a powerful programming tool, it allows to execute the function repeatedly itself.

Advantages:

 It reduces the complexity of program.

 It allows user to write much simpler programs.

 It is top down approach.

1. /*program to find factorial of a number using recursion */

long factorial(long);
void main()
{
long num;
clrscr();
printf("\n enter the number");
scanf("%ld",&num);
ans=fact(num);
printf("\n factorial of %ld is %ld",ans);
getch();
}
long factorial(long n)
{
if(n==0)
return (1);
else
return (n*fact(n-1));
}

2. /* program to generate Fibonacci series upto given limit */


int fib(int);

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 77 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
void main()
{
int n,I;
printf(“\n enter number of terms”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“%d”,fib(i));
}
printf(“elements are %d\n”,I,fib(i));
getch();
}
int fib(int k)
{
if(k = = 0)
return 0;
else if (k==1 || k==2)
return 1;
else
return (fib(k-1)+fib(k-2));
}

Comparison between recursion and iteration

Recursion iteration

1. This is the top down approach. 1. This is bottom up approach.

2. This is natural method. 2. This is a non natural method.

3. Program is smaller length of code. 3. Program having larger length of code.

Storage Classes
We define one variable needs to mention its data type. But mentioning data type is not sufficient it
also requires storage class.

All variables not only have the data types but also having storage class.

Advantages:

 Where the variable should be stored.

 What is the initial value of the variable, if value is not initialized?

 How long the variable exists.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 78 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Syntax: <storage class> data type <variable name> ;

The storage classes are can be classified into 4 types. They are

 Auto

 Static

 Extern

 Register

Auto:

It is the default storage class for all local variables. The keyword auto is derived from
automatic.

Declaration: auto int a; it is similarly to int a;

auto char ch; char ch;

Here auto key word is optional.

Ex: void main()


{
increment();
increment();
increment();
}
void increment( )
{ 2
auto int i=2; 2
printf(“%d”,i); 2
i=i+2;
}
In the above example variable I is declared as auto. Each time increment function is called. When the
function execution is over variable I vanishes and its new value is lost. Next time when the same
function was called I is initialized to 2. So that output will be 2 2 2

Static:

The variables which are declared as static are referred to the static variables. Unlike the auto,
the memory allocated for static variables will not be destroyed when the control goes out of the
function. So that the current value of the variable is available for the next time.

If the static variables are not initialized that time the default value will be zero.

Declaration: static int i;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 79 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
static char ch;

static double f;

Ex: void main()


{
increment();
increment();
increment();
}
void increment( )
{ 2
auto int i=2; 4
printf(“%d”,i); 6
i=i+2;
}
Extern:

The variables are called external variables because they are declared or defined outside of the
function like after the main( ). So that these variables are also called as global variables.

By default these variables are initialized as zero.

Ex: void main()


{
increment();
decrement();
}
void increment( )
{
i=i+5; 5
printf(“ I is %d”,i); 3
}

void decrement( )
{
i=i-2;
printf(“\n I is %d”,i);
}
Register:

The variables which are declared as register are referred as register variables. These are as
same as the automatic variables.

The storage class is applicable only to local variables.

Ex: register int a;

Register char ch;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 80 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Chapter- 9

Structures and Union


Need for Structures:

An array is stored a group of homogeneous elements. This is not suitable to store different or
dissimilar data elements, but most of the real world applications need a group of heterogeneous
elements. In such situations we need one special data structure that is “structures”.

Definition:

“it is a meaning full collection of data items of different data types, but it collects all elements
under an unique name”.

Declaration:

Each and every structure must be defined an declared before it appears in a C-program.

Syntax:

struct structurename

{
type1 data1;
type2 data2;
:
type n data n
};
In the above syntax struct is a key word.
Structurename is a name of the structure. It is also known as tagname.
Type1, type2 …. Type n are the basic data types.
Data1, data2 ----data n are the members or fields of the structures.
{ it indicates sarting of the structure.
} it indicates end of the structure.

The body of the structure is terminated by a semicolon.

Ex: struct student

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 81 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
{
int rollno;
float fee;

char sname[20];
};

Declaration of variables:
Like ordinary variables, we can also define and declare structure variables.

Syntax:
Structurestype varlist;
Where structuretype is type of a structure it takes the keyword struct followed by the name of the
structure.
Variable list is the one or more variables seperated by comma (,).

Declaration of varibles inside the structure:

Syntax: ex:
struct structurename struct employee
{ {
type1 data1; int eid;
type2 data2; char ename[20];
: int sal;

type n data n }e1,e2 ;


}var1,var2….var n ;

Declaration of varibles outside the structure:


In this case we are declare variables outside the structure. Now we are using struct keyword
along with varibles.

Syntax: ex:
struct structurename struct employee

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 82 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
{ {
type1 data1; int eid;
type2 data2; char ename[20];

: int sal;
type n data n };
}; struct employee e1, e2 ;
Struct structurename varlist;

Accessing structure members through variables


The link between members and a variables is established by using member operator or period
operator that is dot operator.

Syntax:
Structurevariable . structuremember
Dot operator
Ex:
struct student
{

int rollno;
float fee;
char sname[20];
}s1,s2 ;
We are accessing rollno through first student.
s1. rollno

/*program to define and assign and access the members of the structure */
void main()
{
struct emp
{
char ename[20];
int eno;
float sal;
};
struct emp e1, e2;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 83 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
e1.ename= “vvfgc”;
e2.eno=500;
e2.sal=10000;
printf(“ ename of e1 is %s\n”, e1.ename);
printf(“ eno of e1 is %d\n”, e1.eno);
printf(“ esal of e2 is %f\n”, e2.sal);
getch();
}

Initialization of a structure
Assigning members to a structure at the time of declaration itself. “but C does not permit initalization
of individual structure members with in the templet [with in the braces ]”.

Syntax:

Static struct structurename variable= {value1,vlaue2 ….. value n};

There are 2 types of initialization in the structure.

Initialization inside the structure:

Whenever the structure is initialized inside a function, it must be declared as “static”.

Ex:

Void main()
{
Struct student
{
Int age;
Float weight;
Char name[20];
};
static struct student stu1= { 20,55.4, “ramu”};
static struct student stu2= { 30,55.4, “raju”};
}

Initialization outside the structure:

Whenever the structure is initialized outside a function, there is no need to declared as


“static”.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 84 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
Ex: struct student

{
int age;
float weight;
char name[20];
};
struct student stu1= { 20,55.4, “ramu”};
struct student stu2= { 30,55.4, “raju”};
Void main()
{
Statements;
}

Nested structures
This is also known as structure with in the structure or embedded structure.

“ A structure that contain other structure as a member or as a structure itself is known as embedded
structure”.

It can be written in 2 ways. They are

1. A structure may completely with in the another structure.

2. There may be separate structures. The embedded structure is declared first and the outer
structure declared next.

Syntax first way: ex:

Struct structurename(outer) struct emp


{ {
Members of outer structure; int eid;
Struct structurename(embedded) char ename[20];
{ struct date
Members of inner structure; {
}; int dd,mm;
}; int yyyy;
}dob;

}e1,e2;
Syntax of second way: ex:

Struct embedded structurename struct date

{ {

Members of structure; int dd,mm,yyyy;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 85 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
}; }dob;

Struct outer structurename struct emp

{ {

Members of structure; int eid;

}; char name[20];

}e1,e2;

/* program to accept goods and display them by using nested structures */

struct item
{
int itemno;
char iname[30];
struct pdate
{
int dd;
int mm;
int yyyy;
}date;
};
struct item items[20];
void main()
{
int i,n;
clrscr();
printf("\n enter the number of goods:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n enter item %d details",i+1);
printf("\n enter item number");
scanf("%d",&items[i].itemno);
printf("\n enter item name:");
scanf("%s",&items[i].iname);
printf("\n enter purchase date:");
scanf("%d%d%d",&items[i].date.dd,&items[i].date.mm,&items[i].date.yyyy);
}
printf("\n details of the items are:");
printf("\n*****************************");
printf("\nitemno\t\tiname\t\tpdate");
for(i=0;i<n;i++)
printf("\n%d\t\t%s\t\t%d-%d-
%d",items[i].itemno,items[i].iname,items[i].date.dd,items[i].date.mm,items[i].date.yyyy);
getch();

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 86 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
}

Union

“It is a collection of heterogenoeus elements of different data types. This is similar to the
structures”.

The main difference between the structures and union is in structure each member is assigned its own
memory location due to this some times memory will be wasted. But in union all members are share
common memory location due to this saves memory.

Declaration:

Like structure Each and every union must be defined an declared before it appears in a C-
program.

Syntax:

union unionname
{

type1 data1;
type2 data2;
:
type n data n
};
In the above syntax union is a key word.

unionname is a name of the union. It is also known as tagname.


Type1, type2 …. Type n are the basic data types.
Data1, data2 ----data n are the members or fields of the union.
{ it indicates sarting of the union.
} it indicates end of the union.
The body of the union is terminated by a semicolon.
Ex: union student

{
int rollno;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 87 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
float fee;
char sname[20];
};

Declaration of variables:
Like ordinary variables, we can also define and declare union variables.

Syntax:
uniontype varlist;
Where uniontype is type of a union it takes the keyword union followed by the name of the union.
Variable list is the one or more variables seperated by comma (,).

Declaration of varibles inside the union:


Syntax: ex:
union unionname union employee
{ {
type1 data1; int eid;
type2 data2; char ename[20];

: int sal;
type n data n }e1,e2 ;
}var1,var2….var n ;

Declaration of varibles outside the union:


In this case we are declare variables outside the union. Now we are using union keyword
along with varibles.

Syntax: ex:
union unionname union employee

{ {
type1 data1; int eid;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 88 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
type2 data2; char ename[20];
: int sal;
type n data n };

}; union employee e1, e2 ;


union unionname varlist;

Accessing union members through variables


The link between members and a variables is established by using member operator or period
operator that is dot operator and also -> arrow operator this is known as this operator.
Syntax:

unionvariable . unionmember
Dot operator
Ex:
union student
{
int rollno;
float fee;

char sname[20];
}s1,s2 ;
We are accessing rollno through first student.
s1. rollno or s1->rollno

/*program to define and assign and access the members of the union */
void main()
{
union emp
{
char ename[20];
int eno;
float sal;
};
union emp e1, e2;
e1.ename= “vvfgc”;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 89 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
e2.eno=500;
e2.sal=10000;
printf(“ ename of e1 is %s\n”, e1.ename);
printf(“ eno of e1 is %d\n”, e1.eno);
printf(“ esal of e2 is %f\n”, e2.sal);
getch();
}
Type def
The keyword typedef allows the users to define a newname or an identifier that would represent an
existing datatype. Once the identifier is defined for existing data type, it can be used later to delare the
varibles.

Syntax:

typedef existingdatatype newdatatype

ex:

typedef int salary;

in the above declaration, slary is an identifier, which is another name for int. what ever the values we
are representing int datatype those are used salary type.

enum
The keyword enum allows the user to define new enumerated user defined type. This user defined
data type is an identifier which can be used to declare variables that can have one of the values
enclosed with in the curly braces.

Syntax: enum identifier { c1,c2,c3 …. Cn };

here c1,c2…cn are the enumerated constants.

Ex: enum month { jan, feb,mar…..dec};

The compiler assigns integer values beginning with 0 to all the enumeration constants. That is jan is
assigned as 0

Feb is assigned as 1 like so on.

Ex:

enum month{jan,feb,mar=6,apr,may=9,jun,jul---dec};

Here by default jan is assigned with 0, feb is assigned with 1 but april is assigned with 7 because
march is assigned with 6 after 6 came ita s 7 like so on.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 90 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

Chapter- 10

Pointers
A pointer is a powerful construct of the C programming language.

Definition:

“A pointer is a variable which holds the address of other variables such as arrays, structures
and functions that are used in program.”

Advantages:

 Manipulation of data at different memory locations is easier.

 To achieve clarity and simplicity.

 More compact and efficient coding.

 Dynamic memory allocation.

Operators used with pointers:

There are 2 basic operators used with pointers. They are

 The address operator (&) : it gives the adress of a variable.

 The indirection operator (*) : it gives the value of the variable that the pointer is pointing to.

Pointer declaration:

Like ordinary variables, pointer variables that appear in a C program must be declared.

address data
dereferencing
1000 100
1001
1002
Referencing
1003 640


2000

There are 2 integer quantities, 100 and 640 which are stored at the memory locations 1000 and 1003
respectively. Let us assign 100 to x and 640 to y.

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 91 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
Now x = 100

y = 200

in order to access the value of a variable x via a pointer, we must need a pointer variable. Assume that
the variable be px. Also, consider another variable py, which points to the address of y.

The following statement assigns the address of x to px

px= &x

= 1000

Similarly, py=&y

= 1003

Thus x,y,px, py are declared in the program as,

int x, y, *px, *py ;

here x and y are 2 integer variables. We are declaring one pointer variable by using this syntax

datatype *pointervariable ;

/* program to find the size of pointer */

void main()

{
int *iptr;
char *cpter;
int s1,s2;
s1 = sizeof (iptr);
s2 = sizeof (cptr);
printf(“size of iptr is %d\n”, s1);

printf(“size of cptr is %d\n”,s2);


}

Pointer Dereferencing
This is a process of referencing the contents of the variables using pointers, indirectly.

Steps involved in dereferencing:

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 92 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

 Address of a variable, whose value is to be referenced is assigned to a pointer.

 Then, this pointer points to the value.

1000
ptr to int 1004
1001
1002
1003
num 1004 400
"
"
2000
in the above figure, the variable num designates the memory location 1004 and the pointer variable
ptr-to-int designates the memory location 1000.

Operations on pointers
A pointer variable holds the address of the other variable. This address can be incremented or
decremented. But the multiplication and division operations cannot be performed on the addresses.
This means that the pointer variables cannot be multiplied or divided. Operations that can be
performed on pointers as given below.

Assignment:
 A pointer variable can be assigned the address of the other variable.

Ex: int *ptr, var;

ptr = &var;

 if 2 pointer variables are pointing to the object of the same data type, then they can be
assigned.

Ex: int *ptr1, *ptr2;

ptr1 = ptr2;

 a pointer variable can be assigned a NULL value (NULL = 0)

Ex: int *ptr;

ptr = NULL;

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 93 VVFGC,TUMKUR.


C-Programming 1st Sem BCA

addition and subtraction:


 an integer value can be added to and subtracted from a pointer variable.

Ex: int *ptrx;

Ptrx = ptrx + 2;

Ptrx = ptrx – 1;

 One pointer variable can be subtracted from another pointer variable, if both are pointing to
the elements of the same array.

Ex: int x[4] = {10,20,30,40 };

int *ptr1, *ptr2, *ptr3, *ptr4;

ptr1 = &x[1];

ptr2 = &x[3];

ptr3 = ptr1 – ptr2;

Comparison:
If two pointer variables are pointing to the objects of same datatype, then they can be
compared with one another.

Ex: int *ptr1,*ptr;

Then, ptr1 == ptr2

ptr1 > ptr2

ptr1 < ptr2

ptr1 != ptr2 etc operations can be performed.

/* program to illustrate operations on pointer variable */

void main()
{

int *ptr;
int x[4] = {10,20,30,40 };
ptr= &x[0];

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 94 VVFGC,TUMKUR.


C-Programming 1st Sem BCA
printf(“address of x[0] is %d\n”,ptr);
printf(“value of x[0] is 5D”,*PTR);
ptr = ptr + 2;

printf(“ value of ptr is %d\n”, ptr);


printf(“value pointed to by ptr is %d\n”,*ptr);
}

MADHUPRIYA MCA.,M.Phil.,M.Tech.,(Ph.D.) 95 VVFGC,TUMKUR.

You might also like