CSC3C03-Problem Solving Using C
CSC3C03-Problem Solving Using C
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
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.
3
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.
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.
Debugging: The process of identifying and removing errors (mistakes) from program
Testing: The process of executing a program with the intent of finding errors.
4
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
{
Declaration Part
Executable Part
}
Subprogram Section
Function1
Function2
Function3 (User Defined Functions)
…………..
……………
Function n
1) Documentation Section
5
2) Link Section
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
6
CHARACTER SET
The task of processing of data is accomplished by executing a sequence of
instructions is called a PROGRAM. These instructions are formed using certain
symbols and words according to some rules known as SYNTAX
RULES(Grammar).
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
Special Characters
Horizontal Tab, newline space, blank space …. are considered to white spaces
C TOKENS
Normally, individual words and punctuation marks are called tokens. In a C
program the smallest individual units are known as C TOKENS. C has six types of
tokens. They are given below.
Keywords
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
OPERATORS
9
Operators are symbols that are used to represent a mathematical calculation or logical
comparison.
5+9
X+Y
m>n
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
10
❏ 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 :
11
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:
12
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 a number
printf(“100”); //output:100
OPERATORS
Operators are symbols that are used to represent a mathematical calculation,
logical comparison etc. Based on the functionality, C operators are categories into the
following eight types.
Arithmetic Operators
Relational Operators
Logical operators
Assignment Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operator
They are :
Symbol : +
Eg : 52+8
Symbol : -
14
Eg : 12-2
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.
15
Assignment Operator
This operator used to store right side operand/value in the left side operand.
Syntax:
variablename=value;
variablename=expression
A=10
Bitwise Operator
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;
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++;
17
Eg:
a++;
++a;
Two Types:
Pre Increment
++operand
Post Increment
operand++
Decrement Operator
Syntax:
--operand;
operand--;
Eg:
a--;
--a;
Two Types:
18
Pre Decrement
--operand
Post Decrement
operand--
Example
Output
19
Special Operators
1) Comma operator
2) sizeof() operator
Comma Operator
The comma operator mainly used to separate variables in a program. And also
used in iteration statements.
Eg:
int a;
int b;
int c;
int a,b,c;
20
sizeof() operator
Syntax:
sizeof(variablename);
Eg:
int a=10;
sizeof(a);
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.
Eg:
a+b*c
x-y+20
21
(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
2) Right to Left
The operator of same precedence is executed from right side first.
Eg:
Expression:
22
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
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)
?:
23
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:
scanf("%d%d",&a,&b);
result=a+b;
printf("Sum=%d\n":result);
result=a-b;
printf("Difference=%d\n":result);
result=a*b;
printf("Product=%d\n":result);
result=a%b;
printf("Reminder=%d\n":result);
root=sqrt(a);
printf("Square Root=d\n":root);
getch();
}
2. C program to perform division.
#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,result;
clrscr();
printf("Enter The numbers\n");
scanf("%f%f",&a,&b);
result=a/b;
printf("Sum=%f\n":result);
getch();
}
scanf(“%d”,&num);
printf(“%d”,num);
answer=getchar();
26
putchar(answer);
response is: Y
Module-2
DECISION MAKING STATEMENTS
When a program breaks the sequential flow and jumps to another part of the
code is called branching. When the branching is based on a particular condition it is
called conditional branching statements. It is also called Selection statements.
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
28
Syntax:
if (condition1)
statement 1;
statement n;
Eg:
if(3<4)
printf (“Four”);
printf (“Haii”);
Output
Four
Haii
29
if –else statement
Flowchart
Syntax:
if (condition1)
statement 1;
else
statement 2;
statement n;
30
if(3>4)
printf((“Four”);
else
printf(“Three”);
printf(“Haii”);
Output
Three
Haii
31
Sytax:
if (condition1)
statement 1;
else if(condition2)
statement2;
else if(condition3)
statement3;
else
statement ;
statement n;
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.
32
Eg:
if(3>4)
printf (“four”);
else if(7>99)
printf (“haii”);
else if(33<44)
printf (“haii”);
else
}
33
Syntax:
if (condition1)
if (condition2)
statement2;
else
statement3;
else
statement 4;
statement n;
Eg:
if(3<4)
if(4<5)
printf (“4”);
else
printf (“5”);
else
printf (“Three”);
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.
35
Syntax:
switch (expression)
………………………………………….
………………………………………….
default : statement n;
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;
Output
Three
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.
Looping Structure
for Loop
Syntax:
for(initialization;condition;increment/decrement)
Working
b)increment/decrement section.
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);
}
38
Output
while Loop
Syntax:
Initialization;
while(condition)
increment/decrement;
}
39
Working
4.condition false: never executes the loop body. Control passed to out of the
while loop.
Eg:
i=100;
while(i>=97)
printf(“%d\n”,i);
i--;
Output:
100
99
98
97
40
do-while Loop
Syntax:
Initialization;
do
increment/decrement;
while(condition);
Working
5.Condition false : never executes the loop body. Control passed to out of the
while loop
Eg:
a=30;
do
printf(“%d,”,a);
++a;
while(a<35);
Output
30,31,32,33,34
Syntax:
for(initialization1;condition1;increment1/decrement1)
for(initialization2;condition2;increment2/decrement2)
}
42
Working
b)increment2/decrement2 section.
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);
}
43
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;
44
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 :
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;
45
Example
for(i=1;i<=5;++i)
if(i==3)
continue;
printf(“%d\n”,i);
Output
5
46
Module-3
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
47
arr[1]=20
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.
Insert values to the array at the time of program creation is called compile time
initialization.
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]);
}
49
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.
50
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
51
Sorting
Example
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;
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”
The compiler automatically supplies a ‘\0’ character to the end of every string.
Declaration
Syntax:
54
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
Example
55
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);
Example
Syntax:
char variablename[size];
gets(variable);
Eg:
char fullname[50];
gets(fullname);
Syntax:
puts(variablename);
Eg:
puts(fullname);
Example
57
Syntax:
#include<string.h>
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
58
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;
…………..
};
59
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 :
Union Members:
Syntax:
union union_name
datatype variable1;
datatype variable2;
………….
} union_variable;
union student
int rollno;
float avg_mark;
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);
64
Module-4
USER DEFINED FUNCTION
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:
Syntax:
Eg:
void display();
int add();
float sub(int,int);
FUNCTION CALL
Syntax:
functionname(argument list);
66
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.
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;
}
67
Eg:
void display()
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()
………………………
…………………………
}
70
Here, the function does not return any value. But the calling function is send
some arguments to the called function.
Syntax:
void functionname(arguments)
……………………
…………………….
………………………
}
71
Eg:
In this type of function, two way communication process is occur. That means,
when calling the function there should transmit a value to the called function and after
the execution of called function it returns a value back to the calling side.
Syntax:
returntype functionname(arguments)
……………………
…………………….
………………………
}
Return integer value
int functionname(…)
72
float functionnanme(…..)
char functionname(….)
Eg:
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
}
73
Eg:
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.
74
Eg:
75
NESTING OF FUNCTION
Syntax:
void main()
………………………….
function1();
…………………………
{ …………………
function2();
………………….
…………………………..
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().
76
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.
RECURSION
Syntax:
returntype function1(argument list);
void main()
………………………….
function1();
…………………………
{ …………………
function1();
………………….
Eg:
78
Output
They are
actual argument.
Eg:
int a,b;
display(a,b);
79
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);
80
print(“a=%d”,a);
getch();
x=x+2;
printf(“x=%d\n”,x);
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);
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.
82
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
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;
83
Example
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
85
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
87
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
89
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
90
Syntax :
datatype *pointer_name;
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;
91
p= &quantity;
n=*p;
quantity - 179
n - 179
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;
92
p=&x[0];
FILE MANAGEMENT
A file is a place on the disk when a group of related data is stored. C
supports a number of functions that have the ability to perform basic file
operations. These includes:
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;
FILE *f2,f3;
93
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);
94
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.
96
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()
Allocates requested size of memory. Here, a block of memory may be
allocated using the function malloc(). It reserves a block of memory
that specifies the space.
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);