0% found this document useful (0 votes)
3 views143 pages

Data Representation and Flowcharts Guide

The document provides an overview of data representation, including various number systems (binary, octal, decimal, and hexadecimal) and flowcharting as a method for illustrating algorithms and processes. It discusses the advantages and disadvantages of flowcharts, problem analysis, algorithm development, program coding, and debugging. Additionally, it introduces decision trees, pseudocode, and the characteristics of algorithms, along with a brief history of the C programming language.

Uploaded by

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

Data Representation and Flowcharts Guide

The document provides an overview of data representation, including various number systems (binary, octal, decimal, and hexadecimal) and flowcharting as a method for illustrating algorithms and processes. It discusses the advantages and disadvantages of flowcharts, problem analysis, algorithm development, program coding, and debugging. Additionally, it introduces decision trees, pseudocode, and the characteristics of algorithms, along with a brief history of the C programming language.

Uploaded by

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

UNIT –I

1
 Data Representation

•Data refers to the symbols that represent people, events, things, and ideas. Data
can be a name, a number, the colors in a photograph, or the notes in a musical
composition.

•Data Representation refers to the form in which data is stored, processed, and
transmitted.

Number systems are the technique to represent numbers in the computer


systemarchitecture, every value that you are saving or getting into/from
computer memory has a defined number system.

Computer architecture supports following number systems.

Binary number system


Octal number system
Decimal number system
Hexadecimal (hex) number system

1) Binary Number System

A Binary number system has only two digits that are 0 and 1. Every number
(value) represents with 0 and 1 in this number system. The base of binary
numbersystem is 2, because it has only two digits.

2
2) Octal number system

Octal number system has only eight (8) digits from 0 to 7. Every number (value)
represents with 0,1,2,3,4,5,6 and 7 in this number system. The base of octal
number system is 8, because it has only 8 digits.

3) Decimal number system


Decimal number system has only ten (10) digits from 0 to 9. Every number (value)
represents with 0,1,2,3,4,5,6, 7,8 and 9 in this number system. The base of
decimalnumber system is 10, because it has only 10 digits.

4) Hexadecimal number system

A Hexadecimal number system has sixteen (16) alphanumeric values from 0 to 9


3
and A to F. Every number (value) represents with 0,1,2,3,4,5,6, 7,8,9,A,B,C,D,E
and F in this number system. The base of hexadecimal number system is 16,
because it has 16 alphanumeric values. Here A is 10, B is 11, C is 12, D is 13, E is
14 and F is 15.

 Flowchart

A flowchart is a type of diagram that represents a workflow or process. A


flowchart can also be defined as a diagrammatic representation of an algorithm,
astep-by-step approach to solving a task.

The flowchart shows the steps as boxes of various kinds, and their order by
connecting the boxes with arrows. This diagrammatic representation illustrates a
solution model to a given problem. Flowcharts are used in analyzing, designing,
documenting or managing a process or program in various fields.

ANSI/ISO
Name Description
Shape

Shows the process's order of operation. A line


Flow line coming from one symbol and pointing at another.
(Arrowhead) Arrowheads are added if the flow is not the
standard top-to-bottom, left-to right.

4
Indicates the beginning and ending of a program or
sub-process. They usually contain the word "Start"
Terminal
or "End", or another phrase signaling the start or
end of a process, such as "submit inquiry" or

"receive product".

Represents a set of operations that changes value,


Process form, or location of data. Represented as a
rectangle.

Shows a conditional operation that determines


which one of the two paths the program will take.
Decision The operation is commonly a yes/no question or
true/false test. Represented as a diamond
(rhombus).

Indicates the process of inputting and outputting


Input/output data, as in entering data or displaying results.
Represented as a parallelogram.

Pairs of labeled connectors replace long or


On-page
confusing lines on a flowchart page. Represented by
Connector
a small circle with a letter inside.

Flow Chart Add Two number

5
Flow Chart compare two number

Advantages of using Flowcharts


Communication: - Flowcharts are a better way of communicating the logic
of a system to all concerned.
Effective analysis:- With the help of flowcharts, problems can be analyzed
more effectively.
Proper documentation:-Program flowcharts serve as a good program
documentation needed for various purposes.
Efficient coding:- Flowcharts act as a guide or blueprints during the
systems analysis and program development phase.
Proper debugging:- Flowcharts help in the debugging process.
Efficient program maintenance:- The maintenance of an operating
program becomes easy with the help of a flowchart.

Disadvantages of using flowcharts

Complex logic: - Sometimes , the program logic is quite complicated . In


such a case a flowcharts become complex.

6
Alterations and modification: - If alterations are required the flowcharts
may need to be redrawn completely.
Reproduction: - Since the flowcharts symbols cannot be typed in, the
reproduction of flowcharts become a problem.
The essentials of what has to be done can easily be lost in the
technicaldetails of how it is to be done.

 Problem Analysis

1. Problem Analysis: Identify the issues. Be clear about what the


problem is. ...

Understand everyone's interests. ...

List the possible solutions (options) ...

Evaluate the options.


7
Select an option or options. ...

Document the agreement(s). ...

Agree on contingencies, monitoring, and evaluation.


2. Algorithm Development

An algorithm in general is a sequence of steps to solve a particular


problem. Algorithms are universal. The algorithm you use in C
programming language is also the same algorithm you use in every
other language. An algorithm produces the same output information
given the same input information, and several short algorithms can be
combined to perform complex tasks such as writing a computer
program.

3. Flow Chart

A flowchart is a formalized graphic representation of a logic


sequence, work or manufacturing process, organization chart, or
similar formalized structure. The purpose of a flow chart is to
providepeople with a common language or reference point when
dealing with a project or process. Flowcharts use simple geometric
symbols and arrows to define relationships.

4. Program Coding

A Programming (or coding) language is a set of syntax rules that


define how code should be written and formatted. Thousands of
different programming languages make it possible for us to
createcomputer software, apps and websites.

5. Compile and Execution

Compilation

First, the source ‘.java’ file is passed through the compiler, which
thenencodes the source code into a machine independent encoding,
8
knownas Bytecode. The content of each class contained in the source
file is stored in a separate ‘.class’ file. While converting the source
code intothe bytecode.

Execution

The class files generated by the compiler are independent of the


machine or the OS, which allows them to be run on any system. To
run,the main class file (the class that contains the method main) is
passed to the JVM, and then goes through three main stages before
the finalmachine code is executed.

6. Debugging and testing

Testing means verifying correct behavior. Testing can be done at all


stages of module development: requirements analysis, interface
design, algorithm design, implementation, and integration with
othermodules. In the following, attention will be directed at
implementation testing. Implementation testing is not restricted to
execution testing. An implementation can also be tested using
correctness proofs, code tracing, and peer reviews, as described
below.
Debugging is a cyclic activity involving execution testing and code
correction. The testing that is done during debugging has a different
aim than final module testing. Final module testing aims to
demonstrate correctness, whereas testing during debugging is
primarily aimed at locating errors. This difference has a significant
effect on the choice of testing strategies.

7. Documentation
The documentation section contains a set of comment including the
name of the program other necessary details. Comments are
ignoredby compiler and are used to provide documentation to
people who reads that code.
 Decision tree

A decision tree is a decision support tool that uses a tree-like model of


decisionsand their possible consequences, including chance event outcomes,

9
resource costs, and utility. It is one way to display an algorithm that only
contains conditional control statements.
Decision trees are commonly used in operations research, specifically in decision
analysis, to help identify a strategy most likely to reach a goal, but are also a
popular tool in machine learning.

Decision tree algorithm falls under the category of supervised learning.


Theycan be used to solve both regression and classification problems.
Decision tree uses the tree representation to solve the problem in which
eachleaf node corresponds to a class label and attributes are represented
on the internal node of the tree.
We can represent any Boolean function on discrete attributes using
thedecision tree.

10
Below are some assumptions that we made while using decision tree:

At the beginning, we consider the whole training set as the root.


Feature values are preferred to be categorical. If the values are
continuousthen they are discredited prior to building the model.
On the basis of attribute values records are distributed recursively.
We use statistical methods for ordering attributes as root or the
internalnode.

As you can see from the above image that Decision Tree works on the Sum
of Product form which is also known as Disjunctive Normal Form. In the
above image, we are predicting the use of computer in the daily life of the
people.

In Decision Tree the major challenge is to identification of the attribute for the root
node in each level. This process is known as attribute selection.

 Pseudo code

Pseudocode is an informal way of programming description that does not


require any strict programming language syntax or underlying technology
[Link] is used for creating an outline or a rough draft of a program.
Pseudocode summarizes a program’s flow, but excludes underlying details.
System designers write pseudocode to ensure that programmers understand a
software project's requirements and align code accordingly.
Advantages of pseudocode –

• Pseudocode is understood by the programmers of all types.

• It enables the programmer to concentrate only on the algorithm part of the


codedevelopment.

• It cannot be compiled into an executable program. Example, Java code : if (i <


10) { i++; } pseudocode :if i is less than 10, increment i by 1.
11
Let's review an example of pseudocode to create a program to add 2 numbers
together and then display the result.

Start Program
Enter two number A,B
Add the number
togetherPrint add
End program

Compare that pseudocode to an example of a flowchart to add two numbers

Now, let's look at a few more simple examples of pseudo code. Here is
apseudocode to compute the area of a rectangle:

Get the length, l, and width,


wCompute the area = l*w
Display the area

Now, let's look at an example of pseudocode to compute the perimeter of


arectangle:
12
Enter length, l
Enter width, w
Compute Perimeter = 2*l + 2*w
Display Perimeter of a rectangle Remember, writing basic pseudocode is not
likewriting an actual coding language. It cannot be compiled or run like a
regular program. Pseudocode can be written how you want. But some
companies use specific pseudocode syntax to keep everyone in the company on
the same page. Syntax is a set of rules on how to use and organize statements
in a programminglanguage. By adhering to specific syntax, everyone in the
company can read and understand the flow of a program. This becomes cost
effective and there is less time spent finding and correcting errors.

Advantages of Pseudocode

1. Pseudocode uses English like statements. Therefore, it can be written


easilyand quickly.
2. In pseudocode, each step is independent of other steps. Therefore, if any
modification is done in any step, it does not affect the codes of other
module
i.e. the code has not to be rewritten if any change occurs in any other step.
3. The format of pseudocode is similar to that of the programs. Both
pseudocode and program consist a set of sequential statements and use
defined set of keywords. Therefore, pseudocode and be converted to a
full-fledged program using any programming language.
4. The learning curve of pseudocode is very smooth. Since, it is written in
highly simple language and thus can be understood by any naïve user
also.

