Data Representation and Flowcharts Guide
Data Representation and Flowcharts Guide
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.
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.
Flowchart
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
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".
5
Flow Chart compare two number
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
3. Flow Chart
4. Program Coding
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
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
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.
10
Below are some assumptions that we made while using decision tree:
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
Start Program
Enter two number A,B
Add the number
togetherPrint add
End program
Now, let's look at a few more simple examples of pseudo code. Here is
apseudocode to compute the area of a rectangle:
Advantages of Pseudocode
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
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
Advantages of Algorithms:
Disadvantages of Algorithms:
Characteristics of Algorithms:
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
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.
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,
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 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.
What is a 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:
height or HEIGHT
_height
_height1
My_name
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:
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
2. Octal constant contains digits from 0-7, and these types of constants
arealways preceded by 0.
The octal and hexadecimal integer constants are very rarely used in programming
with 'C'.
22
II. Character 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
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.
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
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:
25
Size in
Data type Range
bytes
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.
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.
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.
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;
A void data type doesn't contain or return any value. It is mostly used for defining
functions in 'C'.
Example,
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).
29
values.
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
* multiplication
/ division
// 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
== Equal to 5 == 3 is evaluated to 0
1. // Working of relational
operators#include<stdio.h>
int main()
32
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
#include<stdio.h>
int main()
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
35
IV. C Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
V. Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
1. int a, c =5, d;
The sizeof is a unary operator that returns the size of data (constants, variables,
array, structure, etc).
#include<stdio.h>
36
int main()
int a;
float b;
double c;
char d;
return0;
Output
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.
#include<stdio.h>
int main()
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 =
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Conditional Operator
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.
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
C Header Files
42
UNIT-II
Formatted & Unformatted input output
I. getchar()
II. putchar()
III. getch()
IV. putch()
V. gets()
VI. puts()
VII. prinf()
VIII. scanf()
#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
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
);
o }
i Enter the
d string: Use
of data!
m Entered
a string: Use
i of data!
n puts()
( :This
) function
{ prints the
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("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 }
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:
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 }
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:
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 }
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 ) {
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
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
Block;
Example
#include <stdio.h>
int main ()
int 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
81
BCA 1st Sem ( Programming In C)
UNIT-III
Function
Syntax
Syntax
Returntype Functionname(parameterlist)
Statements;
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.
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
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);
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);
{
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;
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 */
}
int main() /* Main function */
{
int a1 = 10;
int b1 = 20;
91
BCA 1st Sem ( Programming In C)
as “Call By References.
function.
madeto the dummy variables in the With this method, using addresses
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;
} }
t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;
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
Syntax Syntax
Returntype Returntype
functioname(parameterlist) functioname(*parameterlist)
{ {
Body; Body;
} }
Recursion
What is Recursion?
94
BCA 1st Sem ( Programming In C)
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;
96
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 −
double balance[10];
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 −
The number of values between braces { } cannot be larger than the number
ofelements that we declare for the array between square brackets [ ].
#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
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] = {
};
Example of 2D Array
#include<stdio.h>
int main()
/* 2D array
declaration*/int
disp[2][3];
loop*/int i, j;
for(j=0;j<3;j++) {
scanf("%d", &disp[i][j]);
101
BCA 1st Sem ( Programming In C)
for(j=0;j<3;j++) {
if(j==2){
printf("\n");
}
return 0;
Output:
102
BCA 1st Sem ( Programming In C)
123
456
Examples:
Two dimensional array:
int two_d[10][20];
int three_d[10][20][30];
103
BCA 1st Sem ( Programming In C)
int x[2][3][4] =
};
// Array
104
BCA 1st Sem ( Programming In C)
#include<stdio.h>
int main()
arrayint x[2][3][2] =
};
printf(“%d”, x[i][j][k]);
105
BCA 1st Sem ( Programming In C)
printf(“\n”);
return 0;
Example
#include <stdio.h>
float average(float
age[]);float average(float
age[])
int i;
sum += age[i];
return avg;
int main()
return 0;
Output
Advantages of Arrays
withsame size.
Iterating the arrays using their index is faster compared to any other
methodslike linked list etc.
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.
‘\0’.
int a[3];
char name[5]={‘R’,’A’,’H’,’U’,’L’};
#include<stdio.h>
int main()
char name[5]={‘R’,’A’,’H’,’U’,’L’};
// print string
printf("%c",str);
return 0;
Output:
109
BCA 1st Sem ( Programming In C)
RAHUL
#include<stdio.h>
int main()
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)
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];
gets(c);
printf("Length of
string a = %d
\n",strlen(a));
return 0;
Output
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)
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
Example:
#include <stdio.h>
#include <string.h>
int main()
strcat(str1,str2);
return 0;
Output:
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.
#include <stdio.h>
#include <string.h>
int main()
int result;
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.
Syntax:
Example:
// c program to demonstrate
// example of strupr()
function.#include<stdio.h>
#include<string.h>
int main()
{
116
BCA 1st Sem ( Programming In C)
printf("%s\n", strupr
(str));
return 0;
Output:
HELLO
Syntax:
Example:
// c program to demonstrate
// example of strlwr()
function.#include<stdio.h>
#include<string.h>
int main()
return 0;
117
BCA 1st Sem ( Programming In C)
Output:
hello
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
Example:
#include <stdio.h>
void main()
{
auto int a = 32;
Output
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
Example:
#include <stdio.h>
void main()
119
BCA 1st Sem ( Programming In C)
extern int a ;
a=34;
}
Output
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
Example:
#include <stdio.h>
void main()
120
BCA 1st Sem ( Programming In C)
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()
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.
Declaration of Structure
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
Syntax
Syntax
[Link]=value;
Example
#include<stdio.h>
struct student
int rollno;
char name[20];
124
BCA 1st Sem ( Programming In C)
};
void main()
scanf(“%d%s”,&[Link],&[Link]);
Output
name23 rahul
rollno is 23
name is
rahul
125
BCA 1st Sem ( Programming In C)
Syntax
Example
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
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
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
#include <stdio.h>
#include <string.h>
struct student
{
int id;
float percentage;
};
128
BCA 1st Sem ( Programming In C)
int main()
{
struct student record;
[Link]=1;
[Link] =
86.5;
func(record);
return 0;
}
Outpu
tId is:
1
Percentage is: 86.500000
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;
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
scanf(“%d%s”,&[Link],&[Link]);
Store Value Stores distinct values for all Stores same value for all
themembers. the members.
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;
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)
return 0;
}
Outpu
t50
4104
#include <stdio.h>
int main()
{
int q;
q = 50;
printf("%u",&q);
return 0;
}
Outpu
t50
4104
134
BCA 1st Sem ( Programming In C)
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.
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)
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
137
BCA 1st Sem ( Programming In C)
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
138
BCA 1st Sem ( Programming In C)
Mode Description
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)
Syntax:
int fgetc(FILE *pointer)
pointer: pointer to a FILE object that identifies
the stream on which the operation is to be performed.
int main ()
{
// open the file
FILE *fp = fopen("[Link]","r");
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.
Example:
142
BCA 1st Sem ( Programming In C)
#include <stdio.h>
int main () {
FILE *fp;
int ch;
fp = fopen("[Link]", "w+");
fputc(ch, fp);
fclose(fp);
return(0);
143