BCA2B02-Problem Solving Using C (4)
BCA2B02-Problem Solving Using C (4)
PROGRAMMING LANGUAGES
A computer language is used to make a computer understand what the
user wants to say. When a user writes a program, programmer uses
programming language.
Programming Languages
2
High-Level Languages
Machine Language
TRANSLATORS
o COMPILER
o INTERPRETER
o ASSEMBLER
Compiler
Interpreter
HISTORY OF C
C is a High-level , structured, machine independent programming
language. In 1972 , the “Traditional C” language was developed by Dennis
Ritche. It allows software developers to develop programs without worrying
about the machine type instruction. It allows so many facilities to programmers. By
the use of C language, the calculation process became easy.
IMPORTANCE OF C
1. Robust Language
2. Efficient and Fast
3. Built-in Functions
4. Portable
5. Structured Programming
6. Extend itself
Robust Language
Programs written in C are fast and efficient. This is due to verity of data type
and powerful operators. It is many faster than other programming languages like
BASIC, COBOL etc.
Built-in Functions
Portable
This means that programs written for one computer can be run on another
without any modification.
4
Structured Programming
The entire program can be divided into function blocks or modules. A proper
collection of these modules would make a complete program. This modular
structure makes program debugging, testing and maintenance easier.
Testing: The process of executing a program with the intent of finding errors.
Extend Itself
C LIBRARY
It is just like a standard library. But here hold functions rather than books. So many
built-in functions are available in C library. We can include desired functions to
our C program by calling the specified function with its header file.
STRUCTURE OF C PROGRAM
Documentation Section
Link Section
Definition Section
Global Declaration Section
main() Function Section
{
5
Declaration Part
Executable Part
}
Subprogram Section
Function1
Function2
Function3 (User Defined Functions)
…………..
……………
Function n
1) Documentation Section
It consist of comment lines giving the name of program, author name,
other details and also can include points in middle of program.
2) Link Section
6
Eg: #include<stdio.h>
3) Definition Section
It defines all symbolic constants.
Eg: pi=3.14
4) Global Declaration Section
There are some variables that are used in more than one function.
Such variables are called global variables and that are declared in global
declaration section.
Every C program must have one main( ) function section. The program’s
execution is starting from this main ( ) function.
It contains 2 parts.
a) Declaration Part
It declares all the variables that are used in the program.
b) Executable Part
CHARACTER SET
7
The character set that can be used to form words, numbers and
expressions depends upon the program. The character set in C can be classified
to the following categories.
1. Letters
2. Digits
3. Special Characters
4. White Spaces
Letters
C language supports all the alphabets from the English language. Lower and
upper case letters together support 52 alphabets.
lowercase letters - a to z UPPER CASE LETTERS - A to Z
Digits
Horizontal Tab, newline space, blank space …. are considered to white spaces
C TOKENS
8
Keywords
All keywords in C programming have fixed meanings and these meaning
cannot be changed. Keywords serve as basic building blocks for program
statements. All keywords must be written in lowercase.
Identifier
Identifiers are used for naming purposes. It refers to the names of variable,
functions and arrays. It consists of letters, digits and underscore ( _ ). Both
uppercase and lowercase are permitted, both are distinct.
STRINGS
SPECIAL CHARACTERS
❏ Special characters or punctuators in c are used to separate individual parts ina program.
OPERATORS
Operators are symbols that are used to represent a mathematical calculation orlogical
comparison.
5+9
X+Y
m>n
10
CONSTANTS
Constants in Java refer to fixed values that do not change during the
execution of a program.
Integer Constants
Eg: 89,-55,0,66,-586
11
Real Constants
Eg:
12.36
-986.65
0.35
Note: White spaces, commas or any other special symbols are not
allowed innumerical constants.
String Constants
Eg:
“hii”
“566”
“Vatakara”
ESCAPE SEQUENCE
An escape sequence in C language is a sequence of characters that doesn't represent itself
when used inside string literal or character.
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\? Question Mark
\0 Null
13
DATA TYPES
As its name indicates, a data type represents type of the data which you
can process using your computer program. Data types specify how we enter data
into our programs and what type of data we enter. The type of a data item
determines how much space it occupies in storage and what operations should be
performed on that item. “Data type defines character and required memory space
of a data item.”
MARK 1 : 86 : Number(Integer)
The C programming language supports almost every type of data. They are given
below.
A fundamental data type is a data type where the values that it can represent have a
very simple nature (a number, a character). C support mainly 5 Fundamental data
types, and they are given below.
❏ Integer Type
❏ Floating Type
❏ Double Type
❏ Character Type
❏ Void Type
14
❏ Integer Type
Integers are whole numbers with a range of values supported by a particular
machine. The integer data type holds these types of values including positive
negative and zero type numbers.
int
❏ Floating type
Floating point numbers are real numbers with a range of values. It includes
fractional numbers (point values) also. The floating data type holds these types
of values including positive negative and zero type numbers.
float
❏ Double Type
Floating point data type hold only 4bytes of data. If a data comes with more
than that range, an error may arise. To avoid that problem C support another
data types called double type that is much larger range than others.
Representation:
double
❏ Character Type
When we want to store a character value in our program, the above mentioned
data types are not significant. For that purpose C support a character oriented
data type.
Representation :
15
char
❏ Void type
The void type has no value. It returns a null value. In a C program, void type
mostly used in module wise programs. It represents each module’s character.
Representation
void
VARIABLES
A variable is an identifier that denotes a storage location used to store data
value. A variable may take different values at different times during the execution
of the program. All the rules of identifiers must follow when choosing a variable
name.
Eg:
Name
mark1
clg_name
VARIABLE DECLARATION
After designing suitable variable names, must declare them to compiler.
Declaration does two things:
The declaration of variable must be done before they are used in the program.
Syntax:
16
Eg:
int a,b,c;
char gender;
float average_score;
int mark1;
DISPLAY IN C
C supports an output display function called printf(). This function is used to
display a message or value in a given program. It is a built-in function in C library.
Syntax:
printf(“message”);
Eg:
Display state name
printf(“Kerala”); //output:Kerala
Display a fruit name
printf(“MANGO”); //output:MANGO
Display a number
printf(“100”); //output:100
MODULE-2
OPERATORS
17
⚫ Arithmetic Operators
⚫ Relational Operators
⚫ Logical operators
⚫ Assignment Operators
⚫ Increment Decrement Operators
⚫ Conditional Operators
⚫ Bitwise Operators
⚫ Special Operators
Arithmetic Operator
They are :
Addition : To add two operands
Symbol : +
Eg : 52+8
Symbol : -
Eg : 12-2
18
Symbol : *
Eg : 6*3
Symbol : /
Eg : 10/2
Symbol : %
Eg : 5%2 #result=1
Relational Operator
1. == Equal To
To check whether tow operators are equal
10==20 return false
2. != Not Equal To
To check whether two operators are not equal
10!=40 return true
3. > Greater than
To check whether first operand is greater than second operand.
20>87 return false
4. < Less than
To check whether first operand is less than second operand
23<10 return true
5. >= Greater than or equal to
To check whether first operand is greater than or equal to second
operand.
Assignment Operator
This operator used to store right side operand/value in the left side operand.
Syntax:
variablename=value;
variablename=expression;
A=10;
20
Bitwise Operator
These operators perform bit level operation on operands.
x=1010 y= 1100
Logical Operators
These operators are used to check two or more conditions. The resultant is
always a Boolean value.
Conditional Operators
exp1?exp2:exp3;
22
Evaluates exp1
If the exp1 is false, then exp3 is evaluated and return. Here exp2 never be
considered.
⚫ Eg:
result=mark>=40?”pass”:”fail”;
Here if the mark is 87, then it returns pass to result variable, otherwise returns fail
to result variable .
Increment Operators
Syntax ++operand;
operand++;
Eg: a++;
++a;
Two Types:
⚫ Pre Increment
++operand
⚫ Post Increment
23
operand++
Decrement Operator
Syntax:
--operand;
operand--;
Eg:
a--;
--a;
Two Types:
⚫ Pre Decrement
--operand
⚫ Post Decrement
operand--
Example
Output
25
Special Operators
1) Comma operator
2) sizeof() operator
Comma Operator
Eg:
int a;
int b;
int c;
sizeof() operator
Syntax:
sizeof(variablename);
Eg:
int a=10;
sizeof(a);
26
STATEMENT
A statement can be thought as an instruction that can be compiled by the C
compiler. A statement is compiled by the compiler and after execution displays
some results (if it needs).
Eg:
1. mark=98;
2. printf(“KERALA”);
EXPRESSIONS
An expression is a combination of variables, constants and operators. C can
handle any complex mathematical expressions.
27
Eg:
a+b*c
x-y+20
(a+b)/2
a*a
2*a/b
PRECEDENCE OF OPERATORS
When an expression has two or more operators, the system needs to
identify the correct sequence to evaluate these operators. Sometimes the result may
wrong. To avoid this problem, a level of precedence is associated with the
operators. Precedence is the condition that specifies the importance of each
operator relative to others.
1) ( ),[ ]
2) * , / , %
3) + , -
<,<=,>,>=………..
ASSOCIATIVITY
We can see that many operators are having same precedence. In that case,
we use Associativity to evaluate the expression. Associativity is nothing but the
direction in which we evaluate the operators if they have same precedence.
1) Left to Right
28
2) Right to Left
The operator of same precedence is executed from right side first.
Eg:
Expression:
2+5-3
L 2 R:
add 2+5 =7
then 7-3=4
R 2 L:
Subtract 5-3=2
OPERATOR CLASSIFICATION
1. Unary Operator
Unary operators are operators with only one operand.
++ --
Eg:
x=30
--x
29 //output
2. Binary Operator
Binary operators are operators with two operands. They are used to
basic calculations and comparisons.(Arithmetic, Relational, etc)
+ - * / < %
Eg: a=10
29
b=90
a+b
100 //output
3. Ternary Operator
Ternary operators are operators with three operands. They are used
to basic condition checking.(Conditional Operator)
?:
Eg: result=mark>=40?’P’:’F’;
MATHEMATICAL FUNCTIONS
C supports some built-in functions to find the square root, power, sine value
cosine value etc. To add the functionalities of this function in program include the
appropriate Header file from C Library.
#include<math.h>
Basic Functions:
float a,b,result;
clrscr();
printf("Enter The numbers\n");
scanf("%f%f",&a,&b);
31
result=a/b;
printf("Sum=%f\n":result);
getch();
}
scanf(“%d”,&num);
printf(“%d”,num);
answer=getchar();
putchar(answer);
TYPE CONVERSION
The concept of changing one data type to another type in C is known as type
conversion. C supports two types of type conversions
Syntax:
(type)expression;
Eg :
X=(int)7.5 // Result 7
Module-3
1) If statement
2) Switch statement
3) Conditional operator statement
If statement
a) Simple if statement
b) if –else statement
c) else if ladder
d) Nested if –else statement
Simple if statement
36
Syntax:
if (condition1)
statement 1;
statement n;
Eg:
if(3<4)
printf (“Four”);
printf (“Haii”);
Output
Four
Haii
37
if –else statement
Flowchart
Syntax:
if (condition1)
statement 1;
else
statement 2;
statement n;
38
printf((“Four”);
else
printf(“Three”);
printf(“Haii”);
Output
Three
Haii
39
Sytax:
if (condition1)
statement 1;
else if(condition2)
statement2;
else if(condition3)
statement3;
else
statement ;
}
40
⚫ If the condition1 is false go to next line and check the condition2, if it true
execute the statement2 and go to statement n.
⚫ If the every condition is false the last statement in the else block is executed.
Eg:
if(3>4)
printf (“four”);
else if(7>99)
printf (“haii”);
else if(33<44)
printf (“haii”);
else
{
41
Syntax:
if (condition1)
if (condition2)
statement2;
}
else
}
}
statement
else
State
ment
4
}
42
Eg:
if(3<4)
if(4<5)
printf (“4”);
else
printf (“5”);
43
else
printf (“Three”);
}
44
SWITCH STATEMENT
When using the else if ladder statement, the program become difficult
to read and follow. Java supports a multi way decision statement known as switch.
The switch statement tests the value of a given variable against a list of case values
and when a match is found, a block of statements associated with the case is
executed.
Syntax:
switch (expression)
Working
The break statement at the end of each block indicates the end of the
particular case statement. And control transferring out of switch statement.
If none of the case values does not match, the default statement will
execute. It is optional.
Eg:
switch(3)
case 1 : printf(“One”);break;
case 2 : printf(“Two”);break;
case 3:
printf(“Three”);break;
Output
Three
46
The control condition tested before the start of loop statements. If the
condition is false, then loop statements never executed.
The control tested after the looping statement. The Loop statement executes
unconditionally at the first time. After finishing first iteration, if the condition is
false, then loop statements never executed.
47
Looping Structure
for Loop
Syntax:
for(initialization;condition;increment/decrement)
Working
⚫ 4.Condition false: never executes the loop body. Control passed to out of
the for loop
Eg:
for(int i=1;i<=7;++i)
printf(“%d\n”,i);
Output
7
49
while Loop
Syntax:
Initialization;
while(condition)
increment/decrement;
Working
⚫ 4.condition false: never executes the loop body. Control passed to out of the
while loop.
50
Eg:
i=100;
while(i>=97)
printf(“%d\n”,i);
i--;
Output:
100
99
98
97
51
do-while Loop
Syntax:
Initialization;
do
increment/decrement;
while(condition);
Working
a=3
0;
do
{
printf(
“%d,”,
a);
++a;
}
while(a<35);
Output
30,31,32,33,34
Syntax:
for(initialization1;condition1;increment1/decrement1)
Working
⚫ d.Condition2 false: stops the execution of inner loop body. Control passed
to outer for loop’s increment/decrement section
⚫ Update the value and test condition1 and if it is true go to inner loop and so
on
⚫ 4.condition true false: never executes the loop body. so inner loop also stop
its execution. Control passed to out of the for loop
Eg:
for(i=1;i<=3;++i)
for(j=3;j>=1;--j)
printf("i=%d j=%d\n",i,j);
}
54
Output
JUMPS IN LOOP
Loop performs a set of operations repeatedly until the condition fails.
Sometimes, when executing a loop it becomes desirable to skip the loop or a part
of the loop. The jumping statements are used for this purpose. They are:
When the loops are nested, the break would only exit from the loop
containing it. That is it will exit only a single loop.
Syntax:
break;
The goto can transfer the control to any place in a program. Another use
of goto statement is to exit from entire loop if it nested. The break statement
would not work like this.
………………..
Label :
56
This statement causes the loop to be continued with the next iteration after
skipping any statement in between. Skip the following statements and continue
with the next iteration. Java support a statement called continue for this
purpose.
Syntax:
continue;
57
Example
for(i=1;i<=5;++i)
if(i==3)
continue;
printf(“%d\n”,i);
Output
5
58
Module-4
59
ARRAYS
An array is a group of contiguous or related data items that share a common
name. An array can be used to represent a list of numbers, names etc. It uses
one variable name and multiple data. So each data represented by its
location. Array location indicated as index or subscript. The values in an
array named as elements.
A list of items can be given one variable name using only one
subscript/index and such a variable is called one dimensional array. The Symbol []
is used for array representation. The array index starts at 0th location.
Here,
arr[0]=10
arr[1]=20
60
arr[2]=30
arr[3]=40
arr[4]=50
‘arr’ means the array name and the 0,1,2 etc are the indices of the array ‘arr’.
The 10, 20 ,30 etc are the data hold in the array named ‘arr’
Declaration Syntax:
datatype arrayname[size];
Eg:
int a[100];
float avg[50];
char name[100];
Assign values to an array means insert data into the corresponding array.
Like variables, we can assign values to an array in two ways.
Syntax:
1)
arrayname[index]=value;
2)
datatype arrayname[size]={value1,valu2,value3………};
Eg:
A[0]=12;
int mark[10]={67,98,78};
Insert data into the array at program execution time. scanf() function is used for
run time reading. By using scanf() and looping statements we can insert elements
to an array at run time.
int a[10];
for(i=0;i<10;++i)
scanf(“%d”,&a[i]);
}
62
Here,
a= array name
Array Limit
At the time of declaration of an array the size should be mentioned. If the
programmer cannot used much size he can set the wanted size at runtime. To
set that, an variable is used and store particular size the programmer want.
int a[20];
printf(“Enter the Limit of array\n”);
scanf(“%d”, &n);
for(i=0;i<n;++i)
scanf(“%d”,&a[i]);
here, n is the limiting variable. The size is 20, but the array variable a can
store only the specified number n.
ARRAY OPERATIONS
⚫ Traversal
⚫ Searching
⚫ Sorting
Traversal
Traversal means that visiting each location of the array. That is just
displaying all elements is known as traversing. For this printf() function can used.
63
Example
Searching
Searching means to check the specified data value is present in the given array. If
it present just display the location.
Process
⚫ item present before last location : but, loop never stops its execution until the
condition false.
⚫ if the item found , then Set a variable , and break the loop.
⚫ After the loop statement, check the already used variable. And display the
result
Example
64
Sorting
Example
65
Declaration
datatype arrayname[row_size][column_size];
Eg:
int a[10][10];
float matrix[20][30];
Initialization
Compile Time
1)
arrayname[row][column]=value;
Eg: arr[0][0]=10;
66
arr[1][2]=22;
2)
datatype arrayname[rowsize][columnsize]={{R1values},{R2values}….};
000
111
Run Time
int a[10][10];
for(i=0;i<10;++i)
for(j=0;j<10;++j)
scanf(“%d”,&a[i][j]);
} }
STRINGS
A string is a sequence of characters that is treated as a single data item. It
represent in double quotes.
Eg: “hai”
67
The compiler automatically supplies a ‘\0’ character to the end of every string.
Declaration
Syntax:
char string_name[size];
Eg:
char name[25];
char college[50];
Initialization
⚫ Compile time
char variablename[size]=“string”;
Eg:
char name[10]=“RAJU”;
Representation:
R A J U \0 \0 \0 \0 \0 \0
68
Example
Run Time
scanf() function is used to read run time initialization. Here the control
string is %s
Syntax:
scanf(“%s”,variable);
eg:
char name[20];
scanf(“%s”,name);
69
Example
Syntax:
char variablename[size];
gets(variable);
Eg:
char fullname[50];
gets(fullname);
70
Syntax:
puts(variablename);
Eg:
puts(fullname);
Example
Syntax:
#include<string.h>
71
This function is used to compare the two given strings are equal or not. It
return 0 when the given strings are equal.
Syntax:
strcmp(string1,string2);
This function is used to store right side contained string to left side.
Syntax:
strcpy(string1,string2);
This function is used to find the length of a string. That means, it return the
number of characters in a given string. It also include space.
Syntax:
strlen(string);
Eg:
strlen(“snc vtk”);
Result : 7
Syntax:
strcat(string1.string2)
Eg:
strcat(“haii”,”hello”);
result: haiihello
STRUCTURES
C Supports a constructed data type called structure. A structure is a powerful
tool to store data values of different types. That means, unlike an array a structure
can store integer, floating, character etc data values in a single unit.
DEFINING A STRUCTURE
The keyword struct is used to define a structure. The structure contains a
structure name (structure tag), structure members and a structure variable.
Syntax
struct structure_tag
datatype variables;
datatype variables;
…………..
};
73
Eg:
struct book
char title[50];
char author[25];
int pages;
float price;
};
STRUCTURE VARIABLE
It is used to access the members of a structure. In C program structure
variable can create in two ways.
1)
struct structure_tag
datatype variables;
datatype variables;
…………..
}structurevariable;
Example
struct book
char title[50];
char author[25];
int pages;
float price;
} b1,b2;
Syntax:
svariable.variable=value;
scanf(“controlstring”,&svariable.variable);
printf(“controlstring”,svariable.variable);
Example
UNIONS
Unions are concept borrowed from structure and therefore follow the similar
syntax as structure. Use the keyword union. Like structure union variable is used
to access the union members.
Example
⚫ Structure Members :
rollno : integer : 2 bytes
76
⚫ Union Members:
rollno : integer : 2 bytes
name : character : 1 byte
union union_name
datatype variable1;
datatype variable2;
………….
} union_variable;
union student
int rollno;
float avg_mark;
77
char gender;
} s1;
Size: 4
Syntax:
unionvariable.variable=value;
scanf(“controlstring”,&unionvariable.variable);
printf(“controlstring”,unionvariable.variable);
Example:
scanf(“%d”,&s1.rollno);
printf(“%d”,s1.rollno);
78
C functions can be classified into two categories. Library function and user
defined function. The difference is, library functions are not required to be written
by programmer, where as user-defined function are to be written by the
programmer.
The program may become too large and complex as of a result the task of
debugging testing etc become difficult. If a program is divided into functional parts
then each part may be independently coded and later combined into a single unit.
These independently coded programs are called sub programs that are much easier
to understand in C. Such sub programs are called Functions.
ADVANTAGES
FUNCTION DECLARATION
All functions in C must be declared like variables, before they are invoked
(called). It consists of the following parts:
d) Semicolon
Syntax:
Eg:
void display();
int add();
float sub(int,int);
FUNCTION CALL
Syntax:
functionname(argument list);
Eg:
display();
In the time of function call, the control of the program is transferred to the called
function. After the execution of function is completed it transferred back to the
calling area.
81
FUNCTION DEFINITION
When calling a function the corresponding code will executed for the
program. That program block is called function definition. It consists of following
parts:
a) Return type
b) Function name
c) Parameter list(argument list)
d) Variable declaration\
Syntax:
variable declaration;
program statements;
…………………..
……………………
return statement;
}
Eg:
void display()
82
int a=10;
printf(“a=%d”,a);
RETURN VALUE
A function may or may not send back any value to the calling function. If it
sends, it is done by the return statement.
Syntax:
return value/variable;
The return value goes to the calling function with corresponding return type. The
return type of the function is based on the return value.
Types:
Example
CATEGORY OF FUNCTION
Argument : value passed to the user defined function
Return value: value passed to the calling side from user defined function
Based on the number of arguments and return type a user defined function
can be categorized into the following:
When a function has no argument, it does not receive any data from the
calling function. Also when it does not return a value, the calling function does not
receive any data from the called function.
Syntax:
void functionname()
………………………
…………………………
}
85
Here, the function does not return any value. But the calling function is send
some arguments to the called function.
Syntax:
void functionname(arguments)
……………………
…………………….
………………………
}
86
Eg:
Syntax:
returntype functionname(arguments)
……………………
…………………….
………………………
}
⚫ Return integer value
int functionname(…)
float functionnanme(…..)
char functionname(….)
Eg:
88
This type of function consists of no argument list in the time of call. But
after the execution of function it returns a value back to the calling side.
Syntax:
returntype functionname()
……………………
…………………….
………………………
return value
Eg:
89
The mechanism that is used in the C program for return multiple value is by
using the address operator(&), which indicates the address of the given variable
names.
90
Eg:
91
NESTING OF FUNCTION
Syntax:
void main()
………………………….
function1();
…………………………
{ …………………
function2();
………………….
…………………………..
}
92
Here the main function calls the sub function named function1(), and in the
execution of first function it calls the second sub function named function2().
Eg:
CHAINING
When a function calls another function, and it calls some another function
and so on, this process of calling is known as chaining.
93
RECURSION
Syntax:
returntype function1(argument list);
void main()
………………………….
function1();
…………………………
{ …………………
function1();
………………….
Eg:
94
⚫ Output
Enter the number
5
They are
actual argument.
Eg:
int a,b;
display(a,b);
Formal Argument
⚫ Eg:
CALL BY VALUE
The process of passing actual value of the variable is called call by value.
Here when passing the argument, only one copy of that variable is passed to the
called function. So if there any change made in the formal argument occurred in
the function definition, it will note affected in the actual arguments.
Eg:
#include<stdio.h>
#include<conio.h>
void sample(int);
void main()
int a;
clrscr();
scanf(“%d”,&a);
print(“a=%d”,a);
getch();
x=x+2;
printf(“x=%d\n”,x);
97
OUTPUT
x=6
a=4
here the value of the variable ‘a’ didn’t change after the execution of sample()
function. It remains the same.
CALL BY REFERENCE
The process of calling a function using pointers to pass the address of the
variables is known as call by reference. The function which is called by reference
can change the value of the variable used in the call(actual variable).
Eg:
#include<stdio.h>
#include<conio.h>
void main()
int a;
clrscr();
scanf(“%d”,&a);
98
print(“a=%d”,a);
getch();
*x=*x+2;
printf(“x=%d\n”,*x);
OUTPUT
x=6
a=6
Here the value of the variable ‘a’ changed after the execution of sample() function.
It remains the same of the formal argument, because here pass the address along
with the value. So changes can be made.
STORAGE CLASSES
C supports a verity of variables in the program coding. The scope, visibility
and life time of these variables are different.
1. Automatic Variable
99
2. External Variable
3. Static Variable
4. Register Variable
AUTOMATIC VARIABLE
They are declared inside a function in which they are to be utilized. They
created automatically when the function is called and destroyed automatically
when function is exited. They are also known as local variable or internal variable.
It may use the keyword auto.
Syntax:
datatype variablename;
or
Eg:
int a;
auto int b;
Example
10
0
EXTERNAL VARIABLE
Variables that are active throughout the entire program are known as
external variable. It is also known as global variable. It can be accessed not only
the specific function but also by any function in the program. They are declared
outside the function. It may use the keyword extern.
Syntax:
datatype variablename;
or
Eg:
int a;
extern int c;
Example
10
2
STATIC VARIABLE
The variable value persists until the end of the program as it declared as
static. It can be declared using the keyword static.
Syntax:
Local Type:
Global Type:
Example
10
4
10
5
REGISTER VARIABLE
To kept the variable in one of` the machine’s register, we use the register
variable. It can be declared using the register keyword.
Syntax:
Eg:
register int b;
MODULE - 5
POINTERS
1- UNDERSTANDING POINTERS
.
.
.
.
.
.
.
.
.
65789
Representation
quantity ← variable
179 ←value
5000 ←address
The actual location of a variable in the memory is system dependent and the
address of a variable is not known immediately. This can be done with the help of
the operator & available in C. It is already used in the scanf function in C. The
operator & immediately preceding a variable returns the address of the variable
associated with it.
Eg:
p=&quantity;
& - address of
Syntax :
datatype *pointer_name;
10
Eg :
Eg:
int quantity;
int *p;
p=&quantity;
here the variable p holds the address of the another variable quantity.
If a pointer has been assigned the address of a variable using pointer, and we
want to access its value, C support an operator * . Consider the following code
quantity= 179;
p= &quantity;
n=*p;
quantity - 179
n - 179
10
6- POINTER EXPRESSIONS
Like the other variables pointer variables can be used in expressions. All
arithmetic , increment, decrement etc operation should perform with the pointer
variables. Here the data types of each variable should match.
Eg:
Y=*p1+*p2;
E=sum+*t1;
*p=*p1++;
*u=10+*t;
Eg:
int x[5]={1,2,3,4,5};
int *p;
p=&x[0];
Eg:
char *str=”good”;
this creates a string of literal and then stores its address in the pointer variable str.
The pointer str points to the first character of the string “ good”.
They are
3) CALL BY VALUE
4) CALL BY REFERENCE
CALL BY VALUE
The process of passing actual value of the variable is called call by value.
Here when passing the argument, only one copy of that variable is passed to the
called function. So if there any change made in the formal argument occurred in
the function definition, it will note affected in the actual arguments.
Eg:
#include<stdio.h>
#include<conio.h>
10
void sample(int);
void main()
int a;
clrscr();
scanf(“%d”,&a);
print(“a=%d”,a);
getch();
x=x+2;
printf(“x=%d\n”,x);
OUTPUT
x=6
a=4
10
here the value of the variable ‘a’ didn’t change after the execution of sample()
function. It remains the same.
CALL BY REFERENCE
The process of calling a function using pointers to pass the address of the
variables is known as call by reference. The function which is called by reference
can change the value of the variable used in the call(actual variable).
Eg:
#include<stdio.h>
#include<conio.h>
void main()
int a;
clrscr();
scanf(“%d”,&a);
print(“a=%d”,a);
getch();
*x=*x+2;
10
printf(“x=%d\n”,*x);
OUTPUT
x=6
a=6
here the value of the variable ‘a’ changed after the execution of sample() function.
It remains the same of the formal argument, because here pass the address along
with the value. So changes can be made.
The pointers are also used in the structures. It can be achieved by the use of
* operator and operator (arrow operator). The structure variable can be
represented by the pointer ( * ) and also the structures members are accessed by the
operator.
struct student
int no;
char name[30];
}*ptr;
void main()
{
10
scanf(“%d%s”,&ptrno,ptrname);
printf(“Name =%s\n”,ptrname);
printf(“Number=%d”,ptrno);
FILE MANAGEMENT
To perform operations on file, first open the file for that purpose. It
includes:
a) Filename
b) Data structure
c) Purpose
Declaring a file
Syntax:
FILE *filepointer;
Eg:
FILE *f1;
10
FILE *f2,f3;
Opening a file
Eg:
FILE *fp;
fopen(“filename”,”mode”);
It opens the named file and assign the file pointer fp to the file location.
MODE
It specifies the purpose of opening the file. The mode can be on the
following:’
Eg:
FILE *f1;
Closing a file
Syntax:
fclose(filepointer);
Eg:
fclose(f1);
a) putc()
Suppose a file is opened with write mode(w) and the file pointer is f1.
Then if we want to write a character to that file =>
putc(c,f1);
here, c indicates the variable that hold the single character.
b) getc()
Suppose a file is opened with read mode(r) and the file pointer is f1.
Then if we want to read a character from the file =>
c=getc(f1);
the getc(f1) read a single character from the file f1 and it stored to the
another variable c.
here f1 is the file pointer, num is the integer value that write to the
file.
b) getw()
Used to read an integer value from the specified file.
o Num=getw(f1);
Here getw() read an integer value from the f1 pointed file and stored
into the variable Num.
1) fprintf()
It is similar to printf() function. But here specifies the file pointer also.
Syntax:
fprintf(fp,”controlstring”,list);
Eg:
fprintf(f1,”%d%f”,num,ratio);
2) fscanf()
Similar to the scanf() function. But here specifies the file pointer also.
Syntax:
fscanf(fp,”controlstring”,list);
Eg:
fscanf(fp,”%d”,&num);
It indicates the end of the file. That is the last content of a file is indicated .
11
Eg:
Every C program should contain main() function and it marked the beginning of
the program. The main() can take 2 parameter(argument) like argc, argv.
The argc is an argument counter that counts the number of arguments on the
command line. The argv is an argument vector and represents an array of character
pointers that point to the command line argument.
argv[0]-> PROGRAM
argv[1]->X_FILE
argv[2]->Y_FILE
}
11
1) Static
2) Dynamic
In static allocation, no additional memory are allocated during running a
program and no extra memory can release to that time.
Eg: Array
In Dynamic, these 2 operations can be performed.
Eg: Linked List.
Dynamic Allocation
1) malloc()
11
Syntax:
eg:
p=(char *)malloc(10);
2) calloc()
It is normally used for requesting memory space of runtime for storing array
and structure. It is used to allocate multiple blocks of memory.
Syntax:
ptr=(type *)calloc(n,size);
eg:
ptr=(record *)calloc(class_size,sizeof(record));
here record=> structure variable.
3) free()
To release the unwanted space during execution time use the free()
function.
Syntax :
free(ptr);
Eg: free(p);
4) realloc()
The previously allocated memory is not sufficient and need to
additional space for more element, C supports the realloc() function.
Syntax:
ptr=malloc(size);
ptr=realloc(ptr,newsize);
Eg:
ptr=malloc(20);
ptr=realloc(ptr,40);
**************************************************************