Disadvantages of Pseudocode
1. Pseudocode is textual representation of an algorithm. It does not
providegraphical representation. Therefore, sometimes, it becomes
difficult to understand the complex logic written in pseudocode.
2. When too many nested conditions are used in the pseudocode, the level
ofdifficulty to understand the code increases.
3. Since pseudocode focus on detailed description, a lot of practice
andconcentration is required.
13
 Algorithm in Programming

In programming, algorithm is a set of well defined instructions in sequence to


solve the problem. An algorithm is defined as a step-by-step procedure or
method for solving a problem by a computer in a finite number of steps. Steps of
an algorithm definition may include branching or repetition depending upon
what problem the algorithm is being developed for. While defining an algorithm
steps are written in human understandable language and independent of any
programming language. We can implement it in any programming language of
ourchoice.

Qualities of a good algorithm

1. Input and output should be defined precisely.


2. Each steps in algorithm should be clear and unambiguous.
3. Algorithm should be most effective among many different ways to solve
aproblem.
4. An algorithm shouldn't have computer code. Instead, the algorithm
shouldbe written in such a way that, it can be used in similar
programming languages.

Write an algorithm to add two numbers entered by user.

Step 1: Start
Step 2: Declare variables num1, num2 and
[Link] 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

Write an algorithm to find the largest among three different numbers


entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
14
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Advantages of Algorithms:

1. It is a step-wise representation of a solution to a given problem,


whichmakes it easy to understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to
understandfor anyone even without programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to
debug.
5. By using algorithm, the problem is broken down into smaller pieces or
stepshence, it is easier for programmer to convert it into an actual
program.

Disadvantages of Algorithms:

1. Algorithms is Time consuming.


2. Difficult to show Branching and Looping in Algorithms.
3. Big tasks are difficult to put in Algorithms.

Characteristics of Algorithms:

1. Precision – the steps are precisely stated(defined).


2. Uniqueness – results of each step are uniquely defined and only depend
onthe input and the result of the preceding steps.
3. Finiteness – the algorithm stops after a finite number of instructions
areexecuted.
4. Input – the algorithm receives input.
5. Output – the algorithm produces output.
6. Generality – the algorithm applies to a set of inputs.
15
 Introduction to C

C is a programming language that has been developed and designed by Dennis


Ritchie in 1970’s at AT & T’s Bell laboratories of USA. It was originally written
under UNIX operating system which itself was rewritten later in C language. C
seems to be so popular because it is reliable, simple, easy to use and potable.
Programs written in C language are fast and very efficient than its predecessors.
Sobefore starting C language , user must have an idea of its historical
development .

Historical development of C

By 1960’s many computer language exist but each has been developed for a
specific purpose. Eg. COBOL for business and commercial applications, FORTRAN
for engineering and scientific purposes etc.

The C language derives its name from the fact that it is based on a language
developed by ken Thompson, another programmer at Bell laboratories . He
adapted it from a language known as basic combined programming
language(BCPL). To distinguish his version of language from BCPL, Thompson
named it B language , which was the first letter of BCPL. When the language was
modified and improved to its present state, the second letter of BCPL, C was
chosen to represent the new version by Dennis Ritchie.

Merits of C

C is a general purpose programming language.


C is a structural programming language.
C is a standardized programming language.
It is system independent.
It has limited data types with great efficiency.
C has high efficiency.
It contains a powerful instruction set for manipulating of data.
It contains the modern methods of coding loops.

 What is a Character set?

Like every other language 'C' also has its own character set. A program is a set of
16
instructions that when executed, generate an output. The data that is processed by a
program consists of various characters and symbols. The output generated is also a
combination of characters and symbols.

A character set in 'C' is divided into,

Letters
Numbers
Special characters
White spaces (blank spaces)

A compiler always ignores the use of characters, but it is widely used for
formatting the data. Following is the character set in 'C' programming:

1. Letters
o Uppercase characters (A-Z)
o Lowercase characters (a-z)
2. Numbers
o All the digits from 0 to 9
3. White spaces
o Blank space
o New line
o Carriage return
o Horizontal tab
4. Special characters
o Special characters in 'C' are shown in the given table,

, (comma) { (opening curly bracket)


. (period) } (closing curly bracket)
; (semi-colon) [ (left bracket)
: (colon) ] (right bracket)
? (question mark) ( (opening left parenthesis)
' (apostrophe) ) (closing right parenthesis)
" (double quotation & (ampersand)
mark)
! (exclamation mark) ^ (caret)
|(vertical bar) + (addition)
/ (forward slash) - (subtraction)
17
\ (backward slash) * (multiplication)
~ (tilde) / (division)
_ (underscore) > (greater than or closing angle bracket)

$ (dollar sign) < (less than or opening angle bracket)


% (percentage sign) # (hash sign)

 Token

A token is the smallest unit in a 'C' program. A token is divided into six different
types as follows,

Tokens in C

 Keywords and Identifiers

In 'C' every word can be either a keyword or an identifier.

Keywords have fixed meanings, and the meaning cannot be changed. They act as a
building block of a 'C' program. There are total 32 keywords in 'C'. Keywords are
written in lowercase letters.

Following table represents the keywords in 'C',


18
auto double int struct
break else long switch
case enum registe typedef
r
char extern return union
const short float unsigned
continu for signed void
e

default goto sizeof volatile


do if static while

An identifier is nothing but a name assigned to an element in a program.


Example,name of a variable, function, etc. Identifiers are the user-defined names
consisting of 'C' standard character set. As the name says, identifiers are used to
identify a particular element in a program. Each identifier must have a unique
name.
Following rules must be followed for identifiers:

1. The first character must always be an alphabet or an underscore.


2. It should be formed using only letters, numbers, or underscore.
3. A keyword cannot be used as an identifier.
4. It should not contain any whitespace character.
5. The name must be meaningful.

 What is a Variable?

A variable is an identifier which is used to store some value. Constants can


neverchange at the time of execution. Variables can change during the
execution of a program and update the value stored inside it.

A single variable can be used at multiple locations in a program. A variable name


must be meaningful. It should represent the purpose of the variable.

Example: Height, age, are the meaningful variables that represent the purpose it
isbeing used for. Height variable can be used to store a height value. Age variable
can be used to store the age of a person
19
Following are the rules that must be followed while creating a variable:

1. A variable name should consist of only characters, digits and an underscore.


2. A variable name should not begin with a number.
3. A variable name should not consist of whitespace.
4. A variable name should not consist of a keyword.
5. 'C' is not a case sensitive language that means a variable named 'age'
and'AGE' are different.

Following are the examples of valid variable names in a 'C' program:

height or HEIGHT
_height
_height1
My_name

Following are the examples of invalid variable names in a 'C' program:

1height
Hei$ght
My name

For example, we declare an integer variable my_variable and assign it the value
48:

int my_variable;
my_variable = 48;

By the way, we can both declare and initialize (assign an initial value) a variable in
a single statement:

int my_variable = 48;


Local variables
Before learning about the local variable, we should learn about the function
blockand function parts. There are two parts of the function block (block means
regionof the function between curly braces in C)
1. Declaration part - Region where we declare all variables which are going to
20
be used within the function (this part starts from starting curly brace "{").
2. Executable part - Other statements except the declarations are
theexecutable statements.
Global variables

Global variables are the variables which are declared or defined below the header
files inclusion section or before the main () function. These variables have global
scope to the program in which they are declared. They can be accessed or
modifiedin any function of the program.

Global variable can also be accessed in another files too (for this, we have to
declare these variables as extern in associate header file and header file needs to
beincluded within particular file).#include <stdio.h>

#include<stdio.h>

/*global variables*/
int a,b;

int main()

/*local

variables*/int x,y;

x=10;

y=20;

setValues();

printf("a=%d, b=%d\n",a,b);

21
printf("x=%d, y=%d\n",x,y);

return 0;

 Constants

Constants are the fixed values that never change during the execution of a
program. Following are the various types of constants:

I. Integer constants

An integer constant is nothing but a value consisting of digits or numbers.


These values never change during the execution of a program. Integer
constants can beoctal, decimal and hexadecimal.

1. Decimal constant contains digits from 0-9 such as,

Example, 111, 1234


Above are the valid decimal constants.

2. Octal constant contains digits from 0-7, and these types of constants
arealways preceded by 0.

Example, 012, 065

Above are the valid decimal constants.

3. Hexadecimal constant contains a digit from 0-9 as well as characters


fromA-F. Hexadecimal constants are always preceded by 0X.

Example, 0X2, 0Xbcd

Above are the valid hexadecimal constants.

The octal and hexadecimal integer constants are very rarely used in programming
with 'C'.

22
II. Character constants

A character constant contains only a single character enclosed within a single


quote (''). We can also represent character constant by providing ASCII value of it.

Example, 'A', '9'

Above are the examples of valid character constants.

III. String constants

A string constant contains a sequence of characters enclosed within double


quotes("").

Example, "Hello", "Programming"

These are the examples of valid string constants.

IV. Real Constants

Like integer constants that always contains an integer value. 'C' also provides real
constants that contain a decimal point or a fraction value. The real constants are
also called as floating point constants. The real constant contains a decimal point
and a fractional value.
V. Symbolic Constants

Symbolic Constant is a name that substitutes for a sequence of characters or a


numeric constant, a character constant or a string constant.

When program is compiled each occurrence of a symbolic constant is replaced


byits corresponding character sequence.
The syntax of Symbolic Constants in C
#define name text

where name implies symbolic name in


[Link] implies value or the text.
For example,

23
#define printf
print#define MAX
50
#define TRUE 1
#define FALSE 0
#define SIZE 15

 Expressions

An expression is a formula in which operands are linked to each other by the use
ofoperators to compute a value. An operand can be a function reference, a
variable, an array element or a constant.

There are four types of expressions exist in C:

o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions

Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of a particular expression produces a specific value.

 Statement

A statement is a command given to the computer that instructs the computer


totake a specific action, such as display to the screen, or collect input. A
computer program is made up of a series of statements.
Following are the statements which is used in programming In C

1. IF statement

2. IF Else Statement

3. Break statement

4. Goto statement

24
5. Switch statement

6. Continue statement

 Data types

'C' provides various data types to make it easy for a programmer to select a suitable
data type as per the requirements of an application. Following are the three data
types:

I. Build-in and primary data types


II. Derived data types
III. User-defined data types

I. Build-in .and Primary Data Types

There are five primary fundamental data types,


1. int for integer data
2. char for character data
3. float for floating point numbers
4. double for double precision floating point numbers
5. void

25
Size in
Data type Range
bytes

Char or signed char 1 -128 to 127

Unsigned char 1 0 to 255

int or signed int 2 -32768 to 32767

Unsigned int 2 0 to 65535

Short int or Unsigned short int 2 0 to 255

Signed short int 2 -128 to 127

Long int or Signed long int 4 -2147483648 to 2147483647

Unsigned long int 4 0 to 4294967295

float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

Long double 10 3.4E-4932 to 1.1E+4932

Note: In C, there is no Boolean data type.


1. Integer data type

Integer is nothing but a whole number. The range for an integer data type varies
from machine to machine. The standard range for an integer data type is -32768
to32767.

An integer typically is of 2 bytes which means it consumes a total of 16 bits in


memory. A single integer value takes 2 bytes of memory. An integer data type is
further divided into other data types such as short int, int, and long int.

Each data type differs in range even though it belongs to the integer data type
family. The size may not change for each data type of integer family.
26
The short int is mostly used for storing small numbers, int is used for storing
averagely sized integer values, and long int is used for storing large integer
values.

Whenever we want to use an integer data type, we have place int before
theidentifier such as,

int age;

Here, age is a variable of an integer data type which can be used to store integer
values.

2. Floating point data type

Like integers, in 'C' program we can also make use of floating point data types.
The 'float' keyword is used to represent the floating point data type. It can hold a
floating point value which means a number is having a fraction and a decimal
part.A floating point value is a real number that contains a decimal point. Integer
data type doesn't store the decimal part hence we can use floats to store decimal
part of a value.

Generally, a float can hold up to 6 precision values. If the float is not sufficient,
then we can make use of other data types that can hold large floating point
values. The data type double and long double are used to store real numbers with
precisionup to 14 and 80 bits respectively.

While using a floating point number a keyword float/double/long double must


beplaced before an identifier. The valid examples are,
float division;
double BankBalance;

3. Character data type

Character data types are used to store a single character value enclosed in
singlequotes.

27
A character data type takes up-to 1 byte of memory space.

Example,

Char

letter;

4. Void data type

A void data type doesn't contain or return any value. It is mostly used for defining
functions in 'C'.

Example,

Type declaration of a variableand using data types

int main()
{
int x, y;
float salary = 13.48;
char letter = 'K';
x = 25;
y = 34;
int z = x+y; printf("%d
\n", z); printf("%f \n",
salary);printf("%c \n",
letter);return 0;}
Output: 59
13.480000
K
We can declare multiple variables with the same data type on a single line by
separating them with a comma. Also, notice the use of format specifiers in
printfoutput function float (%f) and char (%c) and int (%d).

II. User Define Data Types

C allows the feature called type definition which allows programmers to


28
definetheir identifier that would represent an existing data type. There are
three such types:

Data types Description

Structure It is a package of variables of different types under


a single name. This is done to handle data
efficiently. "struct" keyword is used to define a
structure.
Union These allow storing various data types in the
samememory location. Programmers can define a
union with different members, but only a single
member can contain a value at a given time. It is
used for
Enum Enumeration is a special data type that consists of
integral constants, and each of them is assigned
with a specific name. "enum" keyword is used to
define the enumerated data type.

III. Derived Data Types

C supports three derived data types:

Data types Description

Arrays Arrays are sequences of data items


having homogeneous values. They
have
adjacent memory locations to store

29
values.

Function Function pointers allow referencing


functions with a particular signature.

Pointers These are powerful C features which


areused to access the memory and
deal with their addresses.

 C Operators
Operators are used in c for manipulating the data store into the variables .

Types of Operators

I. Arithmetic
II. Relational
III. Logical
IV. Bitwise

I. C Arithmetic Operators

An arithmetic operator performs mathematical operations such as


addition, subtraction, multiplication, division etc on numerical values
30
(constants andvariables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)

Example 1: Arithmetic Operators

// Working of arithmetic
operators#include<stdio.h>
int main()
{
int a =9,b =4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return0;
}

Output

a+b = 13
a-b = 5
a*b = 36
31
a/b = 2
II. C Relational Operators

A relational operator checks the relationship between two operands. If the


relationis true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators

1. // Working of relational

operators#include<stdio.h>

int main()

int a =5, b =5, c =10;

printf("%d == %d is %d \n", a, b, a == b);

printf("%d == %d is %d \n", a, c, a == c);

printf("%d > %d is %d \n", a, b, a > b);

32
printf("%d > %d is %d \n", a, c, a > c);

printf("%d < %d is %d \n", a, b, a < b);


printf("%d < %d is %d \n", a, c, a < c);

printf("%d != %d is %d \n", a, b, a != b);

printf("%d != %d is %d \n", a, c, a != c);

printf("%d >= %d is %d \n", a, b, a >= b);

printf("%d >= %d is %d \n", a, c, a >= c);

printf("%d <= %d is %d \n", a, b, a <= b);

printf("%d <= %d is %d \n", a, c, a <= c);

return0;

Output

5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1

III. C Logical Operators

An expression containing logical operator returns either 0 or 1 depending upon


33
whether expression results true or false. Logical operators are commonly used in
decision making in C programming.

Operator Meaning Example

Operator Meaning Example

Logical AND. True only if all If c = 5 and d = 2 then, expression


&&
operands are true ((c==5) && (d>5)) equals to 0.

Logical OR. True only if either If c = 5 and d = 2 then, expression


||
one operand is true ((c==5) || (d>5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression !(c==5) equals


! operand is 0 to 0.

Example 5: Logical Operators

// Working of logical operators

#include<stdio.h>

int main()

int a =5, b =5, c =10, result;

result =(a == b)&&(c > b

printf("(a == b) && (c > b) is %d \n", result);

result =(a == b)&&(c < b);

printf("(a == b) && (c < b) is %d \n", result);

result =(a == b)||(c < b);


34
printf("(a == b) || (c < b) is %d \n",

result);result =(a != b)||(c < b);

printf("(a != b) || (c < b) is %d \n", result);

result =!(a != b);


printf("!(a == b) is %d \n", result);

result =!(a == b);

printf("!(a == b) is %d \n", result);

return0;

Output

(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0

Explanation of logical operator program

 (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c >


b) is 1 (true).
 (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
 (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
 (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b)
are0 (false).
 !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b)
is 1 (true).
 !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0
(false).

35
IV. C Bitwise Operators

During computation, mathematical operations like: addition, subtraction,


multiplication, division, etc are converted to bit-level which makes
processingfaster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

V. Other Operators

Comma Operator

Comma operators are used to link related expressions together. For example:

1. int a, c =5, d;

The sizeof operator

The sizeof is a unary operator that returns the size of data (constants, variables,
array, structure, etc).

Example 6: sizeof Operator

#include<stdio.h>
36
int main()

int a;

float b;

double c;
char d;

printf("Size of int=%lu bytes\n",sizeof(a));

printf("Size of float=%lu bytes\n",sizeof(b));

printf("Size of double=%lu bytes\n",sizeof(c));

printf("Size of char=%lu byte\n",sizeof(d));

return0;

Output

Size of int = 4 bytes Size


of float = 4 bytes Size of
double = 8 bytesSize of
char = 1 byte

Other operators such as ternary operator ? Reference operator &, dereference


operator *and member selection operator ->will be discussed in later tutorials.

C Increment and Decrement Operators

C programming has two operators increment ++and decrement --to change the
value of an operand (constant or variable) by 1.

37
Increment ++increases the value by 1 whereas decrement --decreases the valueby
1. These two operators are unary operators, meaning they only operate on a
single operand.

Example 2: Increment and Decrement Operators

#include<stdio.h>

int main()

int a =10, b =100;

float c =10.5, d =100.5;

printf("++a = %d \n",++a);

printf("--b = %d \n",--b);

printf("++c = %f \n",++c);

printf("--d = %f \n",--d);

return0;

Output

++a = 11
--b = 99
++c = 11.500000
--d = 99.500000

Here, the operators ++ and -- are used as prefixes. These two operators can also
beused as postfixes like a++ and a--. Visit this page to learn more about how
increment and decrement operators work when used as postfix.

C Assignment Operators
38
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

Operator Example Same as

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

Example 3: Assignment Operators


// Working of assignment
operators#include<stdio.h>
int main()
{
int a =5, c;
c = a;
printf("c = %d\n", c);
c += a;
printf("c = %d\n", c);
c -= a;
printf("c = %d\n", c);
c *= a;
printf("c = %d\n", c);
c /= a;
printf("c = %d\n", c);
c %= a;
printf("c = %d\n", c);
return0;
}
39
Output
c=5
c = 10
c=5
c = 25
c=5
c=0

 Conditional Operator

The conditional operator is also known as a ternary operator. The conditional


statements are the decision-making statements which depends upon the output
ofthe expression. It is represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the
ternaryoperator.

The behavior of the conditional operator is similar to the 'if-else' statement as


'if-else' statement is also a decision-making statement.

Syntax of a conditional operator

1. Expression1? expression2: expression3;

The pictorial representation of the above syntax is shown below:

Meaning of the above syntax.


40
o In the above syntax, the expression1 is a Boolean condition that can
beeither true or false value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.

C Standard Library Functions

In this tutorial, you'll learn about the standard library functions in C. More
specifically, what are they, different library functions in C and how to use them in
your program.
C Standard library functions or simply C Library functions are inbuilt functions inC
programming.
The prototype and data definitions of these functions are present in their
respectiveheader files. To use these functions we need to include the header file
in our program. For example,
If you want to use the printf() function, the header file <stdio.h> should
beincluded.
#include <stdio.h>
int ma in()
{
printf("Catch me if you can.");
}
If you try to use printf() without including the stdio.h header file, you will get
anerror.

Advantages of Using C library functions

1. They work
One of the most important reasons you should use library functions is simply
because they work. These functions have gone through multiple rigorous testing
and are easy to use.
2. The functions are optimized for performance
Since, the functions are "standard library" functions, a dedicated group of
developers constantly make them better. In the process, they are able to create
themost efficient code optimized for maximum performance.
41
3. It saves considerable development time
Since the general functions like printing to a screen, calculating the square root,
and many more are already written. You shouldn't worry about creating them
onceagain.
4. The functions are portable
With ever-changing real-world needs, your application is expected to work every
time, everywhere. And, these library functions help you in that they do the same
thing on every computer.
Library Functions in Different Header Files

C Header Files

<assert.h> Program assertion functions

<ctype.h> Character type functions

<locale.h> Localization functions

C Header Files

<math.h> Mathematics functions

<setjmp.h> Jump functions

<signal.h> Signal handling functions

<stdarg.h> Variable arguments handling functions

<stdio.h> Standard Input/Output functions

<stdlib.h> Standard Utility functions

<string.h> String handling functions

<time.h> Date time functions

42
UNIT-II
Formatted & Unformatted input output

• Unformatted Input/Output functions

I. getchar()
II. putchar()
III. getch()
IV. putch()
V. gets()
VI. puts()
VII. prinf()
VIII. scanf()

I. getchar():This function reads a character-type data from standard input. • It


readsone character at a time till the user presses the enter key.

Example: char c; c = getchar();

#include<stdio.h>

void main()

char c;

printf(“enter a

character”);c=getchar();

printf(“c = %c ”,c);

}
II. putchar() : This function prints one character on the screen at a time which
isread by standard input.

43
E

x put

a cha

m r

p (c);

l #in

e clu

: de<

stdi

c o.h

h >

a voi

r d

mai

c n()

=
{

‘ char ch;

c printf(“e

’ nter a

; characte
44
r );

: putchar(

ch);

” }

) e

; n

s e

c r

n a

( c

“ h

% a

c r

” a

, c

c e

h r

45
: character.

r i

r c

III. getch l
() &
getche(): u
These
functions d
read any
alphanu e
meric
character
from the v
standard
input o
device
The i
character
entered d
is not
displayed
by the
getch() m
function
a
until
enter is
i
pressed
.The n
getche()
accepts (
and
displays )
the
46
{ phabets:”);

p getche();

r getch();

i }
Enter two alphabets a
n
IV. putch():This function prints any alphanumeric character
t
taken by the standardinput device.
f
Example:
(
#

i
E
n
n
c
t
l
e
u
r
d

e
t
<
w
s
o
t

d
a
i
l
o
47
. tf(“Press any key

h to continue”);ch

> = getch();

prin

v tf(“

o you

i pres

d sed:

”);

m putc

a h(ch

i );

n }

) Press

{ any

char ch; key to

contin
p
ueYou
r
presse
i
d:e
n
48
V. gets( t
):This
functio d
n is
used i
for
accepti o
ng any
.
string
until h
enter
key is >
pressed
(string
will be
covere #
d later).
i
#
n
i
c
n
l
c
u
l
d
u
e
d

e
<

s
<
t
s
r

49
i rintf(“E

n nter

g the

. string:”

h );

> gets(ch

);

v printf(“Entered string: %s”, ch);

o }

i Enter the

d string: Use

of data!

m Entered

a string: Use

i of data!

n puts()

( :This

) function

{ prints the

char ch[30]; string or


p
character
50
a to gets().

r #include

r <stdio.h>

a #

y i

. n

I l

t u

i e

<

o s

p t

p r

o i

s n

i g

t .

e h

51
> y(str, "This is

a test string");

v puts(string);

o }

i VI. p
r
d
i
n
t
m f
(
a )
:
i
 In C programming language, printf() function is used to
n print the “character,string, float, integer, octal and
hexadecimal values” onto the output screen.
(  We use printf() function with %d format specifier to
display the value of aninteger variable.
)
 Similarly %c is used to display character, %f for float
{ variable, %s for stringvariable, %lf for double and %x for
hexadecimal variable.
 To generate a newline,we use “\n” in C printf() statement.
char
string[40]; i
n
s t
t
a
=
r
1
c 0
;
p dou
ble
52
d read character, string, numeric data from [Link]
= below example programwhere user enters a character. This
1 value is assigned to the variable “ch” and then displayed.
3
. Then, user enters a string and this value is assigned to the
4 variable “str” andthen displayed.
;

p
i
r
i
n
n
t t
f
(
"
% a
f
% ;
d
"
,
d f
,
l
a
) o
;
a
VII. sc
anf():In t
C
progra
mming
languag b
e,
scanf() ;
functio
scanf("%d%f",&a,&b);
n is
used to
53
Examp "Enter any
le character
progra \n");
m for scanf("%c",
printf( &ch);
) and printf("Entered character is %c
scanf() \n", ch); printf("Enter any
functi string ( upto 100 character )
ons in \n");scanf("%s", &str);
C printf("Entered string is %s \n", str);
progra }
mming
langua Control Statements:
ge:
Control statements enable us to specify the flow of program
#include control; ie, the order inwhich the instructions in a program
<stdio.h> must be executed. They make it possible to make decisions, to
int main() perform tasks repeatedly or to jump from one section of code
{ toanother.
char ch;
char Control Statements are Two Types
str[100];
p I. Decision Making
r II. Case
i III. Looping
n
t

f
(
54
on control statements (if-else andnested if), group of
statements are executed when condition is true. If
condition is false, then else part statements are
I. D executed.
e
c There are 3 types of decision making control statements in C
i language. They are,
s
i  if statements
o  if else statements
n  else if ladder
 if statements:This is the simplest form of ‘if’ statement.
C
The expression is tobe placed in parenthesis. It can be
o
any logical [Link] Block is executed when the
n
given condition is true.
t
r
o
l
S
t
a
t
e
m
e
n
t
s
:
I
n

d
e
c
i
s
i
55
Syntax sitive
If(Cond #include<stdio.
ition) h>
{ void main()
Block1; {
} i
Exampl n
e: t
P
r a
o ;
g
r a
a =
m 1
;
c
if(a>0)
h
{
e
printf(“number is positive”);
c
}
k
}
Output
n
number is positive
u
m  if else statements :In the “if” statement seen earlier,
b we can take some action if expression is true. But if
e expression is false there is no action. Wecan include an
r action for both conditions (i.e. true or false) by using if-
elsestatement. If condition is true block1 is executed
otherwise block2.
i
s

P
o
56
Syntax number is

If(Condition)

Block1;
}

else

Block2;

Example:
Positive
P
#include<stdio.
r
h>
o
void main()
g
{
r
i
a
n
m
t

c
a
h
;
e

c
a
k
57
= ladder or multiple alternative if statement is carried out
from top to bottom. Each conditional expression is
1 tested and iffound true only then its corresponding
statements is executed. In a situationwhere none of the
;
nested conditions is found true then the final else part is
if(a>0) executed.

{ Syntax

printf(“numb if (condition 1)
er is
positive”); Block
}
else if (condition 2)
else
Block
{
e
printf(“numb
er is negative l
“);
s
}
e
}

Output

number is i
positive
f
 else if
ladder (
The
evo c
luti
ons o
of
if- n
else
d
–if
58
i days of week input enter by user from 1 to 7

t #include<stdio.h>

i int main()

o {

n int day;

printf("enter key from 1 to 7 to print


3
days of week");scanf("%d", &day);
)
if(day==1)

printf("T
B
oday is
l
Monday
o
");else
c
if(day==
k
2)
*
printf("T
p
oday is
r
Tuesday
i
");else
n
if(day==
t
3)

printf("Tod
59
a se

y if(day==4)

printf("T

i oday is

s thursday

");else

W if(day==5

e )

d printf("T

n oday is

e Friday");

s else

d if(day==6

a )

y printf("T

" oday is

) Saturday

; ");else

if(day==7

e )

l printf("T

60
o e

d printf("wrong input");

a }

Other decision making statements

i jump: Java supports three jump statement: break, continue


and goto. These threestatements transfer control to other
s part of the program.

1. Break: In Java, break is majorly used for:


 Terminate a sequence in a switch statement
S  To exit a loop.
 Used as a “civilized” form of goto.
u

n Using break to exit a Loop

d #include <stdio.h>

a int main () {

y
/* local
"
variable
)
definition
;
*/int a =

10;
e

l
/*
s

61
d do {

if( a == 15) {

l /*

o ski

o p

p th

e ite

x rat

e ion

c */

u a=

t a+

i 1;

o break;

n }

* printf("va

/ lue of a:

%d\n", a);

62
a

+ a

+ :

} 0
while
(a<
20 );
v

a
retur l
n 0;
u
}
Output e
:

v
o
a
f
l

u
a
e
:

o
1
f
1

63
v o

a f

u a

e :

o 1

f 3

a v

: a

1 u

2 e

v o

a f

u a

e :

64
nue: The continue statement in C programming works
somewhat like the break statement. Instead of forcing
1 termination, it forces the next iteration of the loop to
take place, skipping any code in between.
4
For the for loop, continue statement causes the
conditional test andincrement portions of the
loop to execute. For
v
the while and do...while loops, continue statement
a causes the programcontrol to pass to the
conditional tests.
l
#
u
i
e
n

c
o
l
f
u

a d

: e

1 <

5 s

t
2. C
o d
n
ti i
65
o local
variable
. definition
*/int a =
h 10;

> /*
do
loop
exe
i cuti
on
n */
do {
t
if( a == 15) {
/*
ski
m p
th
a e
ite
i rat
ion
n */
a=
a+
1;
( continue;
}
)
printf("value of a: %d\n", a);
a++;

{ } while( a < 20 );

/
return 0;
*
}
66
Output f
:
v a
a :
l
u 1
e 2

o v
f a
l
a u
: e

1 o
0 f

v a
a :
l
u 1
e 3

o v
f a
l
a u
: e

1 o
1 f

v a
a :
l
u 1
e 4

o v
67
a :
l
u 1
e 8

o v
f a
l
a u
: e

1 o
6 f

v a
a :
l
u 1
e 9

o
f
3. goto: The goto statement is a jump statement which
a is sometimes also referred to as unconditional jump
: statement. The goto statement can be usedto jump
from anywhere to anywhere within a function.
1
7

v
a
l
u
e

o
f

a
68
u
Exampl
m
e
b
#includ
e e
<stdio.
h> r

int =
main()
1
{
;
i
w
n
h
t
il

e
n
69
( ntf("Number is :

n %d", number);

u end:

m printf("Bye Bye !!!");

b
}
e
return 0;
r
}
<
Output
=

1
First run:
0
N
)
u
{
m
if(num
ber==4 b
)
e
go r
to
en
d;
i
p
s
r

i
:
70
m of statement available for selective execution is the
switchstatement. It causes particular group of
1 statements to be selected from
several available group.

y
The general
e
format is as

[Link]
!
(expression)
!
Statement;
!
Where statement consist of one more case
II. switch statements followed by a colonand group of
– case statements.
An
oth switch (expression)
er
for {
71
case
express b
ion 1 :
statem r
ent 1;
e
statem
a
ent 2;
break; k
case ;
express
ion 2 :
statem
ent 1; d

s e

t f

a a

t u

e l

m t

n :

t statement 1;

statement 2;

2 }

; The expression should result in an integer value or


72
char d
acte
r i
valu
e. o
First
.
the
expr
h
essi
on >
follo
win
g
swit v
ch is
solv o
ed.
i
#
d
i

n
m
c
a
l
i
u
n
d

e
(
<

s
)
t
{

73
i

n )

t {

case 1 :

j printf

("nI am
= in case

1.");
2 break;
; case 2:

printf
s
("nI am
w
in case
i
2.");
t
break;
c
case 3:
h
printf ("nI am in case 3.");
default:

( printf ("nI am in default.");

j }
74
We can either repeat the code in our program or use
III. Lo loops instead. It is obvious that if for example we need
op to execute some part of code for a hundred times it is
in not practical to repeat the code. Alternativelywe can
g: use our repeating code inside a loop.
So
m Types of Loops in C
eti
m  while
es  do-while
w  for
e
w  while: The statements within the while loop would keep
an on getting executed tillthe condition being tested
t remains true. When the condition becomes false, the
so control passes to the first statement that follows the
m body of the while loop. It is entry control loop.
e
pa S
rt
of y
ou
r n
co
t
de
to
a
be
ex x
ec
ut
ed
m I
or
e n
th
an i
on
t
ce
.
75
i d

a i

l t

i i

z o

a n

t )

i {

o Block;

n Increm

; ent/de

cremen

W t;

h }

i Three important parts of Loop


l
i) initialization:it is the starting Point of
e loop.

o Example:

76
ii) T n which is tobe checked.
e iii) Increment/decrement :for Increment (++) is used
s and(--) is used for decrement to given
t statements.

C
o
n
d
i
t
i
o
n
:
i
t

i
s

t
h
e

g
i
v
e
n

c
o
n
d
i
t
i
o
77
#include <stdio.h>

int main ()

int a = 10;

while( a < 14 ) {

printf("value of a: %d\n", a);

a++;

return 0;

output

value of a:10

value of a:11

value of a:12

value of a:13

 do while:The while and for loops test the termination condition at the top. By
contrast, the third loop in C, the do-while, tests at the bottom after making
eachpass through the loop body; the body is always executed at least once.

Syntax
78
Initialization;

do

Block;

Increment/decrement ;

}while (condition);

Example

#include <stdio.h>

int main () {

int a = 10;

do

printf("value of a: %d\n", a);

a + +;

while( a < 14 );

return 0;

output

79
value of a:10

value of a:11

value of a:12

value of a:13

 for loop: for loop is something similar to while loop but it is more
complex. for loop is constructed from a control statement that determines
howmany times the loop will run and a command section. Command section
is either a single command or a block of commands.

Syntax

for ( initialization; test condition; increment/decrement )

Block;

Example

#include <stdio.h>

int main ()

int a;

for( a = 10; a <14; a + + )

{
80
printf("value of a: %d\n", a);

}
return 0;

output

value of a:10

value of a:11

value of a:12

value of a:13

BASIS FOR
COMPARISON WHILE DO-WHILE

General Form while ( condition) { do{


statements; //body of .
loop statements; // body of loop.
} .
} while( Condition );

Controlling In 'while' loop the In 'do-while' loop the


Condition controlling condition controlling condition
appears at the start of appearsat the end of the
theloop. loop.
Iterations The iterations do not The iteration occurs at least
occur if, the condition at once even if the condition
the first iteration, appears isfalse at the first iteration.
false.
type It entry Control Loop It Exit Control Loop.

81
BCA 1st Sem ( Programming In C)

UNIT-III

Function

A function is a group of statements that together perform a task. Every C program


has at least one [Link] can divide up your code into separate functions.
Howyou divide up your code among different functions is up to you, but logically
the division is such that each function performs a specific task.

The advantages of using functions are:

 Avoid repetition of codes.


 Increases program readability.
 Divide a complex problem into simpler ones.
 Reduces chances of error.
 Modifying a program becomes easier by using function.

Three parts of Function

Function declaration(Prototype):A function declaration tells the compiler


about a function's name, return type, and parameters.

Syntax

Returntype Functionname (parameterlist);

A function definition in C programming consists of a function header and


a function body. Here are all the parts of a function −
 Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the
desiredoperations without returning a value. In this case, the
return_type is the keyword void.
 Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function
signature.
 Parameters − A parameter is like a placeholder. When a function is
82
BCA 1st Sem ( Programming In C)

invoked, you pass a value to the parameter. This value is referred to as


actualparameter or argument. The parameter list refers to the type, order,
and number of the parameters of a function. Parameters are optional; that
is, a function may contain no parameters
Function Definition: function definition in which number of statements are
write down into body of the function.

Syntax

Returntype Functionname(parameterlist)

Statements;

Function call:A program calls a function, the program control is transferred


to the called function. A called function performs a defined task and when
itsreturn statement is executed or when its function-ending closing brace is
reached, it returns the program control back to the main program.

Syntax

Functionname(); Types

of Function in C
 Predefined Functions: The Predefined Functions are those which are
already defined into C Like printf(),scanf(),main() etc.
 User defined Functions: These Functions are made by program itself
to perforam any task and solve any problem.

User defined Functions: Categories of User defined Functions are

1) Function with no arguments and no return value


83
BCA 1st Sem ( Programming In C)

2) Function with no arguments and a return value


3) Function with arguments and no return value/ Specifying argument data types
4) Function with arguments and a return value/ Function with argument

Categories of User defined Functions ( Function Prototypes)

Function with no arguments and no return value

Function with no arguments and a return value

Function with arguments and no return value

Function with arguments and a return value

1) Function with no arguments and no return value: This Type of Function


have no arguments and any return value that void.

Syntax:
Void functionname (void);
Example:
#include<stdio.h>
void sum(void); //function declaration

void sum(void)
{
int a,b,c;
printf(“enter two number\n”); //function defination

84
BCA 1st Sem ( Programming In C)

scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum is %d”,c);
}
void main()
{
sum(); //function call

}
Output
enter two
number10 20
sum is 30

2) Function with no arguments and a return value:This Type of Function


have no arguments with any return value that is the calculated back to
themain().

Syntax:
returnvalue functionname (void);
Example:
#include<stdio.h>
int sum(void); //function declaration
int sum(void)

{
int a,b,c;
printf(“enter two number\n”); //function
definationscanf(“%d%d”,&a,&b);
85
BCA 1st Sem ( Programming In C)

c=a+b;
return(c)
;
}
void main()
{
int c;
c=sum(); //function call
printf(“sum is %d”,c);
}
Output
enter two
number10 20
sum is 30
3) Function with arguments and No return value:This Type of Function have
arguments that are the value which is enter from the main(), the arguments
have datatype and every argument separated by commas(,). Thesehave no
any return value .

Syntax:
void functionname (parameter list);
Example:
#include<stdio.h>
void sum(int a,int b); //function declaration
void sum(int a,int b)

int a,b,c;
c=a+b; //function
definationprintf(“sum is %d”,c);

86
BCA 1st Sem ( Programming In C)

}
void main()
{
int a,b;
printf(“enter two
number\n”);
scanf(“%d%d”,&a,&b);

sum(a,b); //function call


}
Output
enter two
number10 20
sum is 30
4) Function with arguments and with return value:This Type of Function
have two way communication between user define function and
main().theuser define function accept the data from main() and back the
result to main().

Syntax:
void functionname (parameter list);
Example:
#include<stdio.h>
int sum(int a,int b); //function
declarationint sum(int a,int b)

int a,b,c;
c=a+b; //function
87
BCA 1st Sem ( Programming In C)

definationreturn ( c );
}
void main()
{
Int a,b, c;
printf(“enter two
number\n”);
scanf(“%d%d”,&a,&b);

c=sum(a,b); //function
callprintf(“sum is %d”,c);
}
Output
enter two
number10 20
sum is 30
what formal and actual arguments
Formal Argument :
The formal arguments are the arguments in the function declaration. The
scope of formal arguments is local to the function definition in which they
are used. They belong to the called function.
Actual arguments :
The arguments that are passed in a function call are called actual
[Link] arguments are defined in the calling function.
Example:
#include<stdio.h>
int sum(int a,int b); //function declaration
int sum(int a,int b) formal arguments

88
BCA 1st Sem ( Programming In C)

{
int a,b,c;
c=a+b; //function
definitionreturn ( c );
}
void main()
{
Int a,b, c;
printf(“enter two
number\n”);
scanf(“%d%d”,&a,&b);

c=sum(a,b); //function call Actual Arguments


printf(“sum is %d”,c);
}
Call by value :
In call by value, a copy of actual arguments is passed to formal arguments of
the called function and any change made to the formal arguments in the
calledfunction have no effect on the values of actual arguments in the calling
function.
In call by value, actual arguments will remain safe, they cannot be modified
accidentally.
Example using Call by Value
The classic example of wanting to modify the caller's memory is
a swapByValue() function which exchanges two values. For C uses call by
value, the following version of swap swapByValue() will not work...
#include <stdio.h>
void swapByValue(int a, int b)
89
BCA 1st Sem ( Programming In C)

{
int t;
t = a;
a = b;
b = t;
printf(" Values In user define a: %d, b: %d\n", a,b);
}
int main() /* Main function */
{
int a1 = 10;
int b1 = 20;

/* actual arguments will be as it is


*/swapByValue(a1, b1);
printf ("Values In main a1: %d, b1: %d\n", a1,b1);
}OUTPUT
======
Values In user define a: 20, b: 10
Values In main a1: 10, b1: 20

Call by Reference
In call by reference, to pass a variable n as a reference parameter, the
programmer must pass a pointer to n instead of n itself. The formal
parameterwill be a pointer to the value of interest. The calling function will
need to
use & to compute the pointer of actual parameter. The called function will
need to dereference the pointer with *where appropriate to access the
value ofinterest. Here is an example of a correct swap swapByReference()
90
BCA 1st Sem ( Programming In C)

function.
So, now you got the difference between call by value and call by reference!
#include <stdio.h>
void swapByValue(int *a, int *b); /* Prototype */

void swapByValue(int *a, int * b)


{
int t;
t = *a;
*a = *b;
*b = t;
printf(" Values In user define *a: %d, *b: %d\n", *a,*b);

}
int main() /* Main function */
{
int a1 = 10;
int b1 = 20;

/* actual arguments will be as it is


*/swapByValue(&a1,& b1);
printf("Values In main a1: %d, b1: %d\n", a1, b1);
} OUTPUT
======
Values In user define a: 20, b: 10
Values In main a1: 20, b1: 10

91
BCA 1st Sem ( Programming In C)

CALL BY VALUE CALL BY REFERENCE

While calling a function, we pass While calling a function, instead of

values of variables to it. Such passing the values of variables, we

functions are known as “Call By pass address of variables(location

Values”. ofvariables) to the function known

as “Call By References.

In this method, the value of each In this method, the address of

variable in calling function is copied actualvariables in the calling

into corresponding dummy function are copied into the

variablesof the called function. dummy variables of the called

function.

With this method, the changes

madeto the dummy variables in the With this method, using addresses

calledfunction have no effect on the wewould have an access to the

valuesof actual variables in the actual variables and hence we would

calling function. be ableto manipulate them.

92
BCA 1st Sem ( Programming In C)

// Cmain()
int program to illustrate // Cmain()
int program to illustrate
{// call by value {// Call by Reference
int a = 10, b = 20; int a = 10, b = 20;
#include <stdio.h> #include <stdio.h>
// Pass by Values // Pass reference
// swapx(a,
Function Prototype
b); // swapx(&a,
Function Prototype
&b);
void swapx(int x, int y); void swapx(int*, int*);
printf("a=%d b=%d\n", a, b); printf("a=%d b=%d\n", a, b);
// Main function // Main function
return 0; return 0;
} }

// Swap functions that swaps // Function to swap two variables


// two values // by references
void swapx(int x, int y) void swapx(int* x, int* y)
{ {
int t; int t;

t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;

printf("x=%d y=%d\n", x, y); printf("x=%d y=%d\n", *x, *y)


} }

Output: Output:
x=20 y=10 x=20 y=10
a=10 b=20 a=20 b=10

93
BCA 1st Sem ( Programming In C)

Thus actual values of a and b remain Thus actual values of a and b get

unchanged even after exchanging changed after exchanging values of x

thevalues of x and y. and y.

In call by values we cannot alter In call by reference we can alter

thevalues of actual variables the values of variables through

through function calls. functioncalls.

Pointer variables are necessary to

Values of variables are passes by define to store the address values of

Simple technique. variables.

Syntax Syntax

Returntype Returntype

functioname(parameterlist) functioname(*parameterlist)

{ {

Body; Body;

} }

Recursion
What is Recursion?

94
BCA 1st Sem ( Programming In C)

The process in which a function calls itself directly or indirectly is called


recursion and the corresponding function is called as recursive function.
Usingrecursive algorithm, certain problems can be solved quite easily
What is base condition in recursion?
In the recursive program, the solution to the base case is provided and
the solution of the bigger problem is expressed in terms of smaller
problems.#include <stdio.h>
/* Function declaration */
void printNaturalNumbers(int lowerLimit, int upperLimit);0
int main()
{
int lowerLimit, upperLimit;

/* Input lower and upper limit from user


*/printf("Enter lower limit: ");
scanf("%d", &lowerLimit);
printf("Enter upper limit: ");
scanf("%d", &upperLimit);

printf("All natural numbers from %d to %d are: ", lowerLimit, upperLimit);


printNaturalNumbers(lowerLimit, upperLimit);

return 0;
}
/**
* Recursively prints all natural number between the given range.
*/
void printNaturalNumbers(int lowerLimit, int upperLimit)

95
BCA 1st Sem ( Programming In C)

{
if(lowerLimit > upperLimit)
return;

printf("%d, ", lowerLimit);

// Recursively call the function to print next number


printNaturalNumbers(lowerLimit + 1, upperLimit);
}
Diffrence between Recursion and Iteration
Iteration Recursion
Allows the execution of a sequential A statement in the function’s
set of statements repetitively using bodycalls the function itself.
conditional loops.
There are loops with a control A recursive function must comprise
variable that need to be initialized, of at least one base case i.e. a
incremented or decremented and condition for termination of
a conditional control statement that execution.
continuously gets checked for
the termination of execution.
The value of the control variable The function keeps on converging
continuously approaches the value tothe defined base case as
inthe conditional statement. it continuously calls itself.
A control variable stores the value, Stack memory is used to store
which is then updated, monitored, thecurrent state of the function.
and
compared with the
conditionalstatement.
Infinite loops keep utilizing CPU If there is no base case defined,
cycles until we stop their recursion causes a stack
execution overflow
manually. error.
The execution of iteration is The execution of recursion is
comparatively faster. comparatively slower.

96
BCA 1st Sem ( Programming In C)

Arrays: Defining, processing arrays, passing arrays to a function, multi–


dimensional arrays.
1. Array:Arrays a kind of data structure that can store a fixed-size sequential
collection of elements of the same type. An array is used to store a collection
ofdata, but it is often more useful to think of an array as a collection of
variables of the same type.
Types of Arrays in C

There are three type of array in C language:

 One dimensional array:


 Two dimensional array:
 Multi– dimensional arrays:

 One dimensional array:


o Single or One Dimensional array is used to represent and store data
ina linear form.
o Array having only one subscript variable is called One-Dimensional
97
BCA 1st Sem ( Programming In C)

array
o It is also called as Single Dimensional Array or Linear Array

Syntax
Datatype arrayname[size];

Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer


constant greater than zero and type can be any valid C data type. For example,
todeclare a 10-element array called balance of type double, use this statement

double balance[10];

Here balance is a variable array which is sufficient to hold up to 10 double


numbers.

Initializing Arrays
98
BCA 1st Sem ( Programming In C)

You can initialize an array in C either one by one or using a single statement as
follows −

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

The number of values between braces { } cannot be larger than the number
ofelements that we declare for the array between square brackets [ ].

Example of storing elements into array

#include<stdio.h>
void main()
{
int a[5];
int i;
printf(“enter the number atleast
5\n”);for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}
printf(“elements you enter
are\n”);for(i=0;i<5;i++)
{
printf(“%d\n”,a[i]);
}}

Output
enter the number atleast
510 20 30 40 50
elements you enter
are10
20
99
BCA 1st Sem ( Programming In C)

30
40
50
 Two dimensional array:
o Array having more than one subscript variable is called Multi-
dimensional array.
o Multi Dimensional Array is also called as Matrix.

Declaration of 2D Array

While declaring the 2D Array there are two subscript values.

Syntax:

Datatype Arrayname[rowsize][columnsize];

100
BCA 1st Sem ( Programming In C)

Initialization of 2D Array

There are two ways to initialize a two Dimensional arrays during declaration.

int disp[2][4] = {

{10, 11, 12, 13},

{14, 15, 16, 17}

};

Example of 2D Array

#include<stdio.h>
int main()

/* 2D array

declaration*/int

disp[2][3];

/*Counter variables for the

loop*/int i, j;

for(i=0; i<2; i++) {

for(j=0;j<3;j++) {

printf("Enter value for disp[%d][%d]:", i, j);

scanf("%d", &disp[i][j]);

101
BCA 1st Sem ( Programming In C)

//Displaying array elements

printf("Two Dimensional array

elements:\n");for(i=0; i<2; i++) {

for(j=0;j<3;j++) {

printf("%d ", disp[i][j]);

if(j==2){

printf("\n");

}
return 0;

Output:

Enter value for disp[0][0]:1

Enter value for disp[0][1]:2

Enter value for disp[0][2]:3

Enter value for disp[1][0]:4

Enter value for disp[1][1]:5

Enter value for disp[1][2]:6

102
BCA 1st Sem ( Programming In C)

Two Dimensional array elements:

123

456

 Multi– dimensional arrays:In C, we can define multidimensional arrays in


simple words as array of arrays. Data in multidimensional arrays are stored in
tabular form (in row major order).

General form of declaring N-dimensional arrays:

data_type array_name[size1][size2] .. [sizeN];

data_type: Type of data to be stored in the array.

Here data_type is valid Cdata type

array_name: Name of the array

size1, size2,. .. ,sizeN: Sizes of the dimensions

Examples:
Two dimensional array:

int two_d[10][20];

Three dimensional array:

int three_d[10][20][30];

103
BCA 1st Sem ( Programming In C)

Initializing Three-Dimensional Array: Initialization in Three-Dimensional arrayis


same as that of Two-dimensional arrays. The difference is as the number of
dimension increases so the number of nested braces will also increase.
Method 1:

int x[2][3][4] =

{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },

{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }

};

// C program to print elements of Three-Dimensional

// Array
104
BCA 1st Sem ( Programming In C)

#include<stdio.h>

int main()

// initializing the 3-dimensional

arrayint x[2][3][2] =

{ {0,1}, {2,3}, {4,5} },

{ {6,7}, {8,9}, {10,11} }

};

// output each element's

valuefor (int i = 0; i < 2; ++i)

for (int j = 0; j < 3; ++j)

for (int k = 0; k < 2; ++k)

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

105
BCA 1st Sem ( Programming In C)

printf(“\n”);

return 0;

Passing arrays to a function:

Passing a single element of an array to a function is similar to passing


variableto a function.

Example

// Program to calculate average by passing an array to a function

#include <stdio.h>

float average(float

age[]);float average(float

age[])

int i;

float avg, sum = 0.0;


106
BCA 1st Sem ( Programming In C)

for (i = 0; i < 6; ++i) {

sum += age[i];

avg = (sum / 6);

return avg;

int main()

float avg, age[] = {23.4, 55, 22.6, 3, 40.5, 18};

avg = average(age); // Only name of an array is passed as an

argumentprintf("Average age = %.2f", avg);

return 0;

Output

Average age = 27.08

Advantages of Arrays

 It is better and convenient way of storing the data of same datatype


107
BCA 1st Sem ( Programming In C)

withsame size.

 It allows us to store known number of elements in it.

 It allocates memory in contiguous memory locations for its elements. It


doesnot allocate any extra space/ memory for its elements. Hence there is
no memory overflow or shortage of memory in arrays.

 Iterating the arrays using their index is faster compared to any other
methodslike linked list etc.

 It allows to store the elements in any dimensional array -


supportsmultidimensional array.

Disadvantages of Arrays
 It allows us to enter only fixed number of elements into it. We cannot
alter the size of the array once array is declared. Hence if we need to
insert morenumber of records than declared then it is not possible. We
should know array size at the compile time itself.

 Inserting and deleting the records from the array would be costly since
we add / delete the elements from the array, we need to manage
memory spacetoo.
 It does not verify the indexes while compiling the array. In case there is any
indexes pointed which is more than the dimension specified, then we will
getrun time errors rather than identifying them at compile time.
Strings: String declaration, string functions and string manipulation Program
Structure Storage Class: Automatic, external and static variables.

1. String:Strings are defined as an array of characters. The difference between a


character array and a string is the string is terminated with a special character
108
BCA 1st Sem ( Programming In C)

‘\0’.

int a[3];

 Declaration of strings: Declaring a string is as simple as declaring a one


dimensional array. Below is the basic syntax for declaring a string.

char str_name[size]; char name[10]={‘L’,’U’,’D’,’H’,’I’,’A’,’N’,’A’}

Initializing a String: A string can be initialized in different ways. We will explainthis


with the help of an example.

char name[5]={‘R’,’A’,’H’,’U’,’L’};

// C program to illustrate strings

#include<stdio.h>

int main()

// declare and initialize string

char name[5]={‘R’,’A’,’H’,’U’,’L’};

// print string

printf("%c",str);

return 0;

Output:
109
BCA 1st Sem ( Programming In C)

RAHUL

Second way to use String

// C program to illustrate strings

#include<stdio.h>

int main()

// declare and initialize

stringchar

name[5]=”RAHUL”;

// print string

printf("%s",str);

return 0;

Output:

RAHUL

Here (“ “)Double quotes is used while initializing the string instead of(‘‘)Single
quotes.

110
BCA 1st Sem ( Programming In C)

 String Manipulations In C Programming Using Library Functions

To use String Handling function “string.h” Header file is use

The list ofLibrary Functions is given below

Function Work of Function

strlen() Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings

strcmp() Compares two string

strlwr() Converts string to lowercase

strupr() Converts string to uppercase

1) strlen():The function takes a single argument, i.e, the string variable


whoselength is to be found, and returns the length of the string passed.

Syntax:
size_t strlen(const char *str);

111
BCA 1st Sem ( Programming In C)

Example:

#include <stdio.h>

#include <string.h>

int main()

char a[20];

printf("Enter string: ");

gets(c);

printf("Length of

string a = %d

\n",strlen(a));

return 0;

Output

Enter string: rahul


Length of string a = 5

2) strcpy():The strcpy() function copies the string pointed by source (including the
null character) to the character array [Link] function returns character
array destination.

Syntax:

112
BCA 1st Sem ( Programming In C)

char* strcpy(char* destination, const char* source);

Example

#include <stdio.h>

#include <string.h>

int main()

char str1[10]=

"awesome";char str2[10];

strcpy(str2, str1);

printf(“str2= %s”,str2);

return 0;

Output
str2=awesome

3) strcat():It takes two arguments, i.e, two strings or character arrays, and
storesthe resultant concatenated string in the first string specified in the
argument.
113
BCA 1st Sem ( Programming In C)

Syntax

char *strcat(char *dest, const char *src)

Example:

#include <stdio.h>

#include <string.h>

int main()

char str1[5] = "rahul";

char str2[6] = "sharma";

printf(“old string is = %s”,str1);

strcat(str1,str2);

printf(“new string is =%s”,str1);

return 0;

Output:

old string is = rahul

new string is =rahulsharma

4) strcmp():The strcmp() function takes two strings and return an integer.

114
BCA 1st Sem ( Programming In C)

The strcmp() compares two strings character by character. If the first character of
two strings are equal, next character of two strings are compared. This continues
until the corresponding characters of two strings are different or a null character
'\0'is reached.

Return Value from strcmp()

Return Value Remarks

0 if both strings are identical (equal)

if the ASCII value of first unmatched character is less than


negative
second.

positive if the ASCII value of first unmatched character is greater than


integer second.

Example: C strcmp() function

#include <stdio.h>

#include <string.h>

int main()

char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";

int result;

// comparing strings str1 and

str2result = strcmp(str1, str2);

printf("strcmp(str1, str2) = %d\n", result);


115
BCA 1st Sem ( Programming In C)

// comparing strings str1 and str3


result = strcmp(str1, str3);

printf("strcmp(str1, str3) = %d\n",

result);return 0;

Output

strcmp(str1, str2) =

32strcmp(str1, str3) =

The first unmatched character between string str1 and str2 is third
[Link] ASCII value of 'c' is 99 and the ASCII value of 'C' is 67. Hence,
when strings str1 and str2 are compared, the return value is 32.

When strings str1 and str3 are compared, the result is 0 because both strings
areidentical.

5) strupr():The strupr( ) function is used to converts a given string to uppercase.

Syntax:

char *strupr(char *str);

Example:

// c program to demonstrate

// example of strupr()

function.#include<stdio.h>

#include<string.h>

int main()

{
116
BCA 1st Sem ( Programming In C)

char str[ 5] = "hello";

printf("%s\n", strupr

(str));

return 0;

Output:

HELLO

6) strlwr():The strlwr( ) function is used to converts a given string to lowercase.

Syntax:

char *strlwr(char *str);

Example:

// c program to demonstrate

// example of strlwr()

function.#include<stdio.h>

#include<string.h>

int main()

char str[ 5] = "HELLO";

printf("%s\n", strlwr (str));

return 0;

117
BCA 1st Sem ( Programming In C)

Output:

hello

 Structure Storage Class: Automatic, external and static variables

Structure Storage Class:


Storage Classes are used to describe the features of a variable/function. These
features basically include the scope, visibility and life-time which help us to
tracethe existence of a particular variable during the runtime of a program.

1) auto :This is the default storage class for all the variables declared inside a
function or a block. Hence, the keyword auto is rarely used while writing
programsin C language. Auto variables can be only accessed within the
block/function they have been declared and not outside them (which defines
their scope).
118
BCA 1st Sem ( Programming In C)

Syntax

auto datatype variablename;

Example:

#include <stdio.h>

void main()

{
auto int a = 32;

printf("Value of the variable adeclared as auto: %d\n", a);

Output

Value of the variable a declared as auto:32

2) extern :Extern storage class simply tells us that the variable is defined
elsewhereand not within the same block where it is used. Basically, the value is
assigned to itin a different block and this can be overwritten/changed in a
different block as well. Hence, the keyword extern is rarely used while writing
programs in C language.

Syntax

extern datatype variablename;

Example:

#include <stdio.h>

void main()
119
BCA 1st Sem ( Programming In C)

extern int a ;

printf("Value of the variable a declared as extern: %d\n", a);

a=34;

printf("Value of the variable adeclared as extern: %d\n", a);

}
Output

Value of the variable adeclared as extern:0

Value of the variable adeclared as extern:34

3) static:This storage class is used to declare static variables which are popularly
used while writing programs in C language. Static variables have a property of
preserving their value even after they are out of their scope! Hence, static
variablespreserve the value of their last use in their scope. So we can say that
they are initialized only once and exist till the termination of the program. Hence,
the keyword static is rarely used while writing programs in C language.

Syntax

static datatype variablename;

Example:

#include <stdio.h>

static int a=10;

void main()

120
BCA 1st Sem ( Programming In C)

static int b=20 ;

printf("value of a %d”,a);

printf("value of b %d”,b);

Output

value of a10

value of b20

4) register: This storage class declares register variables which have the same
functionality as that of the auto variables. The only difference is that the compiler
tries to store these variables in the register of the microprocessor if a free register
[Link] makes the use of register variables to be much faster than that of
thevariables stored in the memory during the runtime of the program. If a free
registeris not available, these are then stored in the memory only.

Syntax:

storage_class var_data_type

var_name;#include <stdio.h>

void main()

register int b=20 ;

printf("value of a %d”,a);

printf("value of b %d”,b);
121
BCA 1st Sem ( Programming In C)

Output

value of b20

122
BCA 1st Sem ( Programming In C)

UNIT -IV

 Structures
A structure is a user defined data type in C. A structure creates a data type that
canbe used to group items of possibly different types into a single type.

‘struct’ keyword is used to create a structure.

Declaration of Structure

A structure variable can either be declared with structure declaration or as


aseparate declaration like basic types.

Syntax

struct structurename

Datatype

variablename1;Datatype

variablename2;

Datatype variablename n;

Following is an example.

struct address

123
BCA 1st Sem ( Programming In C)

char name[50];

char

street[100];char

city[50]; char

state[20]; int

pin;

};
Initialization of Structure

Structure members cannot be initialized with declaration. For example the


following C program fails in [Link] always initialize into main() and user
define() by using the object of structure.

Syntax

Struct structurename objectname;

access structure elements

Structure members are accessed using dot (.) operator.

Syntax

[Link]=value;

Example

#include<stdio.h>

struct student

int rollno;

char name[20];

124
BCA 1st Sem ( Programming In C)

};

void main()

struct student obj; //declaring structure

objectprintf(“enter rollno and name\n”);

scanf(“%d%s”,&[Link],&[Link]);

printf(“ rollno is %d \n”,[Link]);

printf(“ name is %s \n”,[Link]);


}

Output

enter rollno and

name23 rahul

rollno is 23

name is

rahul

2) Array of Structure : Array of structures in C can be defined as the collection of


multiple structures variables where each variable contains information about
different entities. The array of structures in C are used to store information about
multiple entities of different data types. The array of structures is also known as
thecollection of structures.

125
BCA 1st Sem ( Programming In C)

Syntax

Struct structurename objectname[size];

Example
#include<stdio.h>

#include <string.h>

struct student{

int rollno;

char name[10];

};

int main(){

int i;

struct student st[5];


126
BCA 1st Sem ( Programming In C)

printf("Enter Records of 5 students");

for(i=0;i<5;i++){

printf("\nEnter Rollno:");

scanf("%d",&st[i].rollno);

printf("\nEnter Name:");

scanf("%s",&st[i].name);

printf("\nStudent Information List:");

for(i=0;i<5;i++){

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);

return 0;

Output:
Enter Records of 5

studentsEnter Rollno:1

Enter Name:Sonoo

Enter Rollno:2

Enter Name:Ratan

Enter Rollno:3

Enter Name:Vimal

Enter Rollno:4

127
BCA 1st Sem ( Programming In C)

Enter Name:James

Enter Rollno:5

Enter Name:Sarfraz

Student Information List:

Rollno:1, Name:Sonoo

Rollno:2, Name:Ratan

Rollno:3, Name:Vimal

Rollno:4, Name:James

Rollno:5, Name:Sarfraz

 Passing structure to function


 A structure can be passed to any function from main function or from
anysub function.
 Structure definition will be available within the function only.
 It won’t be available to other functions unless it is passed to those
functionsby value or by address(reference).

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

struct student
{
int id;

float percentage;
};

void func(struct student record);

128
BCA 1st Sem ( Programming In C)

void func(struct student record)


{
printf(" Id is: %d \n", [Link]);

printf(" Percentage is: %f \n", [Link]);


}

int main()
{
struct student record;

[Link]=1;
[Link] =
86.5;

func(record);
return 0;
}

Outpu
tId is:
1
Percentage is: 86.500000

 Structure using Pointer


Dot(.) operator is used to access the data using normal structure variable and
arrow(->) is used to access the data using pointer variable.

Syntax:
Objectname->variablename=value;

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

struct student
129
BCA 1st Sem ( Programming In C)

{
int id;
char name[30];
float
percentage;
};

int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);

return 0;
}

Output
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is:
90.500000

 Union

Like Structures, union is a user defined data type. In union, all members share
thesame memory location.

130
BCA 1st Sem ( Programming In C)

A union is a special data type available in C that allows to store different data
typesin the same memory location. You can define a union with many members,
but only one member can contain a value at any given time
How is the size of union decided by compiler?
Size of a union is taken according the size of largest member in [Link] Union
keyword is used to declare the unions in C.

Syntax

union structurename

Datatype

variablename1;Datatype

variablename2;

Datatype variablename n;

};

Example

#include<stdio.h>

union student

int rollno;

char name[20];

};

131
BCA 1st Sem ( Programming In C)

void main()

{
struct student obj; //declaring structure

objectprintf(“enter rollno and name\n”);

scanf(“%d%s”,&[Link],&[Link]);

printf(“ rollno is %d \n”,[Link]);

printf(“ name is %s \n”,[Link]);


}
BASIS OF
COMPARISON STRUCTURE UNION

Basic The separate memory location All members of the


isallotted to each member of 'union' share the
the 'structure'. samememory
location.
Declaration struct union
struct_name{type u_name{ type
element1; type element1;
element2; type
. element2;
. .
} variable1, variable2, ...; .
} variable1, variable2,
...;
keyword 'struct' 'union'

Size Size of Structure= sum of size of Size of Union=size of


all the data members. the largest members.

Store Value Stores distinct values for all Stores same value for all
themembers. the members.

At a Time A 'structure' stores multiple A 'union' stores a single


values, of the different value at a time for all
members,of the 'structure'. members.
132
BCA 1st Sem ( Programming In C)

Pointers: Understanding Pointers, Accessing the Address of a Variable,


Declaration and Initialization of Pointer Variables, Accessing a Variable through
its Pointer, Pointers and Arrays

 Pointers
Pointer variable must be declared before using it as we know in C Programming
Language, every variable must be declared before using. Generally if we declare
aninteger type variable that hold a unique memory address from the computer
system, we do it in C like below:

Int Variable_name;
Similarly, we can declare a pointer variable but adding an asterisk ('*' sign)
afterdata type and before variable name. For that there are three type of
pointer declaration style in C. They are:

1. int* variable_name;
2. int * variable_name;
3. int *variable_name;

The pointer in C language is a variable which stores the address of another


variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. However, in 32-
bitarchitecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of
aninteger.
1. int n = 10;
2. int* p = &n;

 Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also
known as indirection pointer used to dereference a pointer.
1. int *a;//pointer to int
2. char *c;//pointer to char

 Initializing a pointer
To initialize the pointer variable &(Address Operator )is used.
int* p = &n;

133
BCA 1st Sem ( Programming In C)

 Accessing a Variable through its Pointer


#include <stdio.h>
int main()
{
int *ptr,
q;q = 50;
/* address of q is assigned to ptr
*/ptr = &q;
/* display q's value using ptr variable
*/printf("%d", *ptr);
printf("%u", ptr);

return 0;
}

Outpu
t50
4104

Accessing a Variable without Pointer

#include <stdio.h>
int main()
{
int q;
q = 50;

printf("%u",&q);

return 0;
}

Outpu
t50
4104

134
BCA 1st Sem ( Programming In C)

 Pointer and Arrays When an array is declared, compiler allocates sufficient


amount of memory to contain all the elements of the array. Base address i.e
address of the first element ofthe array is also allocated by the compiler.
Suppose we declare an array
arr,int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two
bytes,the five elements will be stored as follows:

Here variable arr will give the base address, which is a constant pointer pointing
tothe first element of the array, arr[0]. Hence arr contains the address
of arr[0] i.e 1000. In short, arr has two purpose - it is the name of the array and
itacts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array
[Link] *p;
p = arr;
// or,
p = &arr[0];

 Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use
that pointer to access the array elements. Let’s have an example,

#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p =
&a[0]for (i = 0; i < 5; i++)
135
BCA 1st Sem ( Programming In C)

{
printf("%d \t", *p);
printf("address is %u:\n", p);
p++;
}

return 0;
}
Output
1 address is :1000
2 address is :1001
3 address is :1002
4 address is :1003
5 address is :1004

Topic-3:
File Handling: File Operations, Processing a Data File.

 Why files are needed?


 When a program is terminated, the entire data is lost. Storing in a file
willpreserve your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to
enterthem all.
However, if you have a file containing all the data, you can easily access the
contents of the file using few commands in C.
 You can easily move your data from one computer to another without
anychanges.

 Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
When you open those files, you'll see all the contents within the file as plain text.
136
BCA 1st Sem ( Programming In C)

You can easily edit or delete the contents.


They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.
2. Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a
bettersecurity than text files.

 File Handling in C
In programming, we may require some specific input data to be generated
severalnumbers of times. Sometimes, it is not enough to only display the data on
the console. The data to be displayed may be very large, and only a limited
amount ofdata can be displayed on the console, and since the memory is volatile,
it is impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which
is volatile and can be accessed every time. Here, comes the need of file
handling inC.
File handling in C enables us to create, update, read, and delete the files stored
onthe local file system through our C program. The following operations can be
performed on a file.
o Creation of the new file
o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file
 File Operations

Mode Description

r opens a text file in read mode


w opens a text file in write mode
a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode


a+ opens a text file in read and write mode

137
BCA 1st Sem ( Programming In C)

 Functions for file handling/ Processing a data file

There are many functions in the C library to open, read, write, search and close
thefile. A list of file functions are given below:
No. Function Description

1 fopen() opens new or existing file


2 fprintf() write data into the file

3 fscanf() reads data from the file


4 fputc() writes a character into
thefile
5 fgetc() reads a character from file
6 fclose() closes the file
8 fputw() writes an integer to file

9 fgetw() reads an integer from file


10 ftell() returns current position
11 rewind() sets the file pointer to
thebeginning of the file

1) Opening File: fopen()


We must open a file before it can be read, write, or update. The fopen() function
isused to open a file.
The syntax of the fopen() is given below.
1. FILE *fopen( const char * filename, const char * mode );
The fopen() function accepts two parameters:
o The file name (string). If the file is stored at some specific location, then
wemust mention the path at which the file is stored. For example, a file
name can be like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.

138
BCA 1st Sem ( Programming In C)

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode


a opens a text file in append mode

r+ opens a text file in read and write mode


w+ opens a text file in read and write mode
a+ opens a text file in read and write mode

The fopen function works in the following way.


o Firstly, It searches the file to be opened.
o Then, it loads the file from the disk and place it into the buffer. The buffer
isused to provide efficiency for the read operations.
o It sets up a character pointer which points to the first character of the
[Link] the following example which opens a file in write mode.
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Output
The content of the file will be printed.
#include;
139
BCA 1st Sem ( Programming In C)

void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}

fclose (fp );
}
2) Closing File: fclose()
The fclose() function is used to close a file. The file must be closed after
performing all the operations on it.
The syntax of fclose() function is given below:
1. int fclose( FILE *fp );

3) fprintf():The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.

Syntax:
1. int fprintf(FILE *stream, const char *format [, argument, ...])

Example:

#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("[Link]", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}

140
BCA 1st Sem ( Programming In C)

4) fscanf():The fscanf() function is used to read set of characters from file. It


readsa word from the file and returns EOF at the end of file.
Syntax:
1. int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main()
{
FILE *fp;
char buff[255];//creating char array to store data of
filefp = fopen("[Link]", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Output:
Hello file by fprintf...

5) fgetc():fgetc() is used to obtain input from a file single character at a time.


Thisfunction returns the number of characters read by the function. It returns
the character present at position indicated by file pointer.

Syntax:
int fgetc(FILE *pointer)
pointer: pointer to a FILE object that identifies
the stream on which the operation is to be performed.

// C program to illustate fgetc() function


#include <stdio.h>

int main ()
{
// open the file
FILE *fp = fopen("[Link]","r");

// Return if could not open


fileif (fp == NULL)
return 0;
141
BCA 1st Sem ( Programming In C)

do
{
// Taking input single character at a time
char c = fgetc(fp);
// Checking for end of file
if (feof(fp))
break ;

printf("%c", c);
} while(1);

fclose(fp);
return(0);
}
Output:
The entire content of file is printed character by
character till end of file. It reads newline
characteras well.

5)fputc():fputc() is used to write a single character at a time to a given file. It


writes the given character at the position denoted by the file pointer and
thenadvances the file pointer.
This function returns the character that is written in case of successful
writeoperation else in case of error EOF is returned.
Syntax:

int fputc(int char, FILE *pointer)

char: character to be written.

This is passed as its int promotion.

pointer: pointer to a FILE object that identifies the

stream where the character is to be written.

Example:

142
BCA 1st Sem ( Programming In C)

#include <stdio.h>
int main () {

FILE *fp;

int ch;

fp = fopen("[Link]", "w+");

for( ch = 33 ; ch <= 100; ch++ )

fputc(ch, fp);

fclose(fp);

return(0);

143

You might also